ibanez270dx
1/11/2016 - 3:59 PM

prompt.sh

#!/usr/bin/env bash

##################################################
# Bash Prompt
##################################################

# Current configuration produces:
#   00:00:50 jeff@edison:~/Dev/humani.se (git:master:156d0b4) ruby-2.2.0
#   → _

ps1_identity() {
  if [[ $UID -eq 0 ]]; then
    printf "%s" "\[\033[34m\]\\u\[\033[0m\]@\[\033[36m\]\\h\[\033[35m\]:\w\[\033[0m\] "
  else
    printf "%s" "\[\033[36m\]\\u\[\033[0m\]@\[\033[34m\]\\h\[\033[35m\]:\w\[\033[0m\] "
  fi
}

ps1_git() {
  local branch="" sha1="" line="" attr="" color=0
  shopt -s extglob # Important, for our nice matchers :)

  if ! command -v git >/dev/null 2>&1 ; then
    printf " \033[1;37m\033[41m[git not found]\033[m "
    return 0
  fi

  branch=$(git symbolic-ref -q HEAD 2>/dev/null)
  if [[ $? -gt 0 ]] ; then
    return 0 # Not in a git repo, no need to continue.
  fi
  branch=${branch##refs/heads/}

  # Now we display the branch.
  sha1=($(git log --no-color -1 2>/dev/null))
  sha1=${sha1[1]}
  sha1=${sha1:0:7}

  case "${branch:-"(no branch)"}" in
   production|prod) attr="1;37m\033[" ; color=41 ;; # red
   master|deploy)   color=31                     ;; # red
   stage|staging)   color=33                     ;; # yellow
   dev|development) color=34                     ;; # blue
   next)            color=36                     ;; # gray
   *)
     if [[ -n "${branch}" ]] ; then # Feature Branch :)
       color=32 # green
     else
       color=0 # reset
     fi
     ;;
  esac

  if [[ $color -gt 0 ]] ; then
    printf "\[\033[${attr}${color}m\](git:${branch}:$sha1)\[\033[0m\] "
  fi
}

ps1_gituser() {
  gituser=$(git config user.email)
  if [[ "${gituser}" != "jeff@humani.se" ]]; then
    echo -e "\[\033[33m\]as ${gituser}\[\033[0m\] "
  fi
}

ps1_rbenv() {
  if which rbenv &> /dev/null; then
    rbenv=$(rbenv version-name) || return
    $(rbenv commands | grep -q gemset) && gemset=$(rbenv gemset active 2> /dev/null) && rbenv="$rbenv@${gemset%% *}"
    echo -e "ruby-${rbenv}"
  fi
}

ps1_update() {
  # Default prompt
  local prompt_char='→'

  # Make the prompt a hash mark if logged in as root
  if [[ $UID -eq 0 ]]; then
    prompt_char='#'
  fi

  # Build the prompt!
  PS1="\D{%H:%M:%S} $(ps1_identity)$(ps1_git)$(ps1_gituser)$(ps1_rbenv)\n${prompt_char} "
}

ps1_set() {
  PROMPT_COMMAND="ps1_update $@"
}