feat(completion): fast zsh completion for large host caches
Cobra's generated zsh script spawns a subshell per candidate and sends every host through _describe, so <Tab> hangs for seconds with thousands of cached hosts. netssh now ships its own script: subcommands and flags go through _describe, plain hostnames through compadd. 5000 hosts complete in ~0.08 s instead of ~4 s. Add completion.max_results to cap the number of offered hostnames and sort host candidates for a stable order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7f53b90266
commit
8fb7633783
5 files changed
+172
-18
No files matched your search
@@ -88,7 +88,7 @@ func TestCommandAliasCompletesServerNamesAcrossShells(t *testing.T) {
|
||||
case "bash":
|
||||
err = root.GenBashCompletionV2(&canonical, true)
|
||||
case "zsh":
|
||||
err = root.GenZshCompletion(&canonical)
|
||||
_, err = canonical.WriteString(hook.ZshCompletionScript)
|
||||
case "fish":
|
||||
err = root.GenFishCompletion(&canonical, true)
|
||||
}
|
||||
@@ -149,7 +149,8 @@ compinit -u -D
|
||||
alias j=netssh
|
||||
autoload -Uz _j
|
||||
# Capture matches without requiring an interactive ZLE completion widget.
|
||||
_describe() { print -rl -- "${completions[@]}"; }
|
||||
_describe() { print -rl -- "${(P)4}"; }
|
||||
compadd() { print -rl -- "$@"; }
|
||||
words=(j ser)
|
||||
CURRENT=2
|
||||
_j
|
||||
@@ -169,3 +170,38 @@ complete --do-complete 'j ser'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestZshCompletionSplitsHostsAndCommands(t *testing.T) {
|
||||
zsh, err := exec.LookPath("zsh")
|
||||
if err != nil {
|
||||
t.Skip("zsh unavailable")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
backend := "#!/bin/sh\nprintf 'web01\\nweb:02\\ncache\\tManage the cache\\n:36\\n'\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, "netssh"), []byte(backend), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "_netssh"), []byte(hook.ZshCompletionScript), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := `compdef() { :; }
|
||||
source "$DIR/_netssh"
|
||||
_describe() { print -r -- "describe ${(P)4}"; }
|
||||
compadd() { print -r -- "compadd $*"; }
|
||||
_files() { print -r -- files; }
|
||||
words=(netssh "")
|
||||
CURRENT=2
|
||||
_netssh
|
||||
`
|
||||
cmd := exec.Command(zsh, "-f", "-c", script)
|
||||
cmd.Env = append(os.Environ(), "DIR="+dir, "PATH="+dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%v\n%s", err, out)
|
||||
}
|
||||
// Directive 36 = NoFileComp|KeepOrder: unsorted host group, no file fallback.
|
||||
want := "describe cache:Manage the cache\ncompadd -V hosts -X %Bhosts%b -- web01 web:02\n"
|
||||
if string(out) != want {
|
||||
t.Fatalf("got:\n%s\nwant:\n%s", out, want)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user