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