Merge branch 'mh/ref-races'
[git] / contrib / completion / git-prompt.sh
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 # __gitdir accepts 0 or 1 arguments (i.e., location)
84 # returns location of .git repo
85 __gitdir ()
86 {
87         # Note: this function is duplicated in git-completion.bash
88         # When updating it, make sure you update the other one to match.
89         if [ -z "${1-}" ]; then
90                 if [ -n "${__git_dir-}" ]; then
91                         echo "$__git_dir"
92                 elif [ -n "${GIT_DIR-}" ]; then
93                         test -d "${GIT_DIR-}" || return 1
94                         echo "$GIT_DIR"
95                 elif [ -d .git ]; then
96                         echo .git
97                 else
98                         git rev-parse --git-dir 2>/dev/null
99                 fi
100         elif [ -d "$1/.git" ]; then
101                 echo "$1/.git"
102         else
103                 echo "$1"
104         fi
105 }
106
107 # stores the divergence from upstream in $p
108 # used by GIT_PS1_SHOWUPSTREAM
109 __git_ps1_show_upstream ()
110 {
111         local key value
112         local svn_remote svn_url_pattern count n
113         local upstream=git legacy="" verbose=""
114
115         svn_remote=()
116         # get some config options from git-config
117         local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
118         while read -r key value; do
119                 case "$key" in
120                 bash.showupstream)
121                         GIT_PS1_SHOWUPSTREAM="$value"
122                         if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
123                                 p=""
124                                 return
125                         fi
126                         ;;
127                 svn-remote.*.url)
128                         svn_remote[$((${#svn_remote[@]} + 1))]="$value"
129                         svn_url_pattern+="\\|$value"
130                         upstream=svn+git # default upstream is SVN if available, else git
131                         ;;
132                 esac
133         done <<< "$output"
134
135         # parse configuration values
136         for option in ${GIT_PS1_SHOWUPSTREAM}; do
137                 case "$option" in
138                 git|svn) upstream="$option" ;;
139                 verbose) verbose=1 ;;
140                 legacy)  legacy=1  ;;
141                 esac
142         done
143
144         # Find our upstream
145         case "$upstream" in
146         git)    upstream="@{upstream}" ;;
147         svn*)
148                 # get the upstream from the "git-svn-id: ..." in a commit message
149                 # (git-svn uses essentially the same procedure internally)
150                 local -a svn_upstream
151                 svn_upstream=($(git log --first-parent -1 \
152                                         --grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
153                 if [[ 0 -ne ${#svn_upstream[@]} ]]; then
154                         svn_upstream=${svn_upstream[${#svn_upstream[@]} - 2]}
155                         svn_upstream=${svn_upstream%@*}
156                         local n_stop="${#svn_remote[@]}"
157                         for ((n=1; n <= n_stop; n++)); do
158                                 svn_upstream=${svn_upstream#${svn_remote[$n]}}
159                         done
160
161                         if [[ -z "$svn_upstream" ]]; then
162                                 # default branch name for checkouts with no layout:
163                                 upstream=${GIT_SVN_ID:-git-svn}
164                         else
165                                 upstream=${svn_upstream#/}
166                         fi
167                 elif [[ "svn+git" = "$upstream" ]]; then
168                         upstream="@{upstream}"
169                 fi
170                 ;;
171         esac
172
173         # Find how many commits we are ahead/behind our upstream
174         if [[ -z "$legacy" ]]; then
175                 count="$(git rev-list --count --left-right \
176                                 "$upstream"...HEAD 2>/dev/null)"
177         else
178                 # produce equivalent output to --count for older versions of git
179                 local commits
180                 if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
181                 then
182                         local commit behind=0 ahead=0
183                         for commit in $commits
184                         do
185                                 case "$commit" in
186                                 "<"*) ((behind++)) ;;
187                                 *)    ((ahead++))  ;;
188                                 esac
189                         done
190                         count="$behind  $ahead"
191                 else
192                         count=""
193                 fi
194         fi
195
196         # calculate the result
197         if [[ -z "$verbose" ]]; then
198                 case "$count" in
199                 "") # no upstream
200                         p="" ;;
201                 "0      0") # equal to upstream
202                         p="=" ;;
203                 "0      "*) # ahead of upstream
204                         p=">" ;;
205                 *"      0") # behind upstream
206                         p="<" ;;
207                 *)          # diverged from upstream
208                         p="<>" ;;
209                 esac
210         else
211                 case "$count" in
212                 "") # no upstream
213                         p="" ;;
214                 "0      0") # equal to upstream
215                         p=" u=" ;;
216                 "0      "*) # ahead of upstream
217                         p=" u+${count#0 }" ;;
218                 *"      0") # behind upstream
219                         p=" u-${count%  0}" ;;
220                 *)          # diverged from upstream
221                         p=" u+${count#* }-${count%      *}" ;;
222                 esac
223         fi
224
225 }
226
227 # Helper function that is meant to be called from __git_ps1.  It
228 # builds up a gitstring injecting color codes into the appropriate
229 # places.
230 __git_ps1_colorize_gitstring ()
231 {
232         if [[ -n ${ZSH_VERSION-} ]]; then
233                 local c_red='%F{red}'
234                 local c_green='%F{green}'
235                 local c_lblue='%F{blue}'
236                 local c_clear='%f'
237                 local bad_color=$c_red
238                 local ok_color=$c_green
239                 local branch_color="$c_clear"
240                 local flags_color="$c_lblue"
241                 local branchstring="$c${b##refs/heads/}"
242
243                 if [ $detached = no ]; then
244                         branch_color="$ok_color"
245                 else
246                         branch_color="$bad_color"
247                 fi
248
249                 gitstring="$branch_color$branchstring$c_clear"
250
251                 if [ -n "$w$i$s$u$r$p" ]; then
252                         gitstring="$gitstring$z"
253                 fi
254                 if [ "$w" = "*" ]; then
255                         gitstring="$gitstring$bad_color$w"
256                 fi
257                 if [ -n "$i" ]; then
258                         gitstring="$gitstring$ok_color$i"
259                 fi
260                 if [ -n "$s" ]; then
261                         gitstring="$gitstring$flags_color$s"
262                 fi
263                 if [ -n "$u" ]; then
264                         gitstring="$gitstring$bad_color$u"
265                 fi
266                 gitstring="$gitstring$c_clear$r$p"
267                 return
268         fi
269         local c_red='\e[31m'
270         local c_green='\e[32m'
271         local c_lblue='\e[1;34m'
272         local c_clear='\e[0m'
273         local bad_color=$c_red
274         local ok_color=$c_green
275         local branch_color="$c_clear"
276         local flags_color="$c_lblue"
277         local branchstring="$c${b##refs/heads/}"
278
279         if [ $detached = no ]; then
280                 branch_color="$ok_color"
281         else
282                 branch_color="$bad_color"
283         fi
284
285         # Setting gitstring directly with \[ and \] around colors
286         # is necessary to prevent wrapping issues!
287         gitstring="\[$branch_color\]$branchstring\[$c_clear\]"
288
289         if [ -n "$w$i$s$u$r$p" ]; then
290                 gitstring="$gitstring$z"
291         fi
292         if [ "$w" = "*" ]; then
293                 gitstring="$gitstring\[$bad_color\]$w"
294         fi
295         if [ -n "$i" ]; then
296                 gitstring="$gitstring\[$ok_color\]$i"
297         fi
298         if [ -n "$s" ]; then
299                 gitstring="$gitstring\[$flags_color\]$s"
300         fi
301         if [ -n "$u" ]; then
302                 gitstring="$gitstring\[$bad_color\]$u"
303         fi
304         gitstring="$gitstring\[$c_clear\]$r$p"
305 }
306
307 # __git_ps1 accepts 0 or 1 arguments (i.e., format string)
308 # when called from PS1 using command substitution
309 # in this mode it prints text to add to bash PS1 prompt (includes branch name)
310 #
311 # __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
312 # in that case it _sets_ PS1. The arguments are parts of a PS1 string.
313 # when two arguments are given, the first is prepended and the second appended
314 # to the state string when assigned to PS1.
315 # The optional third parameter will be used as printf format string to further
316 # customize the output of the git-status string.
317 # In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
318 __git_ps1 ()
319 {
320         local pcmode=no
321         local detached=no
322         local ps1pc_start='\u@\h:\w '
323         local ps1pc_end='\$ '
324         local printf_format=' (%s)'
325
326         case "$#" in
327                 2|3)    pcmode=yes
328                         ps1pc_start="$1"
329                         ps1pc_end="$2"
330                         printf_format="${3:-$printf_format}"
331                 ;;
332                 0|1)    printf_format="${1:-$printf_format}"
333                 ;;
334                 *)      return
335                 ;;
336         esac
337
338         local g="$(__gitdir)"
339         if [ -z "$g" ]; then
340                 if [ $pcmode = yes ]; then
341                         #In PC mode PS1 always needs to be set
342                         PS1="$ps1pc_start$ps1pc_end"
343                 fi
344         else
345                 local r=""
346                 local b=""
347                 local step=""
348                 local total=""
349                 if [ -d "$g/rebase-merge" ]; then
350                         b="$(cat "$g/rebase-merge/head-name" 2>/dev/null)"
351                         step=$(cat "$g/rebase-merge/msgnum" 2>/dev/null)
352                         total=$(cat "$g/rebase-merge/end" 2>/dev/null)
353                         if [ -f "$g/rebase-merge/interactive" ]; then
354                                 r="|REBASE-i"
355                         else
356                                 r="|REBASE-m"
357                         fi
358                 else
359                         if [ -d "$g/rebase-apply" ]; then
360                                 step=$(cat "$g/rebase-apply/next" 2>/dev/null)
361                                 total=$(cat "$g/rebase-apply/last" 2>/dev/null)
362                                 if [ -f "$g/rebase-apply/rebasing" ]; then
363                                         b="$(cat "$g/rebase-apply/head-name" 2>/dev/null)"
364                                         r="|REBASE"
365                                 elif [ -f "$g/rebase-apply/applying" ]; then
366                                         r="|AM"
367                                 else
368                                         r="|AM/REBASE"
369                                 fi
370                         elif [ -f "$g/MERGE_HEAD" ]; then
371                                 r="|MERGING"
372                         elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
373                                 r="|CHERRY-PICKING"
374                         elif [ -f "$g/REVERT_HEAD" ]; then
375                                 r="|REVERTING"
376                         elif [ -f "$g/BISECT_LOG" ]; then
377                                 r="|BISECTING"
378                         fi
379
380                         test -n "$b" ||
381                         b="$(git symbolic-ref HEAD 2>/dev/null)" || {
382                                 detached=yes
383                                 b="$(
384                                 case "${GIT_PS1_DESCRIBE_STYLE-}" in
385                                 (contains)
386                                         git describe --contains HEAD ;;
387                                 (branch)
388                                         git describe --contains --all HEAD ;;
389                                 (describe)
390                                         git describe HEAD ;;
391                                 (* | default)
392                                         git describe --tags --exact-match HEAD ;;
393                                 esac 2>/dev/null)" ||
394
395                                 b="$(cut -c1-7 "$g/HEAD" 2>/dev/null)..." ||
396                                 b="unknown"
397                                 b="($b)"
398                         }
399                 fi
400
401                 if [ -n "$step" ] && [ -n "$total" ]; then
402                         r="$r $step/$total"
403                 fi
404
405                 local w=""
406                 local i=""
407                 local s=""
408                 local u=""
409                 local c=""
410                 local p=""
411
412                 if [ "true" = "$(git rev-parse --is-inside-git-dir 2>/dev/null)" ]; then
413                         if [ "true" = "$(git rev-parse --is-bare-repository 2>/dev/null)" ]; then
414                                 c="BARE:"
415                         else
416                                 b="GIT_DIR!"
417                         fi
418                 elif [ "true" = "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
419                         if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
420                            [ "$(git config --bool bash.showDirtyState)" != "false" ]
421                         then
422                                 git diff --no-ext-diff --quiet --exit-code || w="*"
423                                 if git rev-parse --quiet --verify HEAD >/dev/null; then
424                                         git diff-index --cached --quiet HEAD -- || i="+"
425                                 else
426                                         i="#"
427                                 fi
428                         fi
429                         if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ]; then
430                                 git rev-parse --verify refs/stash >/dev/null 2>&1 && s="$"
431                         fi
432
433                         if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
434                            [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
435                            [ -n "$(git ls-files --others --exclude-standard)" ]
436                         then
437                                 u="%${ZSH_VERSION+%}"
438                         fi
439
440                         if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
441                                 __git_ps1_show_upstream
442                         fi
443                 fi
444
445                 local z="${GIT_PS1_STATESEPARATOR-" "}"
446                 local f="$w$i$s$u"
447                 if [ $pcmode = yes ]; then
448                         local gitstring=
449                         if [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
450                                 __git_ps1_colorize_gitstring
451                         else
452                                 gitstring="$c${b##refs/heads/}${f:+$z$f}$r$p"
453                         fi
454                         gitstring=$(printf -- "$printf_format" "$gitstring")
455                         PS1="$ps1pc_start$gitstring$ps1pc_end"
456                 else
457                         # NO color option unless in PROMPT_COMMAND mode
458                         printf -- "$printf_format" "$c${b##refs/heads/}${f:+$z$f}$r$p"
459                 fi
460         fi
461 }