【发布时间】:2015-07-09 09:29:13
【问题描述】:
假设 bash 配置了以下别名:
alias up="git --git-dir /path/to/backup/.git"
并且那个特定的存储库 - 并且只有那个存储库 - 具有以下 git 别名:
[alias]
backup = commit --allow-empty-message
up如何自动补全backup?
这会自动完成backup,但不会自动完成up:
cd /a/different/dir
git --git-dir=/path/to/backup/.git ba
这会使用标准 git 命令自动完成 up,而不是 backup:
complete -o bashdefault -o default -o nospace -F __git_wrap__git_main up
编辑:Etan是对的,补全功能需要看到扩展的别名,所以我创建了如下:
CompletableAlias() {
if (($#<2)); then
return 1
fi
source_c="$1"
target_c="$2"
target_a=( "${@:2}" )
target_s="${target_a[*]}"
alias "${source_c}=${target_s}"
completion_modifier="__${source_c}_completion"
completion_original="$( complete -p "$target_c" 2>/dev/null |
sed 's/.*-F\W\+\(\w\+\).*/\1/'
)"
if [[ -n "$completion_original" ]]; then
read -r -d '' completion_function <<-EOF
function $completion_modifier() {
COMP_LINE="\${COMP_LINE/#${source_c}/${target_s}}"
((COMP_POINT+=${#target_s}-${#source_c}))
((COMP_CWORD+=${#target_a[@]}-1))
COMP_WORDS=( ${target_a[@]} \${COMP_WORDS[@]:1} )
$completion_original
}
EOF
eval "$completion_function"
completion_command="$( complete -p "$target_c" |
sed "s/${completion_original}/${completion_modifier}/;
s/\w\+\$/${source_c}/"
)"
$completion_command
fi
}
source "/usr/share/bash-completion/completions/git"
CompletableAlias "up" "git" "--git-dir" "/path/to/backup/.git"
但是出现了莫名其妙的问题:
-
up bac<Tab>不起作用 -
up <Tab>使用默认完成并且不列出 git 子命令 - 还有更多...
编辑 2:使用Re: Bash completion of aliased commands 的建议更新了脚本以修复上述问题。显然,这是一个很常见的任务。但是现在我遇到了这个错误消息:
$ cd /a/different/dir
$ up backup<Tab> fatal: Not a git repository (or any of the parent directories): .git
【问题讨论】:
-
补全函数看到
up还是扩展别名? -
如果完成函数在命令中读取为“up”,则它不会按预期运行,请使用辅助函数扩展为“backup”,这样您就可以确保将确切的命令发送到完成功能。这就是许多更完整的功能的情况,他们期望(或假设)该命令是他们对其进行编程的。因此,如果您将完成程序附加到其他命令,它将无法工作(因此有中间人功能)。首先,您可能会显示来自 -xv 调用两者的一些输出,以确保您的函数正在执行您期望的(或它的差异)
标签: git bash bash-completion