我正在尝试为 Zsh 编写一个完成脚本。我想对完成脚本进行单元测试。例如,我想测试完成情况my-command --h
包括--help
.
对于鱼,我可以使用complete -C 'my-command --h',然后会输出--help
以及任何其他有效的完成情况。
我似乎找不到 Zsh 的等效命令。有吗?我尝试过类似的事情_main_complete
, _complete
and _normal
,但要么他们不支持这一点,要么我没有以正确的方式调用它们(我得到了很多can only be called from completion function
错误)。
我得到很多can only be called from completion function errors
这是因为 Zsh 的完成命令只能从完成小部件内部运行,而该小部件又只能在 Zsh 行编辑器处于活动状态时调用。我们可以通过在所谓的活动命令行上激活完成小部件来解决此问题伪终端:
# Set up your completions as you would normally.
compdef _my-command my-command
_my-command () {
_arguments '--help[display help text]' # Just an example.
}
# Define our test function.
comptest () {
# Gather all matching completions in this array.
# -U discards duplicates.
typeset -aU completions=()
# Override the builtin compadd command.
compadd () {
# Gather all matching completions for this call in $reply.
# Note that this call overwrites the specified array.
# Therefore we cannot use $completions directly.
builtin compadd -O reply "$@"
completions+=("$reply[@]") # Collect them.
builtin compadd "$@" # Run the actual command.
}
# Bind a custom widget to TAB.
bindkey "^I" complete-word
zle -C {,,}complete-word
complete-word () {
# Make the completion system believe we're on a normal
# command line, not in vared.
unset 'compstate[vared]'
_main_complete "$@" # Generate completions.
# Print out our completions.
# Use of ^B and ^C as delimiters here is arbitrary.
# Just use something that won't normally be printed.
print -n $'\C-B'
print -nlr -- "$completions[@]" # Print one per line.
print -n $'\C-C'
exit
}
vared -c tmp
}
zmodload zsh/zpty # Load the pseudo terminal module.
zpty {,}comptest # Create a new pty and run our function in it.
# Simulate a command being typed, ending with TAB to get completions.
zpty -w comptest $'my-command --h\t'
# Read up to the first delimiter. Discard all of this.
zpty -r comptest REPLY $'*\C-B'
zpty -r comptest REPLY $'*\C-C' # Read up to the second delimiter.
# Print out the results.
print -r -- "${REPLY%$'\C-C'}" # Trim off the ^C, just in case.
zpty -d comptest # Delete the pty.
运行上面的例子将打印出:
--help
如果您想测试整个完成输出,而不仅仅是要在命令行上插入的字符串,请参阅https://unix.stackexchange.com/questions/668618/how-to-write-automated-tests-for-zsh-completion/668827#668827
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)