From 5f31f601476c5619280055d6c1d407bd1c975f01 Mon Sep 17 00:00:00 2001 From: Max Regan Date: Sun, 12 Jul 2020 13:03:41 -0700 Subject: [PATCH] bash: add a custom prompt with git awareness --- .mgr_config/.bashrc | 70 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/.mgr_config/.bashrc b/.mgr_config/.bashrc index faebaa0..379a94b 100644 --- a/.mgr_config/.bashrc +++ b/.mgr_config/.bashrc @@ -11,6 +11,76 @@ alias highlight='grep -U999999 --color=always' export PATH=$PATH:$HOME/.mgr_config/bin +FG_BLK="$(tput setaf 0)" +FG_RED="$(tput setaf 1)" +FG_GRN="$(tput setaf 2)" +FG_YEL="$(tput setaf 3)" +FG_BLU="$(tput setaf 4)" +FG_MGN="$(tput setaf 5)" +FG_CYN="$(tput setaf 6)" +FG_WHT="$(tput setaf 7)" +FG_DEF="$(tput setaf 9)" + +BG_BLK="$(tput setab 0)" +BG_RED="$(tput setab 1)" +BG_GRN="$(tput setab 2)" +BG_YEL="$(tput setab 3)" +BG_BLU="$(tput setab 4)" +BG_MGN="$(tput setab 5)" +BG_CYN="$(tput setab 6)" +BG_WHT="$(tput setab 7)" +BG_DEF="$(tput setab 9)" + +BOLD="$(tput bold)" + +RST=$(tput sgr0) + +git_root() { + git rev-parse --show-toplevel 2> /dev/null +} + +prompt_function() { + prompt="" + + HOST_COLOR_ID=$(( "16#$(echo tls-proxy | md5sum | cut -f1 -d' ')" % 7 + 1)) # [1, 7] + HOST_COLOR="${RST}$(tput setaf $HOST_COLOR_ID)" + GIT_COLOR="${RST}${FG_CYN}" + DIR_COLOR="${RST}${FG_YEL}" + WARN_COLOR="${RST}${BOLD}${FG_RED}" + + if [[ $INSIDE_EMACS ]]; then + prompt+="" + fi + + if [[ "$(whoami)" == root ]]; then + prompt+="${WARN_COLOR}" + else + prompt+="${HOST_COLOR}" + fi + prompt+="$(whoami)@$(hostname)${RST}:" + if root=$(git_root); then + # If in a git repository, only print the path relative to the repo root + path=$(realpath --relative-to=$root $PWD) + ref=$(git symbolic-ref --short -q HEAD) + if [[ $ref == "" ]]; then + ref="${WARN_COLOR}detached${GIT_COLOR}" + fi + dirty=$(git diff-index --quiet HEAD) + if [[ $path == . ]]; then + path="" + fi + prompt+="${GIT_COLOR}[$(basename $root)@${ref}:${DIR_COLOR}${path}${fg}${GIT_COLOR}]${RST}" + else + # If not in a git repo, print the full path + prompt+="${DIR_COLOR}[$(dirs)]${RST}" + fi + + echo "$prompt\$ " +} + +PS1="\$(prompt_function)" + + if [[ -z "$INSIDE_EMACS" ]]; then EMACS="emacsclient -a="" -c" alias emacs="$EMACS"