Skip to content

Instantly share code, notes, and snippets.

@Shourai
Last active October 18, 2018 08:23
Show Gist options
  • Save Shourai/e2c661a32d2aa59d3dcec7f950e6cc14 to your computer and use it in GitHub Desktop.
Save Shourai/e2c661a32d2aa59d3dcec7f950e6cc14 to your computer and use it in GitHub Desktop.
git prompt in zsh
# Adapted from https://joshdick.net/2017/06/08/my_git_prompt_for_zsh_revisited.html
# PROMPT='%~ ❯ '
setopt prompt_subst
autoload -U colors && colors # Enable colors in prompt
# Echoes a username/host string when connected over SSH (empty otherwise)
ssh_info() {
[[ "$SSH_CONNECTION" != '' ]] && echo "%(!.%{$fg[red]%}.%{$fg[yellow]%})%n%{$reset_color%}@%{$fg[green]%}%m%{$reset_color%}:" || echo ""
}
# Echoes information about Git repository status when inside a Git repository
git_info() {
# Git branch/tag, or name-rev if on detached head
local GIT_LOCATION=${$((git symbolic-ref -q HEAD || git name-rev --name-only --no-undefined --always HEAD) 2> /dev/null)#(refs/heads/|tags/)}
if [ -n "$GIT_LOCATION" ]; then
local AHEAD="%F{red}⇡NUM"
local BEHIND="%F{cyan}⇣NUM"
local MERGING="%F{magenta}⚡︎"
local UNTRACKED="%F{red}●"
local MODIFIED="%F{yellow}●"
local STAGED="%F{green}●"
local -a DIVERGENCES
local -a FLAGS
local NUM_AHEAD="$(git log --oneline @{u}.. 2> /dev/null | wc -l | tr -d ' ')"
if [ "$NUM_AHEAD" -gt 0 ]; then
DIVERGENCES+=( "${AHEAD//NUM/$NUM_AHEAD}" )
fi
local NUM_BEHIND="$(git log --oneline ..@{u} 2> /dev/null | wc -l | tr -d ' ')"
if [ "$NUM_BEHIND" -gt 0 ]; then
DIVERGENCES+=( "${BEHIND//NUM/$NUM_BEHIND}" )
fi
local GIT_DIR="$(git rev-parse --git-dir 2> /dev/null)"
if [ -n $GIT_DIR ] && test -r $GIT_DIR/MERGE_HEAD; then
FLAGS+=( "$MERGING" )
fi
if [[ -n $(git ls-files --other --exclude-standard 2> /dev/null) ]]; then
FLAGS+=( "$UNTRACKED" )
fi
if ! git diff --quiet 2> /dev/null; then
FLAGS+=( "$MODIFIED" )
fi
if ! git diff --cached --quiet 2> /dev/null; then
FLAGS+=( "$STAGED" )
fi
local -a GIT_INFO
GIT_INFO+=( "%F{245}±" )
[ -n "$GIT_STATUS" ] && GIT_INFO+=( "$GIT_STATUS" )
[[ ${#DIVERGENCES[@]} -ne 0 ]] && GIT_INFO+=( "${(j::)DIVERGENCES}" )
[[ ${#FLAGS[@]} -ne 0 ]] && GIT_INFO+=( "${(j::)FLAGS}" )
GIT_INFO+=( "%F{245}$GIT_LOCATION" )
echo "${(j: :)GIT_INFO}"
fi
}
# Use ❯ as the non-root prompt character; # for root
# Change the prompt character color if the last command had a nonzero exit code
PS1='
$(ssh_info)%F{147}%~%u $(git_info)
%(?.%F{blue}.%F{red})%(!.#.❯)%f '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment