pantry/projects/git-scm.org/git-shim
Fredrik Averpil fb3e0f2ac1
Improve git subcommand detection (#4121)
* refactor: improve git subcommand detection

* fix: remove redundant case
2023-11-18 16:11:49 -05:00

60 lines
1.5 KiB
Bash
Executable file
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/sh
set -e
# This function searches through the provided arguments
# to find the first non-option argument, which is assumed
# to be the git subcommand.
find_git_subcommand() {
skip_next=0 # Flag to indicate if the next argument should be skipped.
for arg in "$@"; do
# If the skip_next flag is set, skip this argument.
if [ "$skip_next" -eq 1 ]; then
skip_next=0
continue
fi
# Check for options that require skipping the next argument.
case $arg in
-C | --git-dir | --work-tree | --namespace | --super-prefix | --config-env | -c)
skip_next=1 # The next argument is a value for these options.
continue
;;
-*)
continue # Skip other options that start with '-'.
;;
esac
# If we reach this point, it's likely the git subcommand.
echo "$arg"
return
done
}
libexec="$(cd "$(dirname "$0")/.." && pwd)"/libexec
# extract the git subcommand
cmd=$(find_git_subcommand "$@")
_provides() {
if foo="$(pkgx --provider git-"$cmd")"; then
echo "$foo"
else
# syncing is slow but lets be sure about it
pkgx --sync --provider git-"$cmd"
fi
}
if [ -z "$cmd" ]; then
exec "$libexec/git" "$@"
elif [ -x "$libexec/git-$cmd" ] && [ -f "$libexec/git-$cmd" ]; then
exec "$libexec/git" "$@"
elif type "git-$cmd" >/dev/null 2>&1; then
exec "$libexec/git" "$@"
elif command -v pkgx >/dev/null 2>&1 && pkg=$(_provides); then
exec pkgx +"$pkg" "$libexec/git" "$@"
else
exec "$libexec/git" "$@"
fi