Skip to content

Instantly share code, notes, and snippets.

@jacobsmith
Created October 31, 2016 13:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobsmith/29918bc1abe0276f9f0b19fd9a8c6311 to your computer and use it in GitHub Desktop.
Save jacobsmith/29918bc1abe0276f9f0b19fd9a8c6311 to your computer and use it in GitHub Desktop.
Allow fuzzy matching of contiguous letters (i.e. `co mas` would do `git checkout master`)
branch=$( git branch | tr -d '*' | grep $1 )
current_branch() {
echo $(git rev-parse --abbrev-ref HEAD)
}
starting_branch=$(current_branch)
# This function lists all branches with an index (starting at 1)
list_all_branches() {
let i=1
for branch_name in $branch
do echo "$i) $branch_name"
(( i = i + 1 ))
done
}
# Helper method to print an error message if git checkout did not succeed
ensure_success() {
# rather than checking error code, we check that our git branch is different
# becuase git can "checkout" a file or path, just like a branch
if [ $starting_branch == $(current_branch) ]; then
echo
echo "Oops! Looks like something went wrong. Please try again!"
fi
}
checkout_branch() {
input=$1
let i=1
for branch_name in $branch
do if [[ $i -eq $input ]]; then
git checkout $branch_name
ensure_success $?
exit;
else
(( i = i + 1 ));
fi
done
}
num_of_branches_found=$(echo $branch | wc | awk '{printf $2}')
if [[ $num_of_branches_found -eq 0 ]]; then
echo "Did not find a branch with that string (Double check your spelling)"
exit
elif [[ $num_of_branches_found -gt 1 ]]; then
echo "Oops! More than one branch by that name found, please be more specific in your search..."
list_all_branches
read -p "Select one of the numbers above, or enter q to exit: " input
echo
case $input in
[q]* ) exit;;
[0-9]* ) checkout_branch $input;;
* ) echo Next time, enter 'q' or a digit
esac
exit
fi
# If we get to here, we only got one match (:
git checkout $branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment