Skip to content

Instantly share code, notes, and snippets.

@kevupton
Last active February 18, 2019 22:15
Show Gist options
  • Save kevupton/99b6d1a6db0cfd01f6425bba76def5de to your computer and use it in GitHub Desktop.
Save kevupton/99b6d1a6db0cfd01f6425bba76def5de to your computer and use it in GitHub Desktop.
Checkouter
#!/bin/bash
command=$(basename $0)
usage() { printf "Usage: ${BLUE}$command${NC} ${RED}[search-term]${NC} ${GREEN}[-f]${NC}\n" 1>&2; exit 1; }
CODE=$1
TMP=~/.xc
TIME_CHANGE=3600
RED='\033[0;33m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
if [ -z "$CODE" ]; then
usage;
# echo "Please enter a code to checkout"
exit 1
fi
git rev-parse --verify "remotes/origin/$CODE" > /dev/null 2>&1 && {
git checkout $CODE
exit 0
}
NAME=$(git config --get remote.origin.url | sed -E "s/http|https|[:\/@._]|-//g" || {
echo "Not a git repository..."
exit 1
})
FILENAME="$TMP/$NAME"
OPTIND=2
while getopts ":f" o; do
case "${o}" in
f)
rm $FILENAME > /dev/null 2>&1
;;
*)
;;
esac
done
CURRENT_TIME=$(date +%s)
EXISTING_TIME=$((date -r "$FILENAME" "+%s" 2>&1 || echo 0) | tail -1)
DIFF=$(expr $CURRENT_TIME - $EXISTING_TIME)
if (( DIFF > TIME_CHANGE )); then
echo "Fetching Updates..."
git fetch --all > /dev/null || exit 1
mkdir -p $TMP
rm $FILENAME > /dev/null 2>&1
touch $FILENAME
echo "------------------"
echo
fi
BRANCHES=$(git branch --all | sed -n "s/remotes\/origin\/\(.*$CODE.*\)/\1/p")
LINES=$(echo "$BRANCHES" | wc -l | awk '{$1=$1};1')
if (( LINES > 1 )); then
printf "${RED}$LINES${NC} branches found for '$CODE':\n"
i="0"
echo "$BRANCHES" | while read -r line ; do
printf " - ${GREEN}$line${NC}\n"
i=$(expr $i + 1)
if (( i > 10 )); then
echo " ..."
break
fi
done
printf "\nPlease narrow your search term.\n"
exit 1
fi
BRANCH=$(echo $BRANCHES | awk '{$1=$1};1')
if [ -z "$BRANCH" ]; then
printf "No branches found using '${RED}$CODE${NC}'\n"
exit 1
fi
if [[ "$BRANCH" =~ ^\s*\*\s*(.*)$ ]]; then
BRANCH=${BASH_REMATCH[1]}
else
BRANCH="$BRANCH"
fi
if [[ "$BRANCH" =~ ^\s*remotes\/origin\/(.*)$ ]]; then
BRANCH=${BASH_REMATCH[1]}
else
BRANCH="$BRANCH"
fi
BRANCH=$(echo "$BRANCH" | awk '{$1=$1};1')
git checkout "$BRANCH"
@kevupton
Copy link
Author

kevupton commented Feb 15, 2019

Usage:

xc 181

or

xc HELLO

or

xc HELLO-181

The idea is that checks out the branch matching that pattern.

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