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