.git-prompt.sh 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. # see if a cherry-pick or revert is in progress, if the user has committed a
  276. # conflict resolution with 'git commit' in the middle of a sequence of picks or
  277. # reverts then CHERRY_PICK_HEAD/REVERT_HEAD will not exist so we have to read
  278. # the todo file.
  279. __git_sequencer_status ()
  280. {
  281. local todo
  282. if test -f "$g/CHERRY_PICK_HEAD"
  283. then
  284. r="|CHERRY-PICKING"
  285. return 0;
  286. elif test -f "$g/REVERT_HEAD"
  287. then
  288. r="|REVERTING"
  289. return 0;
  290. elif __git_eread "$g/sequencer/todo" todo
  291. then
  292. case "$todo" in
  293. p[\ \ ]|pick[\ \ ]*)
  294. r="|CHERRY-PICKING"
  295. return 0
  296. ;;
  297. revert[\ \ ]*)
  298. r="|REVERTING"
  299. return 0
  300. ;;
  301. esac
  302. fi
  303. return 1
  304. }
  305. # __git_ps1 accepts 0 or 1 arguments (i.e., format string)
  306. # when called from PS1 using command substitution
  307. # in this mode it prints text to add to bash PS1 prompt (includes branch name)
  308. #
  309. # __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
  310. # in that case it _sets_ PS1. The arguments are parts of a PS1 string.
  311. # when two arguments are given, the first is prepended and the second appended
  312. # to the state string when assigned to PS1.
  313. # The optional third parameter will be used as printf format string to further
  314. # customize the output of the git-status string.
  315. # In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
  316. __git_ps1 ()
  317. {
  318. # preserve exit status
  319. local exit=$?
  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. case "$#" in
  326. 2|3) pcmode=yes
  327. ps1pc_start="$1"
  328. ps1pc_end="$2"
  329. printf_format="${3:-$printf_format}"
  330. # set PS1 to a plain prompt so that we can
  331. # simply return early if the prompt should not
  332. # be decorated
  333. PS1="$ps1pc_start$ps1pc_end"
  334. ;;
  335. 0|1) printf_format="${1:-$printf_format}"
  336. ;;
  337. *) return $exit
  338. ;;
  339. esac
  340. # ps1_expanded: This variable is set to 'yes' if the shell
  341. # subjects the value of PS1 to parameter expansion:
  342. #
  343. # * bash does unless the promptvars option is disabled
  344. # * zsh does not unless the PROMPT_SUBST option is set
  345. # * POSIX shells always do
  346. #
  347. # If the shell would expand the contents of PS1 when drawing
  348. # the prompt, a raw ref name must not be included in PS1.
  349. # This protects the user from arbitrary code execution via
  350. # specially crafted ref names. For example, a ref named
  351. # 'refs/heads/$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)' might cause the
  352. # shell to execute 'sudo rm -rf /' when the prompt is drawn.
  353. #
  354. # Instead, the ref name should be placed in a separate global
  355. # variable (in the __git_ps1_* namespace to avoid colliding
  356. # with the user's environment) and that variable should be
  357. # referenced from PS1. For example:
  358. #
  359. # __git_ps1_foo=$(do_something_to_get_ref_name)
  360. # PS1="...stuff...\${__git_ps1_foo}...stuff..."
  361. #
  362. # If the shell does not expand the contents of PS1, the raw
  363. # ref name must be included in PS1.
  364. #
  365. # The value of this variable is only relevant when in pcmode.
  366. #
  367. # Assume that the shell follows the POSIX specification and
  368. # expands PS1 unless determined otherwise. (This is more
  369. # likely to be correct if the user has a non-bash, non-zsh
  370. # shell and safer than the alternative if the assumption is
  371. # incorrect.)
  372. #
  373. local ps1_expanded=yes
  374. [ -z "${ZSH_VERSION-}" ] || [[ -o PROMPT_SUBST ]] || ps1_expanded=no
  375. [ -z "${BASH_VERSION-}" ] || shopt -q promptvars || ps1_expanded=no
  376. local repo_info rev_parse_exit_code
  377. repo_info="$(git rev-parse --git-dir --is-inside-git-dir \
  378. --is-bare-repository --is-inside-work-tree \
  379. --short HEAD 2>/dev/null)"
  380. rev_parse_exit_code="$?"
  381. if [ -z "$repo_info" ]; then
  382. return $exit
  383. fi
  384. local short_sha=""
  385. if [ "$rev_parse_exit_code" = "0" ]; then
  386. short_sha="${repo_info##*$'\n'}"
  387. repo_info="${repo_info%$'\n'*}"
  388. fi
  389. local inside_worktree="${repo_info##*$'\n'}"
  390. repo_info="${repo_info%$'\n'*}"
  391. local bare_repo="${repo_info##*$'\n'}"
  392. repo_info="${repo_info%$'\n'*}"
  393. local inside_gitdir="${repo_info##*$'\n'}"
  394. local g="${repo_info%$'\n'*}"
  395. if [ "true" = "$inside_worktree" ] &&
  396. [ -n "${GIT_PS1_HIDE_IF_PWD_IGNORED-}" ] &&
  397. [ "$(git config --bool bash.hideIfPwdIgnored)" != "false" ] &&
  398. git check-ignore -q .
  399. then
  400. return $exit
  401. fi
  402. local r=""
  403. local b=""
  404. local step=""
  405. local total=""
  406. if [ -d "$g/rebase-merge" ]; then
  407. __git_eread "$g/rebase-merge/head-name" b
  408. __git_eread "$g/rebase-merge/msgnum" step
  409. __git_eread "$g/rebase-merge/end" total
  410. r="|REBASE"
  411. else
  412. if [ -d "$g/rebase-apply" ]; then
  413. __git_eread "$g/rebase-apply/next" step
  414. __git_eread "$g/rebase-apply/last" total
  415. if [ -f "$g/rebase-apply/rebasing" ]; then
  416. __git_eread "$g/rebase-apply/head-name" b
  417. r="|REBASE"
  418. elif [ -f "$g/rebase-apply/applying" ]; then
  419. r="|AM"
  420. else
  421. r="|AM/REBASE"
  422. fi
  423. elif [ -f "$g/MERGE_HEAD" ]; then
  424. r="|MERGING"
  425. elif __git_sequencer_status; then
  426. :
  427. elif [ -f "$g/BISECT_LOG" ]; then
  428. r="|BISECTING"
  429. fi
  430. if [ -n "$b" ]; then
  431. :
  432. elif [ -h "$g/HEAD" ]; then
  433. # symlink symbolic ref
  434. b="$(git symbolic-ref HEAD 2>/dev/null)"
  435. else
  436. local head=""
  437. if ! __git_eread "$g/HEAD" head; then
  438. return $exit
  439. fi
  440. # is it a symbolic ref?
  441. b="${head#ref: }"
  442. if [ "$head" = "$b" ]; then
  443. detached=yes
  444. b="$(
  445. case "${GIT_PS1_DESCRIBE_STYLE-}" in
  446. (contains)
  447. git describe --contains HEAD ;;
  448. (branch)
  449. git describe --contains --all HEAD ;;
  450. (tag)
  451. git describe --tags HEAD ;;
  452. (describe)
  453. git describe HEAD ;;
  454. (* | default)
  455. git describe --tags --exact-match HEAD ;;
  456. esac 2>/dev/null)" ||
  457. b="$short_sha..."
  458. b="($b)"
  459. fi
  460. fi
  461. fi
  462. if [ -n "$step" ] && [ -n "$total" ]; then
  463. r="$r $step/$total"
  464. fi
  465. local w=""
  466. local i=""
  467. local s=""
  468. local u=""
  469. local c=""
  470. local p=""
  471. if [ "true" = "$inside_gitdir" ]; then
  472. if [ "true" = "$bare_repo" ]; then
  473. c="BARE:"
  474. else
  475. b="GIT_DIR!"
  476. fi
  477. elif [ "true" = "$inside_worktree" ]; then
  478. if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
  479. [ "$(git config --bool bash.showDirtyState)" != "false" ]
  480. then
  481. git diff --no-ext-diff --quiet || w="*"
  482. git diff --no-ext-diff --cached --quiet || i="+"
  483. if [ -z "$short_sha" ] && [ -z "$i" ]; then
  484. i="#"
  485. fi
  486. fi
  487. if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ] &&
  488. git rev-parse --verify --quiet refs/stash >/dev/null
  489. then
  490. s="$"
  491. fi
  492. if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
  493. [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
  494. git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*' >/dev/null 2>/dev/null
  495. then
  496. u="%${ZSH_VERSION+%}"
  497. fi
  498. if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
  499. __git_ps1_show_upstream
  500. fi
  501. fi
  502. local z="${GIT_PS1_STATESEPARATOR-" "}"
  503. # NO color option unless in PROMPT_COMMAND mode
  504. if [ $pcmode = yes ] && [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
  505. __git_ps1_colorize_gitstring
  506. fi
  507. b=${b##refs/heads/}
  508. if [ $pcmode = yes ] && [ $ps1_expanded = yes ]; then
  509. __git_ps1_branch_name=$b
  510. b="\${__git_ps1_branch_name}"
  511. fi
  512. local f="$w$i$s$u"
  513. local gitstring="$c$b${f:+$z$f}$r$p"
  514. if [ $pcmode = yes ]; then
  515. if [ "${__git_printf_supports_v-}" != yes ]; then
  516. gitstring=$(printf -- "$printf_format" "$gitstring")
  517. else
  518. printf -v gitstring -- "$printf_format" "$gitstring"
  519. fi
  520. PS1="$ps1pc_start$gitstring$ps1pc_end"
  521. else
  522. printf -- "$printf_format" "$gitstring"
  523. fi
  524. return $exit
  525. }