contrib / completion / git-prompt.shon commit Merge branch 'ta/api-index-doc' (6600dcb)
   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 to see more information about the identity of
  65# commits checked out as a detached HEAD, set GIT_PS1_DESCRIBE_STYLE
  66# to one of these values:
  67#
  68#     contains      relative to newer annotated tag (v1.6.3.2~35)
  69#     branch        relative to newer tag or branch (master~4)
  70#     describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
  71#     default       exactly matching tag
  72#
  73# If you would like a colored hint about the current dirty state, set
  74# GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
  75# the colored output of "git status -sb".
  76
  77# __gitdir accepts 0 or 1 arguments (i.e., location)
  78# returns location of .git repo
  79__gitdir ()
  80{
  81        # Note: this function is duplicated in git-completion.bash
  82        # When updating it, make sure you update the other one to match.
  83        if [ -z "${1-}" ]; then
  84                if [ -n "${__git_dir-}" ]; then
  85                        echo "$__git_dir"
  86                elif [ -n "${GIT_DIR-}" ]; then
  87                        test -d "${GIT_DIR-}" || return 1
  88                        echo "$GIT_DIR"
  89                elif [ -d .git ]; then
  90                        echo .git
  91                else
  92                        git rev-parse --git-dir 2>/dev/null
  93                fi
  94        elif [ -d "$1/.git" ]; then
  95                echo "$1/.git"
  96        else
  97                echo "$1"
  98        fi
  99}
 100
 101# stores the divergence from upstream in $p
 102# used by GIT_PS1_SHOWUPSTREAM
 103__git_ps1_show_upstream ()
 104{
 105        local key value
 106        local svn_remote svn_url_pattern count n
 107        local upstream=git legacy="" verbose=""
 108
 109        svn_remote=()
 110        # get some config options from git-config
 111        local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
 112        while read -r key value; do
 113                case "$key" in
 114                bash.showupstream)
 115                        GIT_PS1_SHOWUPSTREAM="$value"
 116                        if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
 117                                p=""
 118                                return
 119                        fi
 120                        ;;
 121                svn-remote.*.url)
 122                        svn_remote[ $((${#svn_remote[@]} + 1)) ]="$value"
 123                        svn_url_pattern+="\\|$value"
 124                        upstream=svn+git # default upstream is SVN if available, else git
 125                        ;;
 126                esac
 127        done <<< "$output"
 128
 129        # parse configuration values
 130        for option in ${GIT_PS1_SHOWUPSTREAM}; do
 131                case "$option" in
 132                git|svn) upstream="$option" ;;
 133                verbose) verbose=1 ;;
 134                legacy)  legacy=1  ;;
 135                esac
 136        done
 137
 138        # Find our upstream
 139        case "$upstream" in
 140        git)    upstream="@{upstream}" ;;
 141        svn*)
 142                # get the upstream from the "git-svn-id: ..." in a commit message
 143                # (git-svn uses essentially the same procedure internally)
 144                local svn_upstream=($(git log --first-parent -1 \
 145                                        --grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
 146                if [[ 0 -ne ${#svn_upstream[@]} ]]; then
 147                        svn_upstream=${svn_upstream[ ${#svn_upstream[@]} - 2 ]}
 148                        svn_upstream=${svn_upstream%@*}
 149                        local n_stop="${#svn_remote[@]}"
 150                        for ((n=1; n <= n_stop; n++)); do
 151                                svn_upstream=${svn_upstream#${svn_remote[$n]}}
 152                        done
 153
 154                        if [[ -z "$svn_upstream" ]]; then
 155                                # default branch name for checkouts with no layout:
 156                                upstream=${GIT_SVN_ID:-git-svn}
 157                        else
 158                                upstream=${svn_upstream#/}
 159                        fi
 160                elif [[ "svn+git" = "$upstream" ]]; then
 161                        upstream="@{upstream}"
 162                fi
 163                ;;
 164        esac
 165
 166        # Find how many commits we are ahead/behind our upstream
 167        if [[ -z "$legacy" ]]; then
 168                count="$(git rev-list --count --left-right \
 169                                "$upstream"...HEAD 2>/dev/null)"
 170        else
 171                # produce equivalent output to --count for older versions of git
 172                local commits
 173                if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
 174                then
 175                        local commit behind=0 ahead=0
 176                        for commit in $commits
 177                        do
 178                                case "$commit" in
 179                                "<"*) ((behind++)) ;;
 180                                *)    ((ahead++))  ;;
 181                                esac
 182                        done
 183                        count="$behind  $ahead"
 184                else
 185                        count=""
 186                fi
 187        fi
 188
 189        # calculate the result
 190        if [[ -z "$verbose" ]]; then
 191                case "$count" in
 192                "") # no upstream
 193                        p="" ;;
 194                "0      0") # equal to upstream
 195                        p="=" ;;
 196                "0      "*) # ahead of upstream
 197                        p=">" ;;
 198                *"      0") # behind upstream
 199                        p="<" ;;
 200                *)          # diverged from upstream
 201                        p="<>" ;;
 202                esac
 203        else
 204                case "$count" in
 205                "") # no upstream
 206                        p="" ;;
 207                "0      0") # equal to upstream
 208                        p=" u=" ;;
 209                "0      "*) # ahead of upstream
 210                        p=" u+${count#0 }" ;;
 211                *"      0") # behind upstream
 212                        p=" u-${count%  0}" ;;
 213                *)          # diverged from upstream
 214                        p=" u+${count#* }-${count%      *}" ;;
 215                esac
 216        fi
 217
 218}
 219
 220
 221# __git_ps1 accepts 0 or 1 arguments (i.e., format string)
 222# when called from PS1 using command substitution
 223# in this mode it prints text to add to bash PS1 prompt (includes branch name)
 224#
 225# __git_ps1 requires 2 arguments when called from PROMPT_COMMAND (pc)
 226# in that case it _sets_ PS1. The arguments are parts of a PS1 string.
 227# when both arguments are given, the first is prepended and the second appended
 228# to the state string when assigned to PS1.
 229# In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
 230__git_ps1 ()
 231{
 232        local pcmode=no
 233        local detached=no
 234        local ps1pc_start='\u@\h:\w '
 235        local ps1pc_end='\$ '
 236        local printf_format=' (%s)'
 237
 238        case "$#" in
 239                2)      pcmode=yes
 240                        ps1pc_start="$1"
 241                        ps1pc_end="$2"
 242                ;;
 243                0|1)    printf_format="${1:-$printf_format}"
 244                ;;
 245                *)      return
 246                ;;
 247        esac
 248
 249        local g="$(__gitdir)"
 250        if [ -z "$g" ]; then
 251                if [ $pcmode = yes ]; then
 252                        #In PC mode PS1 always needs to be set
 253                        PS1="$ps1pc_start$ps1pc_end"
 254                fi
 255        else
 256                local r=""
 257                local b=""
 258                if [ -f "$g/rebase-merge/interactive" ]; then
 259                        r="|REBASE-i"
 260                        b="$(cat "$g/rebase-merge/head-name")"
 261                elif [ -d "$g/rebase-merge" ]; then
 262                        r="|REBASE-m"
 263                        b="$(cat "$g/rebase-merge/head-name")"
 264                else
 265                        if [ -d "$g/rebase-apply" ]; then
 266                                if [ -f "$g/rebase-apply/rebasing" ]; then
 267                                        r="|REBASE"
 268                                elif [ -f "$g/rebase-apply/applying" ]; then
 269                                        r="|AM"
 270                                else
 271                                        r="|AM/REBASE"
 272                                fi
 273                        elif [ -f "$g/MERGE_HEAD" ]; then
 274                                r="|MERGING"
 275                        elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
 276                                r="|CHERRY-PICKING"
 277                        elif [ -f "$g/BISECT_LOG" ]; then
 278                                r="|BISECTING"
 279                        fi
 280
 281                        b="$(git symbolic-ref HEAD 2>/dev/null)" || {
 282                                detached=yes
 283                                b="$(
 284                                case "${GIT_PS1_DESCRIBE_STYLE-}" in
 285                                (contains)
 286                                        git describe --contains HEAD ;;
 287                                (branch)
 288                                        git describe --contains --all HEAD ;;
 289                                (describe)
 290                                        git describe HEAD ;;
 291                                (* | default)
 292                                        git describe --tags --exact-match HEAD ;;
 293                                esac 2>/dev/null)" ||
 294
 295                                b="$(cut -c1-7 "$g/HEAD" 2>/dev/null)..." ||
 296                                b="unknown"
 297                                b="($b)"
 298                        }
 299                fi
 300
 301                local w=""
 302                local i=""
 303                local s=""
 304                local u=""
 305                local c=""
 306                local p=""
 307
 308                if [ "true" = "$(git rev-parse --is-inside-git-dir 2>/dev/null)" ]; then
 309                        if [ "true" = "$(git rev-parse --is-bare-repository 2>/dev/null)" ]; then
 310                                c="BARE:"
 311                        else
 312                                b="GIT_DIR!"
 313                        fi
 314                elif [ "true" = "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
 315                        if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ]; then
 316                                if [ "$(git config --bool bash.showDirtyState)" != "false" ]; then
 317                                        git diff --no-ext-diff --quiet --exit-code || w="*"
 318                                        if git rev-parse --quiet --verify HEAD >/dev/null; then
 319                                                git diff-index --cached --quiet HEAD -- || i="+"
 320                                        else
 321                                                i="#"
 322                                        fi
 323                                fi
 324                        fi
 325                        if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ]; then
 326                                git rev-parse --verify refs/stash >/dev/null 2>&1 && s="$"
 327                        fi
 328
 329                        if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ]; then
 330                                if [ -n "$(git ls-files --others --exclude-standard)" ]; then
 331                                        u="%"
 332                                fi
 333                        fi
 334
 335                        if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
 336                                __git_ps1_show_upstream
 337                        fi
 338                fi
 339
 340                local f="$w$i$s$u"
 341                if [ $pcmode = yes ]; then
 342                        if [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
 343                                local c_red='\e[31m'
 344                                local c_green='\e[32m'
 345                                local c_lblue='\e[1;34m'
 346                                local c_clear='\e[0m'
 347                                local bad_color=$c_red
 348                                local ok_color=$c_green
 349                                local branch_color="$c_clear"
 350                                local flags_color="$c_lblue"
 351                                local branchstring="$c${b##refs/heads/}"
 352
 353                                if [ $detached = no ]; then
 354                                        branch_color="$ok_color"
 355                                else
 356                                        branch_color="$bad_color"
 357                                fi
 358
 359                                # Setting PS1 directly with \[ and \] around colors
 360                                # is necessary to prevent wrapping issues!
 361                                PS1="$ps1pc_start (\[$branch_color\]$branchstring\[$c_clear\]"
 362
 363                                if [ -n "$w$i$s$u$r$p" ]; then
 364                                        PS1="$PS1 "
 365                                fi
 366                                if [ "$w" = "*" ]; then
 367                                        PS1="$PS1\[$bad_color\]$w"
 368                                fi
 369                                if [ -n "$i" ]; then
 370                                        PS1="$PS1\[$ok_color\]$i"
 371                                fi
 372                                if [ -n "$s" ]; then
 373                                        PS1="$PS1\[$flags_color\]$s"
 374                                fi
 375                                if [ -n "$u" ]; then
 376                                        PS1="$PS1\[$bad_color\]$u"
 377                                fi
 378                                PS1="$PS1\[$c_clear\]$r$p)$ps1pc_end"
 379                        else
 380                                PS1="$ps1pc_start ($c${b##refs/heads/}${f:+ $f}$r$p)$ps1pc_end"
 381                        fi
 382                else
 383                        # NO color option unless in PROMPT_COMMAND mode
 384                        printf -- "$printf_format" "$c${b##refs/heads/}${f:+ $f}$r$p"
 385                fi
 386        fi
 387}