zsh:完成 command1 与 command2 ARG 相同

zsh: Complete `command1` the same as `command2 ARG`

给定两个命令:

如何使 command2 以与 command1 ARG1 相同的方式完成 而无需为 command1 编写自定义完成?

这是一个例子:

alias command1="git ls-files"

command2() {
  echo "I'm a wrapper for git ls-files" >&2
  git ls-files $@
}

一个人可以做到 compdef command2=command1 - 但这将使 command2 以与 git 相同的方式完成,而不像 git ls-files.

编辑:我正在寻找一个广泛而通用的解决方案,该解决方案也适用于未定义单独完成功能的命令,例如 git。 对于这些,您可以按照下面 Marlon Richert 的建议进行操作。

这是一个更好的例子:

alias command1="kubectl get pod"

command2() {
  echo "I'm a wrapper for kubectl get pod" >&2
  kubectl get pod $@
}

执行此操作以找出需要调用的函数的名称:

% git ls-files ^Xh  # That is, press Ctrl-X, then H.
tags in context :completion::complete:git-ls-files::
    argument-rest options  (_arguments _git-ls-files _git)
tags in context :completion::complete:git-ls-files:argument-rest:
    globbed-files  (_files _arguments _git-ls-files _git)
tags in context :completion::complete:git::
    argument-rest  (_arguments _git)

如您所见,是 _git-ls-files

然后,丢弃前导 _ 并使用余数作为 compdef$service 参数:

compdef _git command2=git-ls-files

现在可以正常工作了:

% command2 ^Xh
tags in context :completion::complete:command2::
    argument-rest options  (_arguments _git-ls-files _git)
tags in context :completion::complete:command2:argument-rest:
    globbed-files  (_files _arguments _git-ls-files _git)

更新

对于您的 kubectl 示例,事情稍微不那么简单,因为它的完成 不是 Zsh 原生的。 相反,它只是围绕 Bash补全函数。在这种情况下,您 必须编写自己的完成函数,但值得庆幸的是,它只是一个很短的函数:

_command2 () {
  # Fake having `kubectl get pod` on the line instead of `command2`.
  local -a words=( kubectl get pod $words[2,-1] )
  local -i CURRENT=$(( CURRENT + 2 ))

  # Call kubectl completion.
  eval "$_comps[kubectl]"
}
compdef _command2 command2

完成!