Last active
June 8, 2023 19:42
-
-
Save ozydingo/4b1c9020e5ef7d3eec7072d8fe646f4b to your computer and use it in GitHub Desktop.
Functions for git in bash / zsh prompt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# To use gitprompt to set your prompt to include a colored git branch label: | |
# bash: | |
# source gitprompt | |
# bash_colors | |
# PS1='[\[$(git_branch_color)\]$(parse_git_branch)\[${NORMAL}\]] '"$PS1" | |
# zsh: | |
# source gitprompt | |
# zsh_colors | |
# setopt PROMPT_SUBST | |
# export PROMPT='[%F{$(git_branch_color)}$(parse_git_branch)%f] %B%F{240}%~%f %# ' | |
bash_colors() { | |
export BLACK=$(tput setaf 0) | |
export RED=$(tput setaf 1) | |
export GREEN=$(tput setaf 2) | |
export YELLOW=$(tput setaf 3) | |
export BLUE=$(tput setaf 4) | |
export MAGENTA=$(tput setaf 5) | |
export CYAN=$(tput setaf 6) | |
export WHITE=$(tput setaf 7) | |
export NORMAL=$(tput sgr0) | |
} | |
zsh_colors() { | |
export BLACK='black' | |
export RED='red' | |
export GREEN='green' | |
export YELLOW='yellow' | |
export BLUE='blue' | |
export MAGENTA='magenta' | |
export CYAN='cyan' | |
export WHITE='white' | |
export NORMAL='default' | |
} | |
parse_git_branch () { | |
if git rev-parse --git-dir >/dev/null 2>&1; then | |
gitver=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p') | |
else | |
gitver='none' | |
fi | |
echo -e $gitver | |
} | |
git_branch_status () { | |
if ! git rev-parse --git-dir >/dev/null 2>&1 ; then | |
echo none | |
return 0 | |
fi | |
firstline=1 | |
gitstatus=clean | |
while read line; do | |
if [ $firstline -eq 1 ]; then | |
# Read first line to determine if we are ahead or behind remote | |
firstline=0 | |
if [[ $line =~ '\[ahead .+\]' ]]; then gitstatus=ahead; fi | |
if [[ $line =~ '\[.*behind .+\]' ]]; then gitstatus=behind; fi | |
else | |
# Read sceond line: anything here means there's a modified or added file | |
[ -n "$line" ] && gitstatus=dirty | |
fi | |
done < <(git status -sb | head -2) | |
echo -ne $gitstatus | |
} | |
git_branch_color () { | |
case "$(git_branch_status)" in | |
dirty) | |
echo "$RED" | |
;; | |
ahead) | |
echo "$CYAN" | |
;; | |
behind) | |
echo "$YELLOW" | |
;; | |
clean) | |
echo "$GREEN" | |
;; | |
none) | |
echo "$NORMAL" | |
;; | |
*) | |
echo "$NORMAL" | |
echo "gitprompt error: unrecognized status $(git_branch_status)" >&2 | |
;; | |
esac | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment