[英]Git autocomplete for custom bash functions
在我的.bash_profile
,我有很多 git 的功能快捷方式。 例如:
function gitpull() {
branch="$1"
if [[ -z $branch ]]; then
current_branch=`git symbolic-ref -q --short HEAD`
git pull origin $current_branch;
elif [[ -n $branch && $branch == "m" ]]; then
git pull origin master;
else
git pull origin $branch;
fi;
}
但是,当我在终端中输入此内容时,我希望它自动完成 git 分支。 我该怎么做? (我已经在使用.git-completion.bash
)
手工制作的 bash 完成就像这样简单:
# our handler that returns choices by populating Bash array COMPREPLY
# (filtered by the currently entered word ($2) via compgen builtin)
_gitpull_complete() {
branches=$(git branch -l | cut -c3-)
COMPREPLY=($(compgen -W "$branches" -- "$2"))
}
# we now register our handler to provide completion hints for the "gitpull" command
complete -F _gitpull_complete gitpull
获取上述命令后:
$ gitpull <TAB>
asd master qwe zxc
$ gitpull m<TAB>
$ gitpull master
关于 bash 完成的最终参考(当然)是 bash 手册中关于可编程完成的部分,但在“Debian 管理”页面( 第 1 部分和更重要的第 2 部分)上给出了一个很好的介绍。
推荐的方法是使用__git_complete()
:
__git_complete gitpull _git_pull
Git 2.31(2021 年第一季度)更新了 bash 补全(在contrib/
),使最终用户可以更轻松地为其自定义“ git
”子命令添加补全。
请参阅Felipe Contreras ( felipec
) 的commit 5a067ba 、 commit 0e02bdc 、 commit 810df0e 、 commit 7f94b78 (2020 年 12 月 30 日) 。
(由Junio C gitster
-- gitster
--在提交 f9fb906 中合并,2021 年 1 月 15 日)
completion
:添加适当的公共 __git_complete签字人: Felipe Contreras
当
__git_complete
被引入时,它是暂时的,同时为公共 shell 函数建立了一个适当的指南(暂定_GIT_complete
),但由于这从未发生过,人们开始使用__git_complete
,即使它被标记为非公开.等待八年绰绰有余,让我们将此功能标记为公开,并使其更加用户友好。
所以,而不是这样做:
__git_complete gk __gitk_main
用户可以:
__git_complete gk gitk
而不是:
__git_complete gf _git_fetch
做:
__git_complete gf git_fetch
保持向后兼容性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.