The aptly named.
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.

515 lines
17 KiB

  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 ] && [ $ps1_expanded = yes ]; then
  205. p="$p \${__git_ps1_upstream_name}"
  206. else
  207. p="$p ${__git_ps1_upstream_name}"
  208. # not needed anymore; keep user's
  209. # environment clean
  210. unset __git_ps1_upstream_name
  211. fi
  212. fi
  213. fi
  214. }
  215. # Helper function that is meant to be called from __git_ps1. It
  216. # injects color codes into the appropriate gitstring variables used
  217. # to build a gitstring.
  218. __git_ps1_colorize_gitstring ()
  219. {
  220. if [[ -n ${ZSH_VERSION-} ]]; then
  221. local c_red='%F{red}'
  222. local c_green='%F{green}'
  223. local c_lblue='%F{blue}'
  224. local c_clear='%f'
  225. else
  226. # Using \[ and \] around colors is necessary to prevent
  227. # issues with command line editing/browsing/completion!
  228. local c_red='\[\e[31m\]'
  229. local c_green='\[\e[32m\]'
  230. local c_lblue='\[\e[1;34m\]'
  231. local c_clear='\[\e[0m\]'
  232. fi
  233. local bad_color=$c_red
  234. local ok_color=$c_green
  235. local flags_color="$c_lblue"
  236. local branch_color=""
  237. if [ $detached = no ]; then
  238. branch_color="$ok_color"
  239. else
  240. branch_color="$bad_color"
  241. fi
  242. c="$branch_color$c"
  243. z="$c_clear$z"
  244. if [ "$w" = "*" ]; then
  245. w="$bad_color$w"
  246. fi
  247. if [ -n "$i" ]; then
  248. i="$ok_color$i"
  249. fi
  250. if [ -n "$s" ]; then
  251. s="$flags_color$s"
  252. fi
  253. if [ -n "$u" ]; then
  254. u="$bad_color$u"
  255. fi
  256. r="$c_clear$r"
  257. }
  258. __git_eread ()
  259. {
  260. f="$1"
  261. shift
  262. test -r "$f" && read "$@" <"$f"
  263. }
  264. # __git_ps1 accepts 0 or 1 arguments (i.e., format string)
  265. # when called from PS1 using command substitution
  266. # in this mode it prints text to add to bash PS1 prompt (includes branch name)
  267. #
  268. # __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
  269. # in that case it _sets_ PS1. The arguments are parts of a PS1 string.
  270. # when two arguments are given, the first is prepended and the second appended
  271. # to the state string when assigned to PS1.
  272. # The optional third parameter will be used as printf format string to further
  273. # customize the output of the git-status string.
  274. # In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
  275. __git_ps1 ()
  276. {
  277. local pcmode=no
  278. local detached=no
  279. local ps1pc_start='\u@\h:\w '
  280. local ps1pc_end='\$ '
  281. local printf_format=' (%s)'
  282. case "$#" in
  283. 2|3) pcmode=yes
  284. ps1pc_start="$1"
  285. ps1pc_end="$2"
  286. printf_format="${3:-$printf_format}"
  287. ;;
  288. 0|1) printf_format="${1:-$printf_format}"
  289. ;;
  290. *) return
  291. ;;
  292. esac
  293. # ps1_expanded: This variable is set to 'yes' if the shell
  294. # subjects the value of PS1 to parameter expansion:
  295. #
  296. # * bash does unless the promptvars option is disabled
  297. # * zsh does not unless the PROMPT_SUBST option is set
  298. # * POSIX shells always do
  299. #
  300. # If the shell would expand the contents of PS1 when drawing
  301. # the prompt, a raw ref name must not be included in PS1.
  302. # This protects the user from arbitrary code execution via
  303. # specially crafted ref names. For example, a ref named
  304. # 'refs/heads/$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)' might cause the
  305. # shell to execute 'sudo rm -rf /' when the prompt is drawn.
  306. #
  307. # Instead, the ref name should be placed in a separate global
  308. # variable (in the __git_ps1_* namespace to avoid colliding
  309. # with the user's environment) and that variable should be
  310. # referenced from PS1. For example:
  311. #
  312. # __git_ps1_foo=$(do_something_to_get_ref_name)
  313. # PS1="...stuff...\${__git_ps1_foo}...stuff..."
  314. #
  315. # If the shell does not expand the contents of PS1, the raw
  316. # ref name must be included in PS1.
  317. #
  318. # The value of this variable is only relevant when in pcmode.
  319. #
  320. # Assume that the shell follows the POSIX specification and
  321. # expands PS1 unless determined otherwise. (This is more
  322. # likely to be correct if the user has a non-bash, non-zsh
  323. # shell and safer than the alternative if the assumption is
  324. # incorrect.)
  325. #
  326. local ps1_expanded=yes
  327. [ -z "$ZSH_VERSION" ] || [[ -o PROMPT_SUBST ]] || ps1_expanded=no
  328. [ -z "$BASH_VERSION" ] || shopt -q promptvars || ps1_expanded=no
  329. local repo_info rev_parse_exit_code
  330. repo_info="$(git rev-parse --git-dir --is-inside-git-dir \
  331. --is-bare-repository --is-inside-work-tree \
  332. --short HEAD 2>/dev/null)"
  333. rev_parse_exit_code="$?"
  334. if [ -z "$repo_info" ]; then
  335. if [ $pcmode = yes ]; then
  336. #In PC mode PS1 always needs to be set
  337. PS1="$ps1pc_start$ps1pc_end"
  338. fi
  339. return
  340. fi
  341. local short_sha
  342. if [ "$rev_parse_exit_code" = "0" ]; then
  343. short_sha="${repo_info##*$'\n'}"
  344. repo_info="${repo_info%$'\n'*}"
  345. fi
  346. local inside_worktree="${repo_info##*$'\n'}"
  347. repo_info="${repo_info%$'\n'*}"
  348. local bare_repo="${repo_info##*$'\n'}"
  349. repo_info="${repo_info%$'\n'*}"
  350. local inside_gitdir="${repo_info##*$'\n'}"
  351. local g="${repo_info%$'\n'*}"
  352. local r=""
  353. local b=""
  354. local step=""
  355. local total=""
  356. if [ -d "$g/rebase-merge" ]; then
  357. __git_eread "$g/rebase-merge/head-name" b
  358. __git_eread "$g/rebase-merge/msgnum" step
  359. __git_eread "$g/rebase-merge/end" total
  360. if [ -f "$g/rebase-merge/interactive" ]; then
  361. r="|REBASE-i"
  362. else
  363. r="|REBASE-m"
  364. fi
  365. else
  366. if [ -d "$g/rebase-apply" ]; then
  367. __git_eread "$g/rebase-apply/next" step
  368. __git_eread "$g/rebase-apply/last" total
  369. if [ -f "$g/rebase-apply/rebasing" ]; then
  370. __git_eread "$g/rebase-apply/head-name" b
  371. r="|REBASE"
  372. elif [ -f "$g/rebase-apply/applying" ]; then
  373. r="|AM"
  374. else
  375. r="|AM/REBASE"
  376. fi
  377. elif [ -f "$g/MERGE_HEAD" ]; then
  378. r="|MERGING"
  379. elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
  380. r="|CHERRY-PICKING"
  381. elif [ -f "$g/REVERT_HEAD" ]; then
  382. r="|REVERTING"
  383. elif [ -f "$g/BISECT_LOG" ]; then
  384. r="|BISECTING"
  385. fi
  386. if [ -n "$b" ]; then
  387. :
  388. elif [ -h "$g/HEAD" ]; then
  389. # symlink symbolic ref
  390. b="$(git symbolic-ref HEAD 2>/dev/null)"
  391. else
  392. local head=""
  393. if ! __git_eread "$g/HEAD" head; then
  394. if [ $pcmode = yes ]; then
  395. PS1="$ps1pc_start$ps1pc_end"
  396. fi
  397. return
  398. fi
  399. # is it a symbolic ref?
  400. b="${head#ref: }"
  401. if [ "$head" = "$b" ]; then
  402. detached=yes
  403. b="$(
  404. case "${GIT_PS1_DESCRIBE_STYLE-}" in
  405. (contains)
  406. git describe --contains HEAD ;;
  407. (branch)
  408. git describe --contains --all HEAD ;;
  409. (describe)
  410. git describe HEAD ;;
  411. (* | default)
  412. git describe --tags --exact-match HEAD ;;
  413. esac 2>/dev/null)" ||
  414. b="$short_sha..."
  415. b="($b)"
  416. fi
  417. fi
  418. fi
  419. if [ -n "$step" ] && [ -n "$total" ]; then
  420. r="$r $step/$total"
  421. fi
  422. local w=""
  423. local i=""
  424. local s=""
  425. local u=""
  426. local c=""
  427. local p=""
  428. if [ "true" = "$inside_gitdir" ]; then
  429. if [ "true" = "$bare_repo" ]; then
  430. c="BARE:"
  431. else
  432. b="GIT_DIR!"
  433. fi
  434. elif [ "true" = "$inside_worktree" ]; then
  435. if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
  436. [ "$(git config --bool bash.showDirtyState)" != "false" ]
  437. then
  438. git diff --no-ext-diff --quiet --exit-code || w="*"
  439. if [ -n "$short_sha" ]; then
  440. git diff-index --cached --quiet HEAD -- || i="+"
  441. else
  442. i="#"
  443. fi
  444. fi
  445. if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ] &&
  446. git rev-parse --verify --quiet refs/stash >/dev/null
  447. then
  448. s="$"
  449. fi
  450. if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
  451. [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
  452. git ls-files --others --exclude-standard --error-unmatch -- '*' >/dev/null 2>/dev/null
  453. then
  454. u="%${ZSH_VERSION+%}"
  455. fi
  456. if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
  457. __git_ps1_show_upstream
  458. fi
  459. fi
  460. local z="${GIT_PS1_STATESEPARATOR-" "}"
  461. # NO color option unless in PROMPT_COMMAND mode
  462. if [ $pcmode = yes ] && [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
  463. __git_ps1_colorize_gitstring
  464. fi
  465. b=${b##refs/heads/}
  466. if [ $pcmode = yes ] && [ $ps1_expanded = yes ]; then
  467. __git_ps1_branch_name=$b
  468. b="\${__git_ps1_branch_name}"
  469. fi
  470. local f="$w$i$s$u"
  471. local gitstring="$c$b${f:+$z$f}$r$p"
  472. if [ $pcmode = yes ]; then
  473. if [ "${__git_printf_supports_v-}" != yes ]; then
  474. gitstring=$(printf -- "$printf_format" "$gitstring")
  475. else
  476. printf -v gitstring -- "$printf_format" "$gitstring"
  477. fi
  478. PS1="$ps1pc_start$gitstring$ps1pc_end"
  479. else
  480. printf -- "$printf_format" "$gitstring"
  481. fi
  482. }