contrib / completion / git-prompt.shon commit bash prompt: use bash builtins to find out current branch (3a43c4b)
   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#        Bash: PROMPT_COMMAND='__git_ps1 "\u@\h:\w" "\\\$ "'
  24#        ZSH:  precmd () { __git_ps1 "%n" ":%~$ " "|%s" }
  25#        will show username, at-sign, host, colon, cwd, then
  26#        various status string, followed by dollar and SP, as
  27#        your prompt.
  28#        Optionally, you can supply a third argument with a printf
  29#        format string to finetune the output of the branch status
  30#
  31# The argument to __git_ps1 will be displayed only if you are currently
  32# in a git repository.  The %s token will be the name of the current
  33# branch.
  34#
  35# In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty value,
  36# unstaged (*) and staged (+) changes will be shown next to the branch
  37# name.  You can configure this per-repository with the
  38# bash.showDirtyState variable, which defaults to true once
  39# GIT_PS1_SHOWDIRTYSTATE is enabled.
  40#
  41# You can also see if currently something is stashed, by setting
  42# GIT_PS1_SHOWSTASHSTATE to a nonempty value. If something is stashed,
  43# then a '$' will be shown next to the branch name.
  44#
  45# If you would like to see if there're untracked files, then you can set
  46# GIT_PS1_SHOWUNTRACKEDFILES to a nonempty value. If there're untracked
  47# files, then a '%' will be shown next to the branch name.  You can
  48# configure this per-repository with the bash.showUntrackedFiles
  49# variable, which defaults to true once GIT_PS1_SHOWUNTRACKEDFILES is
  50# enabled.
  51#
  52# If you would like to see the difference between HEAD and its upstream,
  53# set GIT_PS1_SHOWUPSTREAM="auto".  A "<" indicates you are behind, ">"
  54# indicates you are ahead, "<>" indicates you have diverged and "="
  55# indicates that there is no difference. You can further control
  56# behaviour by setting GIT_PS1_SHOWUPSTREAM to a space-separated list
  57# of values:
  58#
  59#     verbose       show number of commits ahead/behind (+/-) upstream
  60#     legacy        don't use the '--count' option available in recent
  61#                   versions of git-rev-list
  62#     git           always compare HEAD to @{upstream}
  63#     svn           always compare HEAD to your SVN upstream
  64#
  65# By default, __git_ps1 will compare HEAD to your SVN upstream if it can
  66# find one, or @{upstream} otherwise.  Once you have set
  67# GIT_PS1_SHOWUPSTREAM, you can override it on a per-repository basis by
  68# setting the bash.showUpstream config variable.
  69#
  70# If you would like to see more information about the identity of
  71# commits checked out as a detached HEAD, set GIT_PS1_DESCRIBE_STYLE
  72# to one of these values:
  73#
  74#     contains      relative to newer annotated tag (v1.6.3.2~35)
  75#     branch        relative to newer tag or branch (master~4)
  76#     describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
  77#     default       exactly matching tag
  78#
  79# If you would like a colored hint about the current dirty state, set
  80# GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
  81# the colored output of "git status -sb".
  82
  83# stores the divergence from upstream in $p
  84# used by GIT_PS1_SHOWUPSTREAM
  85__git_ps1_show_upstream ()
  86{
  87        local key value
  88        local svn_remote svn_url_pattern count n
  89        local upstream=git legacy="" verbose=""
  90
  91        svn_remote=()
  92        # get some config options from git-config
  93        local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
  94        while read -r key value; do
  95                case "$key" in
  96                bash.showupstream)
  97                        GIT_PS1_SHOWUPSTREAM="$value"
  98                        if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
  99                                p=""
 100                                return
 101                        fi
 102                        ;;
 103                svn-remote.*.url)
 104                        svn_remote[$((${#svn_remote[@]} + 1))]="$value"
 105                        svn_url_pattern+="\\|$value"
 106                        upstream=svn+git # default upstream is SVN if available, else git
 107                        ;;
 108                esac
 109        done <<< "$output"
 110
 111        # parse configuration values
 112        for option in ${GIT_PS1_SHOWUPSTREAM}; do
 113                case "$option" in
 114                git|svn) upstream="$option" ;;
 115                verbose) verbose=1 ;;
 116                legacy)  legacy=1  ;;
 117                esac
 118        done
 119
 120        # Find our upstream
 121        case "$upstream" in
 122        git)    upstream="@{upstream}" ;;
 123        svn*)
 124                # get the upstream from the "git-svn-id: ..." in a commit message
 125                # (git-svn uses essentially the same procedure internally)
 126                local -a svn_upstream
 127                svn_upstream=($(git log --first-parent -1 \
 128                                        --grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
 129                if [[ 0 -ne ${#svn_upstream[@]} ]]; then
 130                        svn_upstream=${svn_upstream[${#svn_upstream[@]} - 2]}
 131                        svn_upstream=${svn_upstream%@*}
 132                        local n_stop="${#svn_remote[@]}"
 133                        for ((n=1; n <= n_stop; n++)); do
 134                                svn_upstream=${svn_upstream#${svn_remote[$n]}}
 135                        done
 136
 137                        if [[ -z "$svn_upstream" ]]; then
 138                                # default branch name for checkouts with no layout:
 139                                upstream=${GIT_SVN_ID:-git-svn}
 140                        else
 141                                upstream=${svn_upstream#/}
 142                        fi
 143                elif [[ "svn+git" = "$upstream" ]]; then
 144                        upstream="@{upstream}"
 145                fi
 146                ;;
 147        esac
 148
 149        # Find how many commits we are ahead/behind our upstream
 150        if [[ -z "$legacy" ]]; then
 151                count="$(git rev-list --count --left-right \
 152                                "$upstream"...HEAD 2>/dev/null)"
 153        else
 154                # produce equivalent output to --count for older versions of git
 155                local commits
 156                if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
 157                then
 158                        local commit behind=0 ahead=0
 159                        for commit in $commits
 160                        do
 161                                case "$commit" in
 162                                "<"*) ((behind++)) ;;
 163                                *)    ((ahead++))  ;;
 164                                esac
 165                        done
 166                        count="$behind  $ahead"
 167                else
 168                        count=""
 169                fi
 170        fi
 171
 172        # calculate the result
 173        if [[ -z "$verbose" ]]; then
 174                case "$count" in
 175                "") # no upstream
 176                        p="" ;;
 177                "0      0") # equal to upstream
 178                        p="=" ;;
 179                "0      "*) # ahead of upstream
 180                        p=">" ;;
 181                *"      0") # behind upstream
 182                        p="<" ;;
 183                *)          # diverged from upstream
 184                        p="<>" ;;
 185                esac
 186        else
 187                case "$count" in
 188                "") # no upstream
 189                        p="" ;;
 190                "0      0") # equal to upstream
 191                        p=" u=" ;;
 192                "0      "*) # ahead of upstream
 193                        p=" u+${count#0 }" ;;
 194                *"      0") # behind upstream
 195                        p=" u-${count%  0}" ;;
 196                *)          # diverged from upstream
 197                        p=" u+${count#* }-${count%      *}" ;;
 198                esac
 199        fi
 200
 201}
 202
 203# Helper function that is meant to be called from __git_ps1.  It
 204# builds up a gitstring injecting color codes into the appropriate
 205# places.
 206__git_ps1_colorize_gitstring ()
 207{
 208        if [[ -n ${ZSH_VERSION-} ]]; then
 209                local c_red='%F{red}'
 210                local c_green='%F{green}'
 211                local c_lblue='%F{blue}'
 212                local c_clear='%f'
 213                local bad_color=$c_red
 214                local ok_color=$c_green
 215                local branch_color="$c_clear"
 216                local flags_color="$c_lblue"
 217                local branchstring="$c${b##refs/heads/}"
 218
 219                if [ $detached = no ]; then
 220                        branch_color="$ok_color"
 221                else
 222                        branch_color="$bad_color"
 223                fi
 224
 225                gitstring="$branch_color$branchstring$c_clear"
 226
 227                if [ -n "$w$i$s$u$r$p" ]; then
 228                        gitstring="$gitstring$z"
 229                fi
 230                if [ "$w" = "*" ]; then
 231                        gitstring="$gitstring$bad_color$w"
 232                fi
 233                if [ -n "$i" ]; then
 234                        gitstring="$gitstring$ok_color$i"
 235                fi
 236                if [ -n "$s" ]; then
 237                        gitstring="$gitstring$flags_color$s"
 238                fi
 239                if [ -n "$u" ]; then
 240                        gitstring="$gitstring$bad_color$u"
 241                fi
 242                gitstring="$gitstring$c_clear$r$p"
 243                return
 244        fi
 245        local c_red='\e[31m'
 246        local c_green='\e[32m'
 247        local c_lblue='\e[1;34m'
 248        local c_clear='\e[0m'
 249        local bad_color=$c_red
 250        local ok_color=$c_green
 251        local branch_color="$c_clear"
 252        local flags_color="$c_lblue"
 253        local branchstring="$c${b##refs/heads/}"
 254
 255        if [ $detached = no ]; then
 256                branch_color="$ok_color"
 257        else
 258                branch_color="$bad_color"
 259        fi
 260
 261        # Setting gitstring directly with \[ and \] around colors
 262        # is necessary to prevent wrapping issues!
 263        gitstring="\[$branch_color\]$branchstring\[$c_clear\]"
 264
 265        if [ -n "$w$i$s$u$r$p" ]; then
 266                gitstring="$gitstring$z"
 267        fi
 268        if [ "$w" = "*" ]; then
 269                gitstring="$gitstring\[$bad_color\]$w"
 270        fi
 271        if [ -n "$i" ]; then
 272                gitstring="$gitstring\[$ok_color\]$i"
 273        fi
 274        if [ -n "$s" ]; then
 275                gitstring="$gitstring\[$flags_color\]$s"
 276        fi
 277        if [ -n "$u" ]; then
 278                gitstring="$gitstring\[$bad_color\]$u"
 279        fi
 280        gitstring="$gitstring\[$c_clear\]$r$p"
 281}
 282
 283# __git_ps1 accepts 0 or 1 arguments (i.e., format string)
 284# when called from PS1 using command substitution
 285# in this mode it prints text to add to bash PS1 prompt (includes branch name)
 286#
 287# __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
 288# in that case it _sets_ PS1. The arguments are parts of a PS1 string.
 289# when two arguments are given, the first is prepended and the second appended
 290# to the state string when assigned to PS1.
 291# The optional third parameter will be used as printf format string to further
 292# customize the output of the git-status string.
 293# In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
 294__git_ps1 ()
 295{
 296        local pcmode=no
 297        local detached=no
 298        local ps1pc_start='\u@\h:\w '
 299        local ps1pc_end='\$ '
 300        local printf_format=' (%s)'
 301
 302        case "$#" in
 303                2|3)    pcmode=yes
 304                        ps1pc_start="$1"
 305                        ps1pc_end="$2"
 306                        printf_format="${3:-$printf_format}"
 307                ;;
 308                0|1)    printf_format="${1:-$printf_format}"
 309                ;;
 310                *)      return
 311                ;;
 312        esac
 313
 314        local g="$(git rev-parse --git-dir 2>/dev/null)"
 315        if [ -z "$g" ]; then
 316                if [ $pcmode = yes ]; then
 317                        #In PC mode PS1 always needs to be set
 318                        PS1="$ps1pc_start$ps1pc_end"
 319                fi
 320                return
 321        fi
 322
 323        local r=""
 324        local b=""
 325        local step=""
 326        local total=""
 327        if [ -d "$g/rebase-merge" ]; then
 328                read b 2>/dev/null <"$g/rebase-merge/head-name"
 329                read step 2>/dev/null <"$g/rebase-merge/msgnum"
 330                read total 2>/dev/null <"$g/rebase-merge/end"
 331                if [ -f "$g/rebase-merge/interactive" ]; then
 332                        r="|REBASE-i"
 333                else
 334                        r="|REBASE-m"
 335                fi
 336        else
 337                if [ -d "$g/rebase-apply" ]; then
 338                        read step 2>/dev/null <"$g/rebase-apply/next"
 339                        read total 2>/dev/null <"$g/rebase-apply/last"
 340                        if [ -f "$g/rebase-apply/rebasing" ]; then
 341                                read b 2>/dev/null <"$g/rebase-apply/head-name"
 342                                r="|REBASE"
 343                        elif [ -f "$g/rebase-apply/applying" ]; then
 344                                r="|AM"
 345                        else
 346                                r="|AM/REBASE"
 347                        fi
 348                elif [ -f "$g/MERGE_HEAD" ]; then
 349                        r="|MERGING"
 350                elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
 351                        r="|CHERRY-PICKING"
 352                elif [ -f "$g/REVERT_HEAD" ]; then
 353                        r="|REVERTING"
 354                elif [ -f "$g/BISECT_LOG" ]; then
 355                        r="|BISECTING"
 356                fi
 357
 358                if [ -n "$b" ]; then
 359                        :
 360                elif [ -h "$g/HEAD" ]; then
 361                        # symlink symbolic ref
 362                        b="$(git symbolic-ref HEAD 2>/dev/null)"
 363                else
 364                        local head=""
 365                        if ! read head 2>/dev/null <"$g/HEAD"; then
 366                                if [ $pcmode = yes ]; then
 367                                        PS1="$ps1pc_start$ps1pc_end"
 368                                fi
 369                                return
 370                        fi
 371                        # is it a symbolic ref?
 372                        b="${head#ref: }"
 373                        if [ "$head" = "$b" ]; then
 374                                detached=yes
 375                                b="$(
 376                                case "${GIT_PS1_DESCRIBE_STYLE-}" in
 377                                (contains)
 378                                        git describe --contains HEAD ;;
 379                                (branch)
 380                                        git describe --contains --all HEAD ;;
 381                                (describe)
 382                                        git describe HEAD ;;
 383                                (* | default)
 384                                        git describe --tags --exact-match HEAD ;;
 385                                esac 2>/dev/null)" ||
 386
 387                                b="$(git rev-parse --short HEAD 2>/dev/null)..." ||
 388                                b="unknown"
 389                                b="($b)"
 390                        fi
 391                fi
 392        fi
 393
 394        if [ -n "$step" ] && [ -n "$total" ]; then
 395                r="$r $step/$total"
 396        fi
 397
 398        local w=""
 399        local i=""
 400        local s=""
 401        local u=""
 402        local c=""
 403        local p=""
 404
 405        if [ "true" = "$(git rev-parse --is-inside-git-dir 2>/dev/null)" ]; then
 406                if [ "true" = "$(git rev-parse --is-bare-repository 2>/dev/null)" ]; then
 407                        c="BARE:"
 408                else
 409                        b="GIT_DIR!"
 410                fi
 411        elif [ "true" = "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
 412                if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
 413                   [ "$(git config --bool bash.showDirtyState)" != "false" ]
 414                then
 415                        git diff --no-ext-diff --quiet --exit-code || w="*"
 416                        if git rev-parse --quiet --verify HEAD >/dev/null; then
 417                                git diff-index --cached --quiet HEAD -- || i="+"
 418                        else
 419                                i="#"
 420                        fi
 421                fi
 422                if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ]; then
 423                        git rev-parse --verify refs/stash >/dev/null 2>&1 && s="$"
 424                fi
 425
 426                if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
 427                   [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
 428                   [ -n "$(git ls-files --others --exclude-standard)" ]
 429                then
 430                        u="%${ZSH_VERSION+%}"
 431                fi
 432
 433                if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
 434                        __git_ps1_show_upstream
 435                fi
 436        fi
 437
 438        local z="${GIT_PS1_STATESEPARATOR-" "}"
 439        local f="$w$i$s$u"
 440        if [ $pcmode = yes ]; then
 441                local gitstring=
 442                if [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
 443                        __git_ps1_colorize_gitstring
 444                else
 445                        gitstring="$c${b##refs/heads/}${f:+$z$f}$r$p"
 446                fi
 447                gitstring=$(printf -- "$printf_format" "$gitstring")
 448                PS1="$ps1pc_start$gitstring$ps1pc_end"
 449        else
 450                # NO color option unless in PROMPT_COMMAND mode
 451                printf -- "$printf_format" "$c${b##refs/heads/}${f:+$z$f}$r$p"
 452        fi
 453}