Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env bash
  2. # /usr/share/bash-completion/completions/git
  3. # https://github.com/junegunn/fzf/wiki/examples#git
  4. # declare BOLD=$(tput bold || tput md)
  5. declare c_reset="\e[0m"
  6. declare c_green=$(tput setaf 2 || tput AF 2)
  7. declare c_red=$(tput setaf 1 || tput AF 1)
  8. has() { # {{{
  9. command -v "$1" &> /dev/null
  10. }
  11. # }}}
  12. ask() { # {{{
  13. read -r -n1 -p "$* " ans
  14. echo
  15. [[ ${ans^} == Y* ]]
  16. }
  17. # }}}
  18. err() { # {{{
  19. printf "${c_red}%s${c_reset}" "$*" >&2
  20. }
  21. # }}}
  22. die() { # {{{
  23. [[ -n "$1" ]] && err "$1"
  24. exit 1
  25. }
  26. # }}}
  27. has fzf || die 'fzf not found'
  28. # [[ -d "$PWD/.git" ]] || die 'not a git repo'
  29. fzf() { # {{{
  30. local prompt
  31. if [[ $1 == --prompt=* ]]; then
  32. prompt="${1##*=}>"
  33. shift
  34. fi
  35. branch=$(git status 2> /dev/null | sed 's/On branch />/;q')
  36. $(which fzf) --inline-info --ansi --cycle --prompt="fzgit${branch}>${prompt} " "$@"
  37. }
  38. # }}}
  39. declare -A git_cmds_descriptions=( # {{{
  40. ['add']='Add file contents to the index'
  41. ['am']='Apply a series of patches from a mailbox'
  42. ['annotate']='Annotate file lines with commit information'
  43. ['apply']='Apply a patch to files and/or to the index'
  44. ['archive']='Create an archive of files from a named tree'
  45. ['bisect']='Find by binary search the change that introduced a bug'
  46. ['blame']='Show what revision and author last modified each line of a'
  47. ['branch']='List, create, or delete branches'
  48. ['bundle']='Move objects and refs by archive'
  49. ['cat-file']='Provide content or type and size information for'
  50. ['check-attr']='Display gitattributes information'
  51. ['check-ignore']='Debug gitignore / exclude files'
  52. ['check-mailmap']='Show canonical names and email addresses of'
  53. ['check-ref-format']='Ensures that a reference name is well formed'
  54. ['checkout']='Checkout a branch or paths to the working tree'
  55. ['checkout-index']='Copy files from the index to the working tree'
  56. ['cherry']='Find commits yet to be applied to upstream'
  57. ['cherry-pick']='Apply the changes introduced by some existing commits'
  58. ['citool']='Graphical alternative to git-commit'
  59. ['clean']='Remove untracked files from the working tree'
  60. ['clone']='Clone a repository into a new directory'
  61. ['column']='Display data in columns'
  62. ['commit']='Record changes to the repository'
  63. ['commit-tree']='Create a new commit object'
  64. ['config']='Get and set repository or global options'
  65. ['count-objects']='Count unpacked number of objects and their disk'
  66. ['credential']='Retrieve and store user credentials'
  67. ['daemon']='A really simple server for Git repositories'
  68. ['describe']='Show the most recent tag that is reachable from a commit'
  69. ['diff']='Show changes between commits, commit and working tree, etc'
  70. ['diff-files']='Compares files in the working tree and the index'
  71. ['diff-index']='Compare a tree to the working tree or index'
  72. ['diff-tree']='Compares the content and mode of blobs found via two'
  73. ['difftool']='Show changes using common diff tools'
  74. ['fast-export']='Git data exporter'
  75. ['fast-import']='Backend for fast Git data importers'
  76. ['fetch']='Download objects and refs from another repository'
  77. ['fetch-pack']='Receive missing objects from another repository'
  78. ['filter-branch']='Rewrite branches'
  79. ['fmt-merge-msg']='Produce a merge commit message'
  80. ['for-each-ref']='Output information on each ref'
  81. ['format-patch']='Prepare patches for e-mail submission'
  82. ['fsck']='Verifies the connectivity and validity of the objects in the'
  83. ['fsck-objects']='Verifies the connectivity and validity of the'
  84. ['gc']='Cleanup unnecessary files and optimize the local repository'
  85. ['get-tar-commit-id']='Extract commit ID from an archive created using'
  86. ['grep']='Print lines matching a pattern'
  87. ['gui']='A portable graphical interface to Git'
  88. ['hash-object']='Compute object ID and optionally creates a blob from'
  89. ['help']='Display help information about Git'
  90. ['http-backend']='Server side implementation of Git over HTTP'
  91. ['http-fetch']='Download from a remote Git repository via HTTP'
  92. ['http-push']='Push objects over HTTP/DAV to another repository'
  93. ['imap-send']='Send a collection of patches from stdin to an IMAP'
  94. ['index-pack']='Build pack index file for an existing packed archive'
  95. ['init']='Create an empty Git repository or reinitialize an existing'
  96. ['init-db']='Creates an empty Git repository'
  97. ['instaweb']='Instantly browse your working repository in gitweb'
  98. ['log']='Show commit logs'
  99. ['ls-files']='Show information about files in the index and the'
  100. ['ls-remote']='List references in a remote repository'
  101. ['ls-tree']='List the contents of a tree object'
  102. ['mailinfo']='Extracts patch and authorship from a single e-mail'
  103. ['mailsplit']='Simple UNIX mbox splitter program'
  104. ['merge']='Join two or more development histories together'
  105. ['merge-base']='Find as good common ancestors as possible for a merge'
  106. ['merge-file']='Run a three-way file merge'
  107. ['merge-index']='Run a merge for files needing merging'
  108. ['merge-one-file']='The standard helper program to use with'
  109. ['merge-tree']='Show three-way merge without touching index'
  110. ['mergetool']='Run merge conflict resolution tools to resolve merge'
  111. ['mktag']='Creates a tag object'
  112. ['mktree']='Build a tree-object from ls-tree formatted text'
  113. ['mv']='Move or rename a file, a directory, or a symlink'
  114. ['notes']='Add or inspect object notes'
  115. ['pack-objects']='Create a packed archive of objects'
  116. ['pack-redundant']='Find redundant pack files'
  117. ['pack-refs']='Pack heads and tags for efficient repository access'
  118. ['patch-id']='Compute unique ID for a patch'
  119. ['prune']='Prune all unreachable objects from the object database'
  120. ['prune-packed']='Remove extra objects that are already in pack files'
  121. ['pull']='Fetch from and integrate with another repository or a local'
  122. ['push']='Update remote refs along with associated objects'
  123. ['quiltimport']='Applies a quilt patchset onto the current branch'
  124. ['read-tree']='Reads tree information into the index'
  125. ['rebase']='Forward-port local commits to the updated upstream head'
  126. ['receive-pack']='Receive what is pushed into the repository'
  127. ['reflog']='Manage reflog information'
  128. ['relink']='Hardlink common objects in local repositories'
  129. ['remote']='Manage set of tracked repositories'
  130. ['remote-ext']='Bridge smart transport to external command.'
  131. ['remote-fd']='Reflect smart transport stream back to caller'
  132. ['repack']='Pack unpacked objects in a repository'
  133. ['replace']='Create, list, delete refs to replace objects'
  134. ['request-pull']='Generates a summary of pending changes'
  135. ['rerere']='Reuse recorded resolution of conflicted merges'
  136. ['reset']='Reset current HEAD to the specified state'
  137. ['rev-list']='Lists commit objects in reverse chronological order'
  138. ['rev-parse']='Pick out and massage parameters'
  139. ['revert']='Revert some existing commits'
  140. ['rm']='Remove files from the working tree and from the index'
  141. ['send-pack']='Push objects over Git protocol to another repository'
  142. ['sh-i18n--envsubst']="Git's own envsubst(1) for i18n fallbacks"
  143. ['shell']='Restricted login shell for Git-only SSH access'
  144. ['shortlog']="Summarize 'git log' output"
  145. ['show']='Show various types of objects'
  146. ['show-branch']='Show branches and their commits'
  147. ['show-index']='Show packed archive index'
  148. ['show-ref']='List references in a local repository'
  149. ['stage']='Add file contents to the staging area'
  150. ['stash']='Stash the changes in a dirty working directory away'
  151. ['status']='Show the working tree status'
  152. ['stripspace']='Remove unnecessary whitespace'
  153. ['submodule']='Initialize, update or inspect submodules'
  154. ['subtree']='Merge subtrees together and split repository into'
  155. ['symbolic-ref']='Read, modify and delete symbolic refs'
  156. ['tag']='Create, list, delete or verify a tag object signed with GPG'
  157. ['unpack-file']="Creates a temporary file with a blob's contents"
  158. ['unpack-objects']='Unpack objects from a packed archive'
  159. ['update-index']='Register file contents in the working tree to the'
  160. ['update-ref']='Update the object name stored in a ref safely'
  161. ['update-server-info']='Update auxiliary info file to help dumb'
  162. ['upload-archive']='Send archive back to git-archive'
  163. ['upload-pack']='Send objects packed back to git-fetch-pack'
  164. ['var']='Show a Git logical variable'
  165. ['verify-commit']='Check the GPG signature of commits'
  166. ['verify-pack']='Validate packed Git archive files'
  167. ['verify-tag']='Check the GPG signature of tags'
  168. ['web--browse']='Git helper script to launch a web browser'
  169. ['whatchanged']='Show logs with difference each commit introduces'
  170. ['write-tree']='Create a tree object from the current index'
  171. )
  172. # }}}
  173. declare -A implemented_git_cmds=(
  174. ['stash']='git_stash'
  175. ['add']='git_add'
  176. ['checkout']='git_checkout'
  177. ['commit']='git commit -v'
  178. ['push']='git push'
  179. ['log']='git_log'
  180. )
  181. git_log() { # {{{
  182. local show="git show --color=always \"\$(grep -m1 -o \"[a-f0-9]\{7\}\" <<< {})\""
  183. fzf --prompt='log' -e --no-sort --tiebreak=index \
  184. --preview-window=up \
  185. --bind="enter:execute:$show | less -R" \
  186. --preview="$show" \
  187. < <(git log --graph --color=always \
  188. --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@")
  189. }
  190. # }}}
  191. git_checkout() { # {{{
  192. local list response key branch header
  193. list=$(git branch --all --color -vv; git tag) || return 1
  194. mapfile -t response < <(fzf --prompt='checkout' \
  195. --header="$header" --expect=ctrl-x <<< "$list")
  196. key="${response[0]}"
  197. branch=$(perl -pe 's/^\*?\s*(remotes\/[^\/]*\/)?([^ ]+).*/\2/' <<< "${response[1]}")
  198. git checkout "$branch" || return 1
  199. }
  200. # }}}
  201. git_add() { # {{{
  202. local out response query key header
  203. header='use ctrl-p to add in patch mode'
  204. while out=$(git ls-files -mo --exclude-standard |
  205. fzf --prompt='add' --tac --multi \
  206. --header="$header" --query="$query" --print-query \
  207. --preview='git diff --color=always {} 2>&1' \
  208. --preview-window=up \
  209. --bind=ctrl-p:accept --expect=ctrl-p)
  210. do
  211. mapfile -t response <<< "$out"
  212. query="${response[0]}" && unset response[0]
  213. key="${response[1]}" && unset response[1]
  214. [[ "${#response[@]}" == 0 ]] && continue
  215. if [[ "$key" == 'ctrl-p' ]]; then
  216. git add -p "${response[@]}" < /dev/tty
  217. else
  218. git add "${response[@]}"
  219. fi
  220. done
  221. }
  222. # }}}
  223. git_stash() { # {{{
  224. local out response query key sha header
  225. header='use ctrl-d to show a diff or ctrl-b to create a new branch'
  226. while out=$(git stash list \
  227. --pretty="%C(yellow)%h %>(14)%Cgreen%cr %C(blue)%gs" |
  228. fzf --prompt='stash' --no-sort --header="$header" \
  229. --query="$query" --print-query \
  230. --preview='git diff --color {1}' \
  231. --expect=ctrl-d,ctrl-b)
  232. do
  233. mapfile -t response <<< "$out"
  234. query="${response[0]}" && unset response[0]
  235. key="${response[1]}" && unset response[1]
  236. sha="${response[-1]}"
  237. sha="${sha%% *}"
  238. [[ -z "$sha" ]] && continue
  239. case "$key" in
  240. 'ctrl-d') git diff "$sha" --color=always | less -R ;;
  241. 'ctrl-b') git stash branch "stash-$sha" "$sha" ;;
  242. *) git stash show -p "$sha" --color=always | less -R ;;
  243. esac
  244. done
  245. }
  246. # }}}
  247. pick_cmd() {
  248. for c in "${!implemented_git_cmds[@]}"; do
  249. printf "${c_green}%s${c_reset}| -- %s\n" "$c" "${git_cmds_descriptions[$c]}"
  250. done | column -s'|' -t | fzf | awk '{print $1}'
  251. }
  252. main() {
  253. local pick
  254. while pick=$(pick_cmd); do
  255. if [[ -n $pick ]] && has "${implemented_git_cmds[${pick%% *}]}"; then
  256. ${implemented_git_cmds[$pick]}
  257. else
  258. break
  259. fi
  260. done
  261. }
  262. main