899eb095c65e73cdf2263d7d39ba0c506686020a
   1# bash/zsh git prompt support
   2#
   3# Copyright (C) 2006,2007 Shawn O. Pearce <spearce@spearce.org>
   4# Distributed under the GNU General Public License, version 2.0.
   5#
   6# This script allows you to see the current branch in your prompt.
   7#
   8# To enable:
   9#
  10#    1) Copy this file to somewhere (e.g. ~/.git-prompt.sh).
  11#    2) Add the following line to your .bashrc/.zshrc:
  12#        source ~/.git-prompt.sh
  13#    3a) Change your PS1 to call __git_ps1 as
  14#        command-substitution:
  15#        Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
  16#        ZSH:  PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
  17#        the optional argument will be used as format string.
  18#    3b) Alternatively, if you are using bash, __git_ps1 can be
  19#        used for PROMPT_COMMAND with two parameters, <pre> and
  20#        <post>, which are strings you would put in $PS1 before
  21#        and after the status string generated by the git-prompt
  22#        machinery.  e.g.
  23#           PROMPT_COMMAND='__git_ps1 "\u@\h:\w" "\\\$ "'
  24#        will show username, at-sign, host, colon, cwd, then
  25#        various status string, followed by dollar and SP, as
  26#        your prompt.
  27#
  28# The argument to __git_ps1 will be displayed only if you are currently
  29# in a git repository.  The %s token will be the name of the current
  30# branch.
  31#
  32# In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty value,
  33# unstaged (*) and staged (+) changes will be shown next to the branch
  34# name.  You can configure this per-repository with the
  35# bash.showDirtyState variable, which defaults to true once
  36# GIT_PS1_SHOWDIRTYSTATE is enabled.
  37#
  38# You can also see if currently something is stashed, by setting
  39# GIT_PS1_SHOWSTASHSTATE to a nonempty value. If something is stashed,
  40# then a '$' will be shown next to the branch name.
  41#
  42# If you would like to see if there're untracked files, then you can set
  43# GIT_PS1_SHOWUNTRACKEDFILES to a nonempty value. If there're untracked
  44# files, then a '%' will be shown next to the branch name.
  45#
  46# If you would like to see the difference between HEAD and its upstream,
  47# set GIT_PS1_SHOWUPSTREAM="auto".  A "<" indicates you are behind, ">"
  48# indicates you are ahead, "<>" indicates you have diverged and "="
  49# indicates that there is no difference. You can further control
  50# behaviour by setting GIT_PS1_SHOWUPSTREAM to a space-separated list
  51# of values:
  52#
  53#     verbose       show number of commits ahead/behind (+/-) upstream
  54#     legacy        don't use the '--count' option available in recent
  55#                   versions of git-rev-list
  56#     git           always compare HEAD to @{upstream}
  57#     svn           always compare HEAD to your SVN upstream
  58#
  59# By default, __git_ps1 will compare HEAD to your SVN upstream if it can
  60# find one, or @{upstream} otherwise.  Once you have set
  61# GIT_PS1_SHOWUPSTREAM, you can override it on a per-repository basis by
  62# setting the bash.showUpstream config variable.
  63#
  64# If you would like a colored hint about the current dirty state, set
  65# GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
  66# the colored output of "git status -sb".
  67#
  68# __gitdir accepts 0 or 1 arguments (i.e., location)
  69# returns location of .git repo
  70__gitdir ()
  71{
  72        # Note: this function is duplicated in git-completion.bash
  73        # When updating it, make sure you update the other one to match.
  74        if [ -z "${1-}" ]; then
  75                if [ -n "${__git_dir-}" ]; then
  76                        echo "$__git_dir"
  77                elif [ -n "${GIT_DIR-}" ]; then
  78                        test -d "${GIT_DIR-}" || return 1
  79                        echo "$GIT_DIR"
  80                elif [ -d .git ]; then
  81                        echo .git
  82                else
  83                        git rev-parse --git-dir 2>/dev/null
  84                fi
  85        elif [ -d "$1/.git" ]; then
  86                echo "$1/.git"
  87        else
  88                echo "$1"
  89        fi
  90}
  91
  92# stores the divergence from upstream in $p
  93# used by GIT_PS1_SHOWUPSTREAM
  94__git_ps1_show_upstream ()
  95{
  96        local key value
  97        local svn_remote svn_url_pattern count n
  98        local upstream=git legacy="" verbose=""
  99
 100        svn_remote=()
 101        # get some config options from git-config
 102        local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
 103        while read -r key value; do
 104                case "$key" in
 105                bash.showupstream)
 106                        GIT_PS1_SHOWUPSTREAM="$value"
 107                        if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
 108                                p=""
 109                                return
 110                        fi
 111                        ;;
 112                svn-remote.*.url)
 113                        svn_remote[ $((${#svn_remote[@]} + 1)) ]="$value"
 114                        svn_url_pattern+="\\|$value"
 115                        upstream=svn+git # default upstream is SVN if available, else git
 116                        ;;
 117                esac
 118        done <<< "$output"
 119
 120        # parse configuration values
 121        for option in ${GIT_PS1_SHOWUPSTREAM}; do
 122                case "$option" in
 123                git|svn) upstream="$option" ;;
 124                verbose) verbose=1 ;;
 125                legacy)  legacy=1  ;;
 126                esac
 127        done
 128
 129        # Find our upstream
 130        case "$upstream" in
 131        git)    upstream="@{upstream}" ;;
 132        svn*)
 133                # get the upstream from the "git-svn-id: ..." in a commit message
 134                # (git-svn uses essentially the same procedure internally)
 135                local svn_upstream=($(git log --first-parent -1 \
 136                                        --grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
 137                if [[ 0 -ne ${#svn_upstream[@]} ]]; then
 138                        svn_upstream=${svn_upstream[ ${#svn_upstream[@]} - 2 ]}
 139                        svn_upstream=${svn_upstream%@*}
 140                        local n_stop="${#svn_remote[@]}"
 141                        for ((n=1; n <= n_stop; n++)); do
 142                                svn_upstream=${svn_upstream#${svn_remote[$n]}}
 143                        done
 144
 145                        if [[ -z "$svn_upstream" ]]; then
 146                                # default branch name for checkouts with no layout:
 147                                upstream=${GIT_SVN_ID:-git-svn}
 148                        else
 149                                upstream=${svn_upstream#/}
 150                        fi
 151                elif [[ "svn+git" = "$upstream" ]]; then
 152                        upstream="@{upstream}"
 153                fi
 154                ;;
 155        esac
 156
 157        # Find how many commits we are ahead/behind our upstream
 158        if [[ -z "$legacy" ]]; then
 159                count="$(git rev-list --count --left-right \
 160                                "$upstream"...HEAD 2>/dev/null)"
 161        else
 162                # produce equivalent output to --count for older versions of git
 163                local commits
 164                if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
 165                then
 166                        local commit behind=0 ahead=0
 167                        for commit in $commits
 168                        do
 169                                case "$commit" in
 170                                "<"*) ((behind++)) ;;
 171                                *)    ((ahead++))  ;;
 172                                esac
 173                        done
 174                        count="$behind  $ahead"
 175                else
 176                        count=""
 177                fi
 178        fi
 179
 180        # calculate the result
 181        if [[ -z "$verbose" ]]; then
 182                case "$count" in
 183                "") # no upstream
 184                        p="" ;;
 185                "0      0") # equal to upstream
 186                        p="=" ;;
 187                "0      "*) # ahead of upstream
 188                        p=">" ;;
 189                *"      0") # behind upstream
 190                        p="<" ;;
 191                *)          # diverged from upstream
 192                        p="<>" ;;
 193                esac
 194        else
 195                case "$count" in
 196                "") # no upstream
 197                        p="" ;;
 198                "0      0") # equal to upstream
 199                        p=" u=" ;;
 200                "0      "*) # ahead of upstream
 201                        p=" u+${count#0 }" ;;
 202                *"      0") # behind upstream
 203                        p=" u-${count%  0}" ;;
 204                *)          # diverged from upstream
 205                        p=" u+${count#* }-${count%      *}" ;;
 206                esac
 207        fi
 208
 209}
 210
 211
 212# __git_ps1 accepts 0 or 1 arguments (i.e., format string)
 213# when called from PS1 using command substitution
 214# in this mode it prints text to add to bash PS1 prompt (includes branch name)
 215#
 216# __git_ps1 requires 2 arguments when called from PROMPT_COMMAND (pc)
 217# in that case it _sets_ PS1. The arguments are parts of a PS1 string.
 218# when both arguments are given, the first is prepended and the second appended
 219# to the state string when assigned to PS1.
 220# In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
 221__git_ps1 ()
 222{
 223        local pcmode=no
 224        local detached=no
 225        local ps1pc_start='\u@\h:\w '
 226        local ps1pc_end='\$ '
 227        local printf_format=' (%s)'
 228
 229        case "$#" in
 230                2)      pcmode=yes
 231                        ps1pc_start="$1"
 232                        ps1pc_end="$2"
 233                ;;
 234                0|1)    printf_format="${1:-$printf_format}"
 235                ;;
 236                *)      return
 237                ;;
 238        esac
 239
 240        local g="$(__gitdir)"
 241        if [ -z "$g" ]; then
 242                if [ $pcmode = yes ]; then
 243                        #In PC mode PS1 always needs to be set
 244                        PS1="$ps1pc_start$ps1pc_end"
 245                fi
 246        else
 247                local r=""
 248                local b=""
 249                if [ -f "$g/rebase-merge/interactive" ]; then
 250                        r="|REBASE-i"
 251                        b="$(cat "$g/rebase-merge/head-name")"
 252                elif [ -d "$g/rebase-merge" ]; then
 253                        r="|REBASE-m"
 254                        b="$(cat "$g/rebase-merge/head-name")"
 255                else
 256                        if [ -d "$g/rebase-apply" ]; then
 257                                if [ -f "$g/rebase-apply/rebasing" ]; then
 258                                        r="|REBASE"
 259                                elif [ -f "$g/rebase-apply/applying" ]; then
 260                                        r="|AM"
 261                                else
 262                                        r="|AM/REBASE"
 263                                fi
 264                        elif [ -f "$g/MERGE_HEAD" ]; then
 265                                r="|MERGING"
 266                        elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
 267                                r="|CHERRY-PICKING"
 268                        elif [ -f "$g/BISECT_LOG" ]; then
 269                                r="|BISECTING"
 270                        fi
 271
 272                        b="$(git symbolic-ref HEAD 2>/dev/null)" || {
 273                                detached=yes
 274                                b="$(
 275                                case "${GIT_PS1_DESCRIBE_STYLE-}" in
 276                                (contains)
 277                                        git describe --contains HEAD ;;
 278                                (branch)
 279                                        git describe --contains --all HEAD ;;
 280                                (describe)
 281                                        git describe HEAD ;;
 282                                (* | default)
 283                                        git describe --tags --exact-match HEAD ;;
 284                                esac 2>/dev/null)" ||
 285
 286                                b="$(cut -c1-7 "$g/HEAD" 2>/dev/null)..." ||
 287                                b="unknown"
 288                                b="($b)"
 289                        }
 290                fi
 291
 292                local w=""
 293                local i=""
 294                local s=""
 295                local u=""
 296                local c=""
 297                local p=""
 298
 299                if [ "true" = "$(git rev-parse --is-inside-git-dir 2>/dev/null)" ]; then
 300                        if [ "true" = "$(git rev-parse --is-bare-repository 2>/dev/null)" ]; then
 301                                c="BARE:"
 302                        else
 303                                b="GIT_DIR!"
 304                        fi
 305                elif [ "true" = "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
 306                        if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ]; then
 307                                if [ "$(git config --bool bash.showDirtyState)" != "false" ]; then
 308                                        git diff --no-ext-diff --quiet --exit-code || w="*"
 309                                        if git rev-parse --quiet --verify HEAD >/dev/null; then
 310                                                git diff-index --cached --quiet HEAD -- || i="+"
 311                                        else
 312                                                i="#"
 313                                        fi
 314                                fi
 315                        fi
 316                        if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ]; then
 317                                git rev-parse --verify refs/stash >/dev/null 2>&1 && s="$"
 318                        fi
 319
 320                        if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ]; then
 321                                if [ -n "$(git ls-files --others --exclude-standard)" ]; then
 322                                        u="%"
 323                                fi
 324                        fi
 325
 326                        if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
 327                                __git_ps1_show_upstream
 328                        fi
 329                fi
 330
 331                local f="$w$i$s$u"
 332                if [ $pcmode = yes ]; then
 333                        if [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
 334                                local c_red='\e[31m'
 335                                local c_green='\e[32m'
 336                                local c_lblue='\e[1;34m'
 337                                local c_clear='\e[0m'
 338                                local bad_color=$c_red
 339                                local ok_color=$c_green
 340                                local branch_color="$c_clear"
 341                                local flags_color="$c_lblue"
 342                                local branchstring="$c${b##refs/heads/}"
 343
 344                                if [ $detached = no ]; then
 345                                        branch_color="$ok_color"
 346                                else
 347                                        branch_color="$bad_color"
 348                                fi
 349
 350                                # Setting PS1 directly with \[ and \] around colors
 351                                # is necessary to prevent wrapping issues!
 352                                PS1="$ps1pc_start (\[$branch_color\]$branchstring\[$c_clear\]"
 353
 354                                if [ -n "$w$i$s$u$r$p" ]; then
 355                                        PS1="$PS1 "
 356                                fi
 357                                if [ "$w" = "*" ]; then
 358                                        PS1="$PS1\[$bad_color\]$w"
 359                                fi
 360                                if [ -n "$i" ]; then
 361                                        PS1="$PS1\[$ok_color\]$i"
 362                                fi
 363                                if [ -n "$s" ]; then
 364                                        PS1="$PS1\[$flags_color\]$s"
 365                                fi
 366                                if [ -n "$u" ]; then
 367                                        PS1="$PS1\[$bad_color\]$u"
 368                                fi
 369                                PS1="$PS1\[$c_clear\]$r$p)$ps1pc_end"
 370                        else
 371                                PS1="$ps1pc_start ($c${b##refs/heads/}${f:+ $f}$r$p)$ps1pc_end"
 372                        fi
 373                else
 374                        # NO color option unless in PROMPT_COMMAND mode
 375                        printf -- "$printf_format" "$c${b##refs/heads/}${f:+ $f}$r$p"
 376                fi
 377        fi
 378}