Skip to content

Instantly share code, notes, and snippets.

@hannestyden
Created January 18, 2013 11:00
Show Gist options
  • Save hannestyden/4563896 to your computer and use it in GitHub Desktop.
Save hannestyden/4563896 to your computer and use it in GitHub Desktop.
# Git Navigation
#
# By Hannes Tydén <hannes@tyden.name> @pht
#
# Navigate backwards and forwards in your Git history.
#
# Inspired by https://twitter.com/avdi/status/292057753088827392
#
# Tested on
# zsh 5.0.2 (x86_64-apple-darwin12.2.1)
# git version 1.8.1
git-backward() {
git checkout HEAD~
}
git-forward () {
children=$(git-children)
child_count=$(echo $children | grep . | wc -l | git-support-trim)
if [[ $child_count -eq 1 ]]
then
git checkout $children
else
echo "Cannot go forward"
echo "$(git-sha) has $child_count children"
if [[ $child_count -eq 0 ]]
then
tips=$(git-branch-leaf-shas | grep '^\*' | sed 's/^\* *//')
if [[ $(echo $tips | grep . | wc -l | sed 's/ *//') -ne 0 ]]
then
echo Also HEAD is the leaf of
echo $tips
fi
else
for child in $(echo $children)
do
echo "$child ($(git-status-in-branches $child | git-support-collapse | git-support-trim))"
done
echo
echo " git checkout <sha> to continue ..."
echo
fi
fi
}
git-sha () {
git log --format=format:%H --max-count 1 $@
}
git-children () {
# http://stackoverflow.com/questions/1761825/referencing-the-child-of-a-commit-in-git
treeish=$1
git rev-list --parents --all $treeish | grep " $(git-sha $treeish)" | cut -d ' ' -f 1
}
git-branch-leaf-shas () {
git branch -v --no-abbrev | grep -v '(no branch)' | sed -E 's/^[* ] ([^[:space:]]+)[[:space:]]+([[:alnum:]]+).*/\2 \1/'
}
git-leaf-in-branches () {
sha=$(git-sha $1)
git-branch-leaf-shas | grep $sha | sed "s/${sha}[[:space:]]*//"
}
git-status-in-branches () {
# * infront of the branch name indicates that the sha is the leaf of the branch
sha=$(git-sha $1)
comm -1 <(git-leaf-in-branches $sha) <(git branch --contains $sha | grep -v '(no branch)' | sed 's/[[:space:]]*//') | sed -E 's/^[[:space:]]+/*/'
}
git-support-trim () {
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}
git-support-collapse () {
tr '\n' ' ' | sed -E 's/[[:space:]]+/ /'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment