Har*_* Mc 11 git bash bash-completion git-alias
我已经成功地为各种 Git 别名配置了 Bash 完成。例如:
$ git config alias.subject
!git --no-pager show --quiet --pretty='%s'
$ function _git_subject() { _git_show; }
$ git subject my<TAB>
$ git subject my-branch
Run Code Online (Sandbox Code Playgroud)
但是,我有一个 Git 别名,我不知道如何为其设置 Bash 完成。问题是我希望别名能够像顶级 Git 命令本身一样完成。别名是这样的:
$ git config alias.alias
alias = !"f() { if [[ \"$#\" != 1 ]]; then >&2 echo \"Usage: git alias COMMAND\"; return 1; fi; git config alias.\"$1\"; }; f"
# Example
$ git alias s
status
Run Code Online (Sandbox Code Playgroud)
我试过使用_git
, __git_main
, 和__git_wrap__git_main
,但它们都不起作用(我认为这会导致无限循环,因为它在我按下 Tab 后永远不会返回)。
有没有办法为 Git 别名添加完成,就像它是顶级 Git 命令一样?或者具体如何完成这个别名?
function _git_alias() { _git; }
function _git_alias() { __git_main; }
function _git_alias() { __git_wrap__git_main; }
Run Code Online (Sandbox Code Playgroud)
$ git alias su<TAB>
subject submodule
$ git alias sub
Run Code Online (Sandbox Code Playgroud)
或者,如果有一种简单的方法来完成别名也很酷。不过,我也想知道如何完成就好像顶级 Git 命令一样,只是出于好奇。
我终于能够通过围绕“神奇”Bash 完成变量的一些技巧来创建一个可行的解决方案。我更改了这些变量以“假装”我们正在完成给定的命令git
本身。
如果有人有任何简化此操作的建议,我完全愿意接受建议。
# This is complex because we want to delegate to the completion for Git
# itself without ending up with an infinite loop (which happens if you try
# to just delegate to _git).
_git_alias() {
if [[ "$COMP_CWORD" -lt 2 ]]; then
return
fi
local old_comp_line_length new_comp_line_length
COMP_WORDS=(git "${COMP_WORDS[@]:2}")
((COMP_CWORD -= 1))
old_comp_line_length=${#COMP_LINE}
if [[ "$COMP_LINE" =~ ^[^[:blank:]]+[[:blank:]]+[^[:blank:]]+[[:blank:]]+(.*)$ ]]; then
COMP_LINE="git ${BASH_REMATCH[1]}"
fi
new_comp_line_length=${#COMP_LINE}
(( COMP_POINT += new_comp_line_length - old_comp_line_length ))
_git "$@"
# git alias blah
# ^
# 01234567890123
# 0 1
# point: 11
# length: 13
#
# git blah
# ^
# 01234567
# point: 5
# length: 7
#
# point = point - (old length) + (new length)
# point = 11 - 13 + 7
# point = -2 + 7
# point = 5
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
108 次 |
最近记录: |