Created
April 17, 2015 08:42
-
-
Save mdeous/e20d5ac58343a0951e03 to your computer and use it in GitHub Desktop.
Bash prompt (virtualenv + git status)
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
RED="\033[0;31m" | |
YELLOW="\033[0;33m" | |
GREEN="\033[0;32m" | |
BLUE="\033[0;34m" | |
LIGHT_GRAY="\033[0;37m" | |
COLOR_NONE="\033[0;0m" | |
RE_GIT_BRANCH="^On branch ([^${IFS}]*)" | |
RE_GIT_REMOTE="Your branch is (.*) '" | |
RE_GIT_GAP="Your branch is .* ([0-9]+) commits?" | |
RE_GIT_DIVERGE="Your branch and (.*) have diverged" | |
function gen_prompt { | |
# Handle last command's return value | |
retval=$? | |
if [ $retval -eq 0 ]; then | |
last_ret="${GREEN}${retval}↩${COLOR_NONE}" | |
else | |
last_ret="${RED}${retval}↩${COLOR_NONE}" | |
fi | |
# Handle Git repository informations | |
if [ ! -d "$(pwd)/.git" ]; then | |
git_infos="" | |
else | |
git_status="$(LC_ALL=en_US.UTF-8 git status 2> /dev/null)" | |
# Handle uncommited changes | |
if [[ ! ${git_status} =~ "working directory clean" ]]; then | |
state="${RED}⚡" | |
else | |
state="${GREEN}✓" | |
fi | |
# Handle commits gap with remote | |
if [[ ${git_status} =~ ${RE_GIT_REMOTE} ]]; then | |
if [[ ${BASH_REMATCH[1]} == "ahead of" ]]; then | |
remote="${YELLOW}↑" | |
remote_symbol="+" | |
elif [[ ${BASH_REMATCH[1]} == "up-to-date with" ]]; then | |
remote="" | |
remote_symbol="" | |
else | |
remote="${YELLOW}↓" | |
remote_symbol="-" | |
fi | |
if [[ ${git_status} =~ ${RE_GIT_GAP} ]]; then | |
remote="${remote_symbol}${BASH_REMATCH[1]}${remote}" | |
fi | |
else | |
remote="" | |
fi | |
# Handle diverged branches | |
if [[ ${git_status} =~ ${RE_GIT_DIVERGE} ]]; then | |
remote="${YELLOW}↕" | |
fi | |
# Generate git informations summary | |
if [[ ${git_status} =~ ${RE_GIT_BRANCH} ]]; then | |
branch=${BASH_REMATCH[1]} | |
git_infos=" (${branch} ${remote}${state}${GREEN})" | |
else | |
git_infos="" | |
fi | |
fi | |
# Handle virtualenvs | |
if [ "$VIRTUAL_ENV" != "" ]; then | |
venv="($(basename $VIRTUAL_ENV))" | |
else | |
venv="" | |
fi | |
# Build the prompt | |
current_path=`pwd | sed "s|${HOME}|~|"` | |
main_part="${YELLOW}$(whoami)${COLOR_NONE}@${YELLOW}$(hostname -s)${LIGHT_GRAY}:${BLUE}${current_path}" | |
PS1L="$venv${LIGHT_GRAY}[${main_part}${GREEN}${git_infos}${LIGHT_GRAY}]${COLOR_NONE}" | |
PS1L_NOCOLOR=$(echo "${PS1L}" | sed -r 's|\\033\[[0-9];[0-9]+m||g') | |
# Go figure why there is always a 20 characters difference | |
PS1=$(printf "%s%$((${COLUMNS}-${#PS1L_NOCOLOR}+20))s \n\$ " "${PS1L}" "${last_ret}") | |
} | |
PROMPT_COMMAND="gen_prompt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment