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