// Package completion is the shared " completion " command // of the Yetano program standard (see docs/program-conventions.md in the // yetano meta-repository): it prints a shell completion script for bash, // zsh, fish or PowerShell, generated from a static command tree. // // The scripts are deliberately simple, word-based completion of command // and subcommand names (not flag-aware): they join the words typed so far // into a prefix and look up what may follow it. A level that also takes a // file or directory path (a program without subcommands that is started // as " [path]") adds the Files key; the shell then completes // paths there too: // // var tree = completion.Tree{completion.Files: nil, "manual": nil, ...} // // var tree = completion.Tree{ // "serve": nil, // "config": completion.Leaf("create", "validate", "path"), // "manual": nil, // "doctor": nil, // "completion": completion.Leaf(completion.Shells...), // "version": nil, // } // case "completion": // err := completion.Run("yasl", tree, args[1:], os.Stdout) package completion import ( "errors" "fmt" "io" "regexp" "sort" "strings" ) // Tree is one level of a program's commands: a name maps to its // subcommands, or to nil for a command without any. type Tree map[string]Tree // Leaf is a level of commands that have no subcommands themselves. func Leaf(names ...string) Tree { t := make(Tree, len(names)) for _, n := range names { t[n] = nil } return t } // Files is a Tree key, not a command: the level it is in also completes // file and directory paths. Its value is ignored. const Files = "" // Shells are the supported shells, in the order help texts list them. var Shells = []string{"bash", "zsh", "fish", "powershell"} // ErrUsage is returned by Run for a missing or unknown shell. var ErrUsage = errors.New("usage: completion ") var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`) // entry is a prefix (words typed so far, space-joined) and what may follow. type entry struct { prefix string words []string files bool // paths complete here too (Files) } func flatten(tree Tree) ([]entry, error) { var out []entry var walk func(prefix string, t Tree) error walk = func(prefix string, t Tree) error { names := make([]string, 0, len(t)) files := false for n := range t { if n == Files { files = true continue } if !safeWord.MatchString(n) { return fmt.Errorf("completion: command name %q is not a plain word", n) } names = append(names, n) } sort.Strings(names) out = append(out, entry{prefix, names, files}) for _, n := range names { if sub := t[n]; len(sub) > 0 { p := n if prefix != "" { p = prefix + " " + n } if err := walk(p, sub); err != nil { return err } } } return nil } return out, walk("", tree) } func anyFiles(entries []entry) bool { for _, e := range entries { if e.files { return true } } return false } // Script returns the completion script for shell. func Script(program, shell string, tree Tree) (string, error) { if !safeWord.MatchString(program) { return "", fmt.Errorf("completion: program name %q is not a plain word", program) } entries, err := flatten(tree) if err != nil { return "", err } fn := "_" + strings.NewReplacer("-", "_", ".", "_", ":", "_", "+", "_").Replace(program) + "_complete" var b strings.Builder switch shell { case "bash": fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program) fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn) for _, e := range entries { fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\"))", e.prefix, strings.Join(e.words, " ")) if e.files { // One path per line, so names with spaces stay whole; // compopt (bash 4+) adds the trailing "/" and quoting. b.WriteString("\n local IFS=$'\\n'; COMPREPLY+=($(compgen -f -- \"$cur\")); compopt -o filenames 2>/dev/null") } b.WriteString("; return ;;\n") } fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program) case "zsh": fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program) fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\" files=0\n local -a completions\n case \"$prefix\" in\n", fn) for _, e := range entries { f := "" if e.files { f = "; files=1" } fmt.Fprintf(&b, " %q) completions=(%s)%s ;;\n", e.prefix, strings.Join(e.words, " "), f) } fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n") if anyFiles(entries) { b.WriteString(" (( files )) && _files\n") } b.WriteString("}\n") fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program) case "fish": fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program) fmt.Fprintf(&b, "function %s\n set -l tokens (commandline -opc)\n set -l prefix (string join ' ' -- $tokens[2..-1])\n switch \"$prefix\"\n", fn) for _, e := range entries { if e.prefix == "" { b.WriteString(" case ''\n") } else { fmt.Fprintf(&b, " case %q\n", e.prefix) } quoted := make([]string, len(e.words)) for i, w := range e.words { quoted[i] = fmt.Sprintf("%q", w) } fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " ")) if e.files { b.WriteString(" __fish_complete_path (commandline -ct)\n") } } fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn) case "powershell": fmt.Fprintf(&b, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", program, program) fmt.Fprintf(&b, "Register-ArgumentCompleter -Native -CommandName '%s', '%s.exe' -ScriptBlock {\n", program, program) b.WriteString(" param($wordToComplete, $commandAst, $cursorPosition)\n") b.WriteString(" $words = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.ToString() })\n") b.WriteString(" if ($wordToComplete -ne '' -and $words.Count -gt 0) { $words = @($words | Select-Object -First ($words.Count - 1)) }\n") b.WriteString(" $prefix = $words -join ' '\n $candidates = switch ($prefix) {\n") for _, e := range entries { quoted := make([]string, len(e.words)) for i, w := range e.words { quoted[i] = "'" + w + "'" } fmt.Fprintf(&b, " '%s' { @(%s) }\n", e.prefix, strings.Join(quoted, ", ")) } b.WriteString(" default { @() }\n }\n") b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n") b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n") var filePrefixes []string for _, e := range entries { if e.files { filePrefixes = append(filePrefixes, "'"+e.prefix+"'") } } if len(filePrefixes) > 0 { fmt.Fprintf(&b, " if (@(%s) -contains $prefix) {\n", strings.Join(filePrefixes, ", ")) b.WriteString(" [System.Management.Automation.CompletionCompleters]::CompleteFilename($wordToComplete)\n }\n") } b.WriteString("}\n") default: return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell) } return b.String(), nil } // Run serves " completion " -- args are the arguments // after "completion" -- writing the script to w. func Run(program string, tree Tree, args []string, w io.Writer) error { if len(args) != 1 { return ErrUsage } script, err := Script(program, args[0], tree) if err != nil { return err } _, err = io.WriteString(w, script) return err }