git-prompt.sh 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 repository status 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: setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
  17. # the optional argument will be used as format string.
  18. # 3b) Alternatively, for a slightly faster prompt, __git_ps1 can
  19. # be used for PROMPT_COMMAND in Bash or for precmd() in Zsh
  20. # with two parameters, <pre> and <post>, which are strings
  21. # you would put in $PS1 before and after the status string
  22. # generated by the git-prompt machinery. e.g.
  23. # Bash: 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. # ZSH: precmd () { __git_ps1 "%n" ":%~$ " "|%s" }
  28. # will show username, pipe, then various status string,
  29. # followed by colon, cwd, dollar and SP, as your prompt.
  30. # Optionally, you can supply a third argument with a printf
  31. # format string to finetune the output of the branch status
  32. #
  33. # The repository status will be displayed only if you are currently in a
  34. # git repository. The %s token is the placeholder for the shown status.
  35. #
  36. # The prompt status always includes the current branch name.
  37. #
  38. # In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty value,
  39. # unstaged (*) and staged (+) changes will be shown next to the branch
  40. # name. You can configure this per-repository with the
  41. # bash.showDirtyState variable, which defaults to true once
  42. # GIT_PS1_SHOWDIRTYSTATE is enabled.
  43. #
  44. # You can also see if currently something is stashed, by setting
  45. # GIT_PS1_SHOWSTASHSTATE to a nonempty value. If something is stashed,
  46. # then a '$' will be shown next to the branch name.
  47. #
  48. # If you would like to see if there're untracked files, then you can set
  49. # GIT_PS1_SHOWUNTRACKEDFILES to a nonempty value. If there're untracked
  50. # files, then a '%' will be shown next to the branch name. You can
  51. # configure this per-repository with the bash.showUntrackedFiles
  52. # variable, which defaults to true once GIT_PS1_SHOWUNTRACKEDFILES is
  53. # enabled.
  54. #
  55. # If you would like to see the difference between HEAD and its upstream,
  56. # set GIT_PS1_SHOWUPSTREAM="auto". A "<" indicates you are behind, ">"
  57. # indicates you are ahead, "<>" indicates you have diverged and "="
  58. # indicates that there is no difference. You can further control
  59. # behaviour by setting GIT_PS1_SHOWUPSTREAM to a space-separated list
  60. # of values:
  61. #
  62. # verbose show number of commits ahead/behind (+/-) upstream
  63. # name if verbose, then also show the upstream abbrev name
  64. # legacy don't use the '--count' option available in recent
  65. # versions of git-rev-list
  66. # git always compare HEAD to @{upstream}
  67. # svn always compare HEAD to your SVN upstream
  68. #
  69. # You can change the separator between the branch name and the above
  70. # state symbols by setting GIT_PS1_STATESEPARATOR. The default separator
  71. # is SP.
  72. #
  73. # By default, __git_ps1 will compare HEAD to your SVN upstream if it can
  74. # find one, or @{upstream} otherwise. Once you have set
  75. # GIT_PS1_SHOWUPSTREAM, you can override it on a per-repository basis by
  76. # setting the bash.showUpstream config variable.
  77. #
  78. # If you would like to see more information about the identity of
  79. # commits checked out as a detached HEAD, set GIT_PS1_DESCRIBE_STYLE
  80. # to one of these values:
  81. #
  82. # contains relative to newer annotated tag (v1.6.3.2~35)
  83. # branch relative to newer tag or branch (master~4)
  84. # describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
  85. # tag relative to any older tag (v1.6.3.1-13-gdd42c2f)
  86. # default exactly matching tag
  87. #
  88. # If you would like a colored hint about the current dirty state, set
  89. # GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
  90. # the colored output of "git status -sb" and are available only when
  91. # using __git_ps1 for PROMPT_COMMAND or precmd.
  92. #
  93. # If you would like __git_ps1 to do nothing in the case when the current
  94. # directory is set up to be ignored by git, then set
  95. # GIT_PS1_HIDE_IF_PWD_IGNORED to a nonempty value. Override this on the
  96. # repository level by setting bash.hideIfPwdIgnored to "false".
  97. # check whether printf supports -v
  98. __git_printf_supports_v=
  99. printf -v __git_printf_supports_v -- '%s' yes >/dev/null 2>&1
  100. # stores the divergence from upstream in $p
  101. # used by GIT_PS1_SHOWUPSTREAM
  102. __git_ps1_show_upstream ()
  103. {
  104. local key value
  105. local svn_remote svn_url_pattern count n
  106. local upstream=git legacy="" verbose="" name=""
  107. svn_remote=()
  108. # get some config options from git-config
  109. local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
  110. while read -r key value; do
  111. case "$key" in
  112. bash.showupstream)
  113. GIT_PS1_SHOWUPSTREAM="$value"
  114. if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
  115. p=""
  116. return
  117. fi
  118. ;;
  119. svn-remote.*.url)
  120. svn_remote[$((${#svn_remote[@]} + 1))]="$value"
  121. svn_url_pattern="$svn_url_pattern\\|$value"
  122. upstream=svn+git # default upstream is SVN if available, else git
  123. ;;
  124. esac
  125. done <<< "$output"
  126. # parse configuration values
  127. for option in ${GIT_PS1_SHOWUPSTREAM}; do
  128. case "$option" in
  129. git|svn) upstream="$option" ;;
  130. verbose) verbose=1 ;;
  131. legacy) legacy=1 ;;
  132. name) name=1 ;;
  133. esac
  134. done
  135. # Find our upstream
  136. case "$upstream" in
  137. git) upstream="@{upstream}" ;;
  138. svn*)
  139. # get the upstream from the "git-svn-id: ..." in a commit message
  140. # (git-svn uses essentially the same procedure internally)
  141. local -a svn_upstream
  142. svn_upstream=($(git log --first-parent -1 \
  143. --grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
  144. if [[ 0 -ne ${#svn_upstream[@]} ]]; then
  145. svn_upstream=${svn_upstream[${#svn_upstream[@]} - 2]}
  146. svn_upstream=${svn_upstream%@*}
  147. local n_stop="${#svn_remote[@]}"
  148. for ((n=1; n <= n_stop; n++)); do
  149. svn_upstream=${svn_upstream#${svn_remote[$n]}}
  150. done
  151. if [[ -z "$svn_upstream" ]]; then
  152. # default branch name for checkouts with no layout:
  153. upstream=${GIT_SVN_ID:-git-svn}
  154. else
  155. upstream=${svn_upstream#/}
  156. fi
  157. elif [[ "svn+git" = "$upstream" ]]; then
  158. upstream="@{upstream}"
  159. fi
  160. ;;
  161. esac
  162. # Find how many commits we are ahead/behind our upstream
  163. if [[ -z "$legacy" ]]; then
  164. count="$(git rev-list --count --left-right \
  165. "$upstream"...HEAD 2>/dev/null)"
  166. else
  167. # produce equivalent output to --count for older versions of git
  168. local commits
  169. if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
  170. then
  171. local commit behind=0 ahead=0
  172. for commit in $commits
  173. do
  174. case "$commit" in
  175. "<"*) ((behind++)) ;;
  176. *) ((ahead++)) ;;
  177. esac
  178. done
  179. count="$behind $ahead"
  180. else
  181. count=""
  182. fi
  183. fi
  184. # calculate the result
  185. if [[ -z "$verbose" ]]; then
  186. case "$count" in
  187. "") # no upstream
  188. p="" ;;
  189. "0 0") # equal to upstream
  190. p="=" ;;
  191. "0 "*) # ahead of upstream
  192. p=">" ;;
  193. *" 0") # behind upstream
  194. p="<" ;;
  195. *) # diverged from upstream
  196. p="<>" ;;
  197. esac
  198. else
  199. case "$count" in
  200. "") # no upstream
  201. p="" ;;
  202. "0 0") # equal to upstream
  203. p=" u=" ;;
  204. "0 "*) # ahead of upstream
  205. p=" u+${count#0 }" ;;
  206. *" 0") # behind upstream
  207. p=" u-${count% 0}" ;;
  208. *) # diverged from upstream
  209. p=" u+${count#* }-${count% *}" ;;
  210. esac
  211. if [[ -n "$count" && -n "$name" ]]; then
  212. __git_ps1_upstream_name=$(git rev-parse \
  213. --abbrev-ref "$upstream" 2>/dev/null)
  214. if [ "$pcmode" = yes ] && [ "$ps1_expanded" = yes ]; then
  215. p="$p \${__git_ps1_upstream_name}"
  216. else
  217. p="$p ${__git_ps1_upstream_name}"
  218. # not needed anymore; keep user's
  219. # environment clean
  220. unset __git_ps1_upstream_name
  221. fi
  222. fi
  223. fi
  224. }
  225. # Helper function that is meant to be called from __git_ps1. It
  226. # injects color codes into the appropriate gitstring variables used
  227. # to build a gitstring.
  228. __git_ps1_colorize_gitstring ()
  229. {
  230. if [[ -n "${ZSH_VERSION-}" ]]; then
  231. local c_red='%F{red}'
  232. local c_green='%F{green}'
  233. local c_lblue='%F{blue}'
  234. local c_clear='%f'
  235. else
  236. # Using \[ and \] around colors is necessary to prevent
  237. # issues with command line editing/browsing/completion!
  238. local c_red='\[\e[31m\]'
  239. local c_green='\[\e[32m\]'
  240. local c_lblue='\[\e[1;34m\]'
  241. local c_clear='\[\e[0m\]'
  242. fi
  243. local bad_color=$c_red
  244. local ok_color=$c_green
  245. local flags_color="$c_lblue"
  246. local branch_color=""
  247. if [ "$detached" = no ]; then
  248. branch_color="$ok_color"
  249. else
  250. branch_color="$bad_color"
  251. fi
  252. c="$branch_color$c"
  253. z="$c_clear$z"
  254. if [ "$w" = "*" ]; then
  255. w="$bad_color$w"
  256. fi
  257. if [ -n "$i" ]; then
  258. i="$ok_color$i"
  259. fi
  260. if [ -n "$s" ]; then
  261. s="$flags_color$s"
  262. fi
  263. if [ -n "$u" ]; then
  264. u="$bad_color$u"
  265. fi
  266. r="$c_clear$r"
  267. }
  268. # Helper function to read the first line of a file into a variable.
  269. # __git_eread requires 2 arguments, the file path and the name of the
  270. # variable, in that order.
  271. __git_eread ()
  272. {
  273. test -r "$1" && IFS=$'\r\n' read "$2" <"$1"
  274. }
  275. # __git_ps1 accepts 0 or 1 arguments (i.e., format string)
  276. # when called from PS1 using command substitution
  277. # in this mode it prints text to add to bash PS1 prompt (includes branch name)
  278. #
  279. # __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
  280. # in that case it _sets_ PS1. The arguments are parts of a PS1 string.
  281. # when two arguments are given, the first is prepended and the second appended
  282. # to the state string when assigned to PS1.
  283. # The optional third parameter will be used as printf format string to further
  284. # customize the output of the git-status string.
  285. # In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
  286. __git_ps1 ()
  287. {
  288. # preserve exit status
  289. local exit=$?
  290. local pcmode=no
  291. local detached=no
  292. local ps1pc_start='\u@\h:\w '
  293. local ps1pc_end='\$ '
  294. local printf_format=' (%s)'
  295. case "$#" in
  296. 2|3) pcmode=yes
  297. ps1pc_start="$1"
  298. ps1pc_end="$2"
  299. printf_format="${3:-$printf_format}"
  300. # set PS1 to a plain prompt so that we can
  301. # simply return early if the prompt should not
  302. # be decorated
  303. PS1="$ps1pc_start$ps1pc_end"
  304. ;;
  305. 0|1) printf_format="${1:-$printf_format}"
  306. ;;
  307. *) return $exit
  308. ;;
  309. esac
  310. # ps1_expanded: This variable is set to 'yes' if the shell
  311. # subjects the value of PS1 to parameter expansion:
  312. #
  313. # * bash does unless the promptvars option is disabled
  314. # * zsh does not unless the PROMPT_SUBST option is set
  315. # * POSIX shells always do
  316. #
  317. # If the shell would expand the contents of PS1 when drawing
  318. # the prompt, a raw ref name must not be included in PS1.
  319. # This protects the user from arbitrary code execution via
  320. # specially crafted ref names. For example, a ref named
  321. # 'refs/heads/$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)' might cause the
  322. # shell to execute 'sudo rm -rf /' when the prompt is drawn.
  323. #
  324. # Instead, the ref name should be placed in a separate global
  325. # variable (in the __git_ps1_* namespace to avoid colliding
  326. # with the user's environment) and that variable should be
  327. # referenced from PS1. For example:
  328. #
  329. # __git_ps1_foo=$(do_something_to_get_ref_name)
  330. # PS1="...stuff...\${__git_ps1_foo}...stuff..."
  331. #
  332. # If the shell does not expand the contents of PS1, the raw
  333. # ref name must be included in PS1.
  334. #
  335. # The value of this variable is only relevant when in pcmode.
  336. #
  337. # Assume that the shell follows the POSIX specification and
  338. # expands PS1 unless determined otherwise. (This is more
  339. # likely to be correct if the user has a non-bash, non-zsh
  340. # shell and safer than the alternative if the assumption is
  341. # incorrect.)
  342. #
  343. local ps1_expanded=yes
  344. [ -z "${ZSH_VERSION-}" ] || [[ -o PROMPT_SUBST ]] || ps1_expanded=no
  345. [ -z "${BASH_VERSION-}" ] || shopt -q promptvars || ps1_expanded=no
  346. local repo_info rev_parse_exit_code
  347. repo_info="$(git rev-parse --git-dir --is-inside-git-dir \
  348. --is-bare-repository --is-inside-work-tree \
  349. --short HEAD 2>/dev/null)"
  350. rev_parse_exit_code="$?"
  351. if [ -z "$repo_info" ]; then
  352. return $exit
  353. fi
  354. local short_sha=""
  355. if [ "$rev_parse_exit_code" = "0" ]; then
  356. short_sha="${repo_info##*$'\n'}"
  357. repo_info="${repo_info%$'\n'*}"
  358. fi
  359. local inside_worktree="${repo_info##*$'\n'}"
  360. repo_info="${repo_info%$'\n'*}"
  361. local bare_repo="${repo_info##*$'\n'}"
  362. repo_info="${repo_info%$'\n'*}"
  363. local inside_gitdir="${repo_info##*$'\n'}"
  364. local g="${repo_info%$'\n'*}"
  365. if [ "true" = "$inside_worktree" ] &&
  366. [ -n "${GIT_PS1_HIDE_IF_PWD_IGNORED-}" ] &&
  367. [ "$(git config --bool bash.hideIfPwdIgnored)" != "false" ] &&
  368. git check-ignore -q .
  369. then
  370. return $exit
  371. fi
  372. local r=""
  373. local b=""
  374. local step=""
  375. local total=""
  376. if [ -d "$g/rebase-merge" ]; then
  377. __git_eread "$g/rebase-merge/head-name" b
  378. __git_eread "$g/rebase-merge/msgnum" step
  379. __git_eread "$g/rebase-merge/end" total
  380. if [ -f "$g/rebase-merge/interactive" ]; then
  381. r="|REBASE-i"
  382. else
  383. r="|REBASE-m"
  384. fi
  385. else
  386. if [ -d "$g/rebase-apply" ]; then
  387. __git_eread "$g/rebase-apply/next" step
  388. __git_eread "$g/rebase-apply/last" total
  389. if [ -f "$g/rebase-apply/rebasing" ]; then
  390. __git_eread "$g/rebase-apply/head-name" b
  391. r="|REBASE"
  392. elif [ -f "$g/rebase-apply/applying" ]; then
  393. r="|AM"
  394. else
  395. r="|AM/REBASE"
  396. fi
  397. elif [ -f "$g/MERGE_HEAD" ]; then
  398. r="|MERGING"
  399. elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
  400. r="|CHERRY-PICKING"
  401. elif [ -f "$g/REVERT_HEAD" ]; then
  402. r="|REVERTING"
  403. elif [ -f "$g/BISECT_LOG" ]; then
  404. r="|BISECTING"
  405. fi
  406. if [ -n "$b" ]; then
  407. :
  408. elif [ -h "$g/HEAD" ]; then
  409. # symlink symbolic ref
  410. b="$(git symbolic-ref HEAD 2>/dev/null)"
  411. else
  412. local head=""
  413. if ! __git_eread "$g/HEAD" head; then
  414. return $exit
  415. fi
  416. # is it a symbolic ref?
  417. b="${head#ref: }"
  418. if [ "$head" = "$b" ]; then
  419. detached=yes
  420. b="$(
  421. case "${GIT_PS1_DESCRIBE_STYLE-}" in
  422. (contains)
  423. git describe --contains HEAD ;;
  424. (branch)
  425. git describe --contains --all HEAD ;;
  426. (tag)
  427. git describe --tags HEAD ;;
  428. (describe)
  429. git describe HEAD ;;
  430. (* | default)
  431. git describe --tags --exact-match HEAD ;;
  432. esac 2>/dev/null)" ||
  433. b="$short_sha..."
  434. b="($b)"
  435. fi
  436. fi
  437. fi
  438. if [ -n "$step" ] && [ -n "$total" ]; then
  439. r="$r $step/$total"
  440. fi
  441. local w=""
  442. local i=""
  443. local s=""
  444. local u=""
  445. local c=""
  446. local p=""
  447. if [ "true" = "$inside_gitdir" ]; then
  448. if [ "true" = "$bare_repo" ]; then
  449. c="BARE:"
  450. else
  451. b="GIT_DIR!"
  452. fi
  453. elif [ "true" = "$inside_worktree" ]; then
  454. if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
  455. [ "$(git config --bool bash.showDirtyState)" != "false" ]
  456. then
  457. git diff --no-ext-diff --quiet || w="*"
  458. git diff --no-ext-diff --cached --quiet || i="+"
  459. if [ -z "$short_sha" ] && [ -z "$i" ]; then
  460. i="#"
  461. fi
  462. fi
  463. if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ] &&
  464. git rev-parse --verify --quiet refs/stash >/dev/null
  465. then
  466. s="$"
  467. fi
  468. if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
  469. [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
  470. git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*' >/dev/null 2>/dev/null
  471. then
  472. u="%${ZSH_VERSION+%}"
  473. fi
  474. if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
  475. __git_ps1_show_upstream
  476. fi
  477. fi
  478. local z="${GIT_PS1_STATESEPARATOR-" "}"
  479. # NO color option unless in PROMPT_COMMAND mode or it's Zsh
  480. if [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
  481. if [ "$pcmode" = yes ] || [ -n "${ZSH_VERSION-}" ]; then
  482. __git_ps1_colorize_gitstring
  483. fi
  484. fi
  485. b=${b##refs/heads/}
  486. if [ "$pcmode" = yes ] && [ "$ps1_expanded" = yes ]; then
  487. __git_ps1_branch_name=$b
  488. b="\${__git_ps1_branch_name}"
  489. fi
  490. local f="$w$i$s$u"
  491. local gitstring="$c$b${f:+$z$f}$r$p"
  492. if [ "$pcmode" = yes ]; then
  493. if [ "${__git_printf_supports_v-}" != yes ]; then
  494. gitstring=$(printf -- "$printf_format" "$gitstring")
  495. else
  496. printf -v gitstring -- "$printf_format" "$gitstring"
  497. fi
  498. PS1="$ps1pc_start$gitstring$ps1pc_end"
  499. else
  500. printf -- "$printf_format" "$gitstring"
  501. fi
  502. return $exit
  503. }