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