You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

git-prompt.sh 16KB

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