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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. # By default, __git_ps1 will compare HEAD to your SVN upstream if it can
  70. # find one, or @{upstream} otherwise. Once you have set
  71. # GIT_PS1_SHOWUPSTREAM, you can override it on a per-repository basis by
  72. # setting the bash.showUpstream config variable.
  73. #
  74. # If you would like to see more information about the identity of
  75. # commits checked out as a detached HEAD, set GIT_PS1_DESCRIBE_STYLE
  76. # to one of these values:
  77. #
  78. # contains relative to newer annotated tag (v1.6.3.2~35)
  79. # branch relative to newer tag or branch (master~4)
  80. # describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
  81. # default exactly matching tag
  82. #
  83. # If you would like a colored hint about the current dirty state, set
  84. # GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
  85. # the colored output of "git status -sb" and are available only when
  86. # using __git_ps1 for PROMPT_COMMAND or precmd.
  87. # check whether printf supports -v
  88. __git_printf_supports_v=
  89. printf -v __git_printf_supports_v -- '%s' yes >/dev/null 2>&1
  90. # stores the divergence from upstream in $p
  91. # used by GIT_PS1_SHOWUPSTREAM
  92. __git_ps1_show_upstream ()
  93. {
  94. local key value
  95. local svn_remote svn_url_pattern count n
  96. local upstream=git legacy="" verbose="" name=""
  97. svn_remote=()
  98. # get some config options from git-config
  99. local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
  100. while read -r key value; do
  101. case "$key" in
  102. bash.showupstream)
  103. GIT_PS1_SHOWUPSTREAM="$value"
  104. if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
  105. p=""
  106. return
  107. fi
  108. ;;
  109. svn-remote.*.url)
  110. svn_remote[$((${#svn_remote[@]} + 1))]="$value"
  111. svn_url_pattern="$svn_url_pattern\\|$value"
  112. upstream=svn+git # default upstream is SVN if available, else git
  113. ;;
  114. esac
  115. done <<< "$output"
  116. # parse configuration values
  117. for option in ${GIT_PS1_SHOWUPSTREAM}; do
  118. case "$option" in
  119. git|svn) upstream="$option" ;;
  120. verbose) verbose=1 ;;
  121. legacy) legacy=1 ;;
  122. name) name=1 ;;
  123. esac
  124. done
  125. # Find our upstream
  126. case "$upstream" in
  127. git) upstream="@{upstream}" ;;
  128. svn*)
  129. # get the upstream from the "git-svn-id: ..." in a commit message
  130. # (git-svn uses essentially the same procedure internally)
  131. local -a svn_upstream
  132. svn_upstream=($(git log --first-parent -1 \
  133. --grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
  134. if [[ 0 -ne ${#svn_upstream[@]} ]]; then
  135. svn_upstream=${svn_upstream[${#svn_upstream[@]} - 2]}
  136. svn_upstream=${svn_upstream%@*}
  137. local n_stop="${#svn_remote[@]}"
  138. for ((n=1; n <= n_stop; n++)); do
  139. svn_upstream=${svn_upstream#${svn_remote[$n]}}
  140. done
  141. if [[ -z "$svn_upstream" ]]; then
  142. # default branch name for checkouts with no layout:
  143. upstream=${GIT_SVN_ID:-git-svn}
  144. else
  145. upstream=${svn_upstream#/}
  146. fi
  147. elif [[ "svn+git" = "$upstream" ]]; then
  148. upstream="@{upstream}"
  149. fi
  150. ;;
  151. esac
  152. # Find how many commits we are ahead/behind our upstream
  153. if [[ -z "$legacy" ]]; then
  154. count="$(git rev-list --count --left-right \
  155. "$upstream"...HEAD 2>/dev/null)"
  156. else
  157. # produce equivalent output to --count for older versions of git
  158. local commits
  159. if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
  160. then
  161. local commit behind=0 ahead=0
  162. for commit in $commits
  163. do
  164. case "$commit" in
  165. "<"*) ((behind++)) ;;
  166. *) ((ahead++)) ;;
  167. esac
  168. done
  169. count="$behind $ahead"
  170. else
  171. count=""
  172. fi
  173. fi
  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. if [[ -n "$count" && -n "$name" ]]; then
  202. __git_ps1_upstream_name=$(git rev-parse \
  203. --abbrev-ref "$upstream" 2>/dev/null)
  204. if [ $pcmode = yes ]; then
  205. # see the comments around the
  206. # __git_ps1_branch_name variable below
  207. p="$p \${__git_ps1_upstream_name}"
  208. else
  209. p="$p ${__git_ps1_upstream_name}"
  210. # not needed anymore; keep user's
  211. # environment clean
  212. unset __git_ps1_upstream_name
  213. fi
  214. fi
  215. fi
  216. }
  217. # Helper function that is meant to be called from __git_ps1. It
  218. # injects color codes into the appropriate gitstring variables used
  219. # to build a gitstring.
  220. __git_ps1_colorize_gitstring ()
  221. {
  222. if [[ -n ${ZSH_VERSION-} ]]; then
  223. local c_red='%F{red}'
  224. local c_green='%F{green}'
  225. local c_lblue='%F{blue}'
  226. local c_clear='%f'
  227. else
  228. # Using \[ and \] around colors is necessary to prevent
  229. # issues with command line editing/browsing/completion!
  230. local c_red='\[\e[31m\]'
  231. local c_green='\[\e[32m\]'
  232. local c_lblue='\[\e[1;34m\]'
  233. local c_clear='\[\e[0m\]'
  234. fi
  235. local bad_color=$c_red
  236. local ok_color=$c_green
  237. local flags_color="$c_lblue"
  238. local branch_color=""
  239. if [ $detached = no ]; then
  240. branch_color="$ok_color"
  241. else
  242. branch_color="$bad_color"
  243. fi
  244. c="$branch_color$c"
  245. z="$c_clear$z"
  246. if [ "$w" = "*" ]; then
  247. w="$bad_color$w"
  248. fi
  249. if [ -n "$i" ]; then
  250. i="$ok_color$i"
  251. fi
  252. if [ -n "$s" ]; then
  253. s="$flags_color$s"
  254. fi
  255. if [ -n "$u" ]; then
  256. u="$bad_color$u"
  257. fi
  258. r="$c_clear$r"
  259. }
  260. # __git_ps1 accepts 0 or 1 arguments (i.e., format string)
  261. # when called from PS1 using command substitution
  262. # in this mode it prints text to add to bash PS1 prompt (includes branch name)
  263. #
  264. # __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
  265. # in that case it _sets_ PS1. The arguments are parts of a PS1 string.
  266. # when two arguments are given, the first is prepended and the second appended
  267. # to the state string when assigned to PS1.
  268. # The optional third parameter will be used as printf format string to further
  269. # customize the output of the git-status string.
  270. # In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
  271. __git_ps1 ()
  272. {
  273. local pcmode=no
  274. local detached=no
  275. local ps1pc_start='\u@\h:\w '
  276. local ps1pc_end='\$ '
  277. local printf_format=' (%s)'
  278. case "$#" in
  279. 2|3) pcmode=yes
  280. ps1pc_start="$1"
  281. ps1pc_end="$2"
  282. printf_format="${3:-$printf_format}"
  283. ;;
  284. 0|1) printf_format="${1:-$printf_format}"
  285. ;;
  286. *) return
  287. ;;
  288. esac
  289. local repo_info rev_parse_exit_code
  290. repo_info="$(git rev-parse --git-dir --is-inside-git-dir \
  291. --is-bare-repository --is-inside-work-tree \
  292. --short HEAD 2>/dev/null)"
  293. rev_parse_exit_code="$?"
  294. if [ -z "$repo_info" ]; then
  295. if [ $pcmode = yes ]; then
  296. #In PC mode PS1 always needs to be set
  297. PS1="$ps1pc_start$ps1pc_end"
  298. fi
  299. return
  300. fi
  301. local short_sha
  302. if [ "$rev_parse_exit_code" = "0" ]; then
  303. short_sha="${repo_info##*$'\n'}"
  304. repo_info="${repo_info%$'\n'*}"
  305. fi
  306. local inside_worktree="${repo_info##*$'\n'}"
  307. repo_info="${repo_info%$'\n'*}"
  308. local bare_repo="${repo_info##*$'\n'}"
  309. repo_info="${repo_info%$'\n'*}"
  310. local inside_gitdir="${repo_info##*$'\n'}"
  311. local g="${repo_info%$'\n'*}"
  312. local r=""
  313. local b=""
  314. local step=""
  315. local total=""
  316. if [ -d "$g/rebase-merge" ]; then
  317. read b 2>/dev/null <"$g/rebase-merge/head-name"
  318. read step 2>/dev/null <"$g/rebase-merge/msgnum"
  319. read total 2>/dev/null <"$g/rebase-merge/end"
  320. if [ -f "$g/rebase-merge/interactive" ]; then
  321. r="|REBASE-i"
  322. else
  323. r="|REBASE-m"
  324. fi
  325. else
  326. if [ -d "$g/rebase-apply" ]; then
  327. read step 2>/dev/null <"$g/rebase-apply/next"
  328. read total 2>/dev/null <"$g/rebase-apply/last"
  329. if [ -f "$g/rebase-apply/rebasing" ]; then
  330. read b 2>/dev/null <"$g/rebase-apply/head-name"
  331. r="|REBASE"
  332. elif [ -f "$g/rebase-apply/applying" ]; then
  333. r="|AM"
  334. else
  335. r="|AM/REBASE"
  336. fi
  337. elif [ -f "$g/MERGE_HEAD" ]; then
  338. r="|MERGING"
  339. elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
  340. r="|CHERRY-PICKING"
  341. elif [ -f "$g/REVERT_HEAD" ]; then
  342. r="|REVERTING"
  343. elif [ -f "$g/BISECT_LOG" ]; then
  344. r="|BISECTING"
  345. fi
  346. if [ -n "$b" ]; then
  347. :
  348. elif [ -h "$g/HEAD" ]; then
  349. # symlink symbolic ref
  350. b="$(git symbolic-ref HEAD 2>/dev/null)"
  351. else
  352. local head=""
  353. if ! read head 2>/dev/null <"$g/HEAD"; then
  354. if [ $pcmode = yes ]; then
  355. PS1="$ps1pc_start$ps1pc_end"
  356. fi
  357. return
  358. fi
  359. # is it a symbolic ref?
  360. b="${head#ref: }"
  361. if [ "$head" = "$b" ]; then
  362. detached=yes
  363. b="$(
  364. case "${GIT_PS1_DESCRIBE_STYLE-}" in
  365. (contains)
  366. git describe --contains HEAD ;;
  367. (branch)
  368. git describe --contains --all HEAD ;;
  369. (describe)
  370. git describe HEAD ;;
  371. (* | default)
  372. git describe --tags --exact-match HEAD ;;
  373. esac 2>/dev/null)" ||
  374. b="$short_sha..."
  375. b="($b)"
  376. fi
  377. fi
  378. fi
  379. if [ -n "$step" ] && [ -n "$total" ]; then
  380. r="$r $step/$total"
  381. fi
  382. local w=""
  383. local i=""
  384. local s=""
  385. local u=""
  386. local c=""
  387. local p=""
  388. if [ "true" = "$inside_gitdir" ]; then
  389. if [ "true" = "$bare_repo" ]; then
  390. c="BARE:"
  391. else
  392. b="GIT_DIR!"
  393. fi
  394. elif [ "true" = "$inside_worktree" ]; then
  395. if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
  396. [ "$(git config --bool bash.showDirtyState)" != "false" ]
  397. then
  398. git diff --no-ext-diff --quiet --exit-code || w="*"
  399. if [ -n "$short_sha" ]; then
  400. git diff-index --cached --quiet HEAD -- || i="+"
  401. else
  402. i="#"
  403. fi
  404. fi
  405. if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ] &&
  406. [ -r "$g/refs/stash" ]; then
  407. s="$"
  408. fi
  409. if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
  410. [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
  411. git ls-files --others --exclude-standard --error-unmatch -- '*' >/dev/null 2>/dev/null
  412. then
  413. u="%${ZSH_VERSION+%}"
  414. fi
  415. if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
  416. __git_ps1_show_upstream
  417. fi
  418. fi
  419. local z="${GIT_PS1_STATESEPARATOR-" "}"
  420. # NO color option unless in PROMPT_COMMAND mode
  421. if [ $pcmode = yes ] && [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
  422. __git_ps1_colorize_gitstring
  423. fi
  424. b=${b##refs/heads/}
  425. if [ $pcmode = yes ]; then
  426. # In pcmode (and only pcmode) the contents of
  427. # $gitstring are subject to expansion by the shell.
  428. # Avoid putting the raw ref name in the prompt to
  429. # protect the user from arbitrary code execution via
  430. # specially crafted ref names (e.g., a ref named
  431. # '$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)' would execute
  432. # 'sudo rm -rf /' when the prompt is drawn). Instead,
  433. # put the ref name in a new global variable (in the
  434. # __git_ps1_* namespace to avoid colliding with the
  435. # user's environment) and reference that variable from
  436. # PS1.
  437. __git_ps1_branch_name=$b
  438. # note that the $ is escaped -- the variable will be
  439. # expanded later (when it's time to draw the prompt)
  440. b="\${__git_ps1_branch_name}"
  441. fi
  442. local f="$w$i$s$u"
  443. local gitstring="$c$b${f:+$z$f}$r$p"
  444. if [ $pcmode = yes ]; then
  445. if [ "${__git_printf_supports_v-}" != yes ]; then
  446. gitstring=$(printf -- "$printf_format" "$gitstring")
  447. else
  448. printf -v gitstring -- "$printf_format" "$gitstring"
  449. fi
  450. PS1="$ps1pc_start$gitstring$ps1pc_end"
  451. else
  452. printf -- "$printf_format" "$gitstring"
  453. fi
  454. }