Skip to content

Instantly share code, notes, and snippets.

@chx
Last active September 21, 2021 07:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chx/3a694c2a077451e3d446f85546bb9278 to your computer and use it in GitHub Desktop.
Save chx/3a694c2a077451e3d446f85546bb9278 to your computer and use it in GitHub Desktop.
my git
function git() {
# Path to the `git` binary
GIT="/usr/bin/git"
# Sanity check
if [ ! -f ${GIT} ]
then
echo "Error: git binary not found" >&2
return 255
fi
# Command to be executed
command=$1
# Remove command from $@ array
shift 1
# Check command against list of supported commands
case $command in
"cd")
cd $(git rev-parse --show-toplevel)/${1}
;;
"ch")
cut -f2- $(git rev-parse --git-dir)/logs/HEAD |tac|awk '$1=="checkout:" { print $NF }'
;;
"push")
if [ -z "$1" ]
then
$GIT push || $GIT push -u origin $($GIT rev-parse --abbrev-ref @)
else
$GIT ${command} "$@"
fi
;;
"reset")
if [ "$1" = "--hard" ]
then
$GIT add -u
if $GIT commit -m "Saving state before hard reset"; then
# only create a backup ref & perform a reset if
# a commit was created (otherwise there's nothing
# to reset!)
backupRef="refs/reset-backups/`date +%s`"
$GIT update-ref $backupRef HEAD
$GIT reset --hard HEAD~1
echo "Created backup ref: $backupRef"
fi
if [ -n "$2" ]
then
$GIT reset --hard $2
fi
else
$GIT ${command} "$@"
fi
;;
*)
# Execute the git binary
$GIT ${command} "$@"
;;
esac
# Return something
return $?
}
@brandonchinn178
Copy link

When you type in git foo, git will first look for a command on PATH named git-foo. So you could break these out into separate scripts (e.g. git-cd) and itll just work without needing to wrap git

@chx
Copy link
Author

chx commented Sep 21, 2021

@brandonchinn178 that works for git cd etc but not for git reset IMO.

@brandonchinn178
Copy link

Sure, but you could always just use a different name. e.g. I just have git p aliased to git push --force-with-lease, and i almost never use git push anymore. (im not sure what your usecase for the reset command is, but i have a git wip command thats basically an alias for git add . && git commit -m wip --no-verify which i use a lot)

Also, cant you define your cd subcommand using gitconfig aliases?

@chx
Copy link
Author

chx commented Sep 21, 2021

Nope, that doesn't work either. This is the only way AFAIK to override a built in git command. And I don't want to retrain myself to use an alias -- it defeats the purpose, the moment you slip will be the moment when you shouldn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment