cobracmd: standard completion and exit codes for cobra programs; bash install line via eval
New module yetano.dev/yetano/core/cobracmd (own go.mod, cobra stays out of the main module): Completion replaces cobra's default completion command, which exits 0 for an unknown shell, with one that accepts only bash|zsh|fish|powershell (exit 2 otherwise); Execute maps cobra's usage errors to exit 2, other errors to 1. completion: the bash script's install line is eval "$(prog completion bash)" -- bash 3.2 on macOS cannot source a process substitution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fa52990e3e
commit
5288c4ce74
6 files changed
+317
-1
No files matched your search
@@ -0,0 +1,178 @@
|
||||
// Package cobracmd gives cobra-based Yetano programs the parts of the
|
||||
// program standard (docs/program-conventions.md in the yetano
|
||||
// meta-repository) that cobra does differently by default:
|
||||
//
|
||||
// - Completion replaces cobra's default "completion" command with one
|
||||
// that takes exactly bash, zsh, fish or powershell. cobra's own
|
||||
// command prints its help and exits 0 for "completion tcsh"; the
|
||||
// standard wants exit 2 for an unknown shell.
|
||||
// - Execute runs the root command and returns the standard exit code:
|
||||
// 0 on success, 2 for a usage error (unknown command, flag or shell,
|
||||
// wrong number of arguments), 1 for any other error.
|
||||
//
|
||||
// It is a separate module (yetano.dev/yetano/core/cobracmd) so that the
|
||||
// main core module stays free of cobra.
|
||||
//
|
||||
// func main() {
|
||||
// root := newRootCommand()
|
||||
// cobracmd.Completion(root)
|
||||
// os.Exit(cobracmd.Execute(root))
|
||||
// }
|
||||
//
|
||||
// A command that wants to report a usage error itself returns
|
||||
// cobracmd.Usage(err).
|
||||
package cobracmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Exit codes, matching core/doctor's.
|
||||
const (
|
||||
ExitOK = 0
|
||||
ExitProblem = 1
|
||||
ExitUsage = 2
|
||||
)
|
||||
|
||||
// Shells are the shells "completion" accepts.
|
||||
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
||||
|
||||
// UsageError marks an error as a usage error (exit 2).
|
||||
type UsageError struct{ Err error }
|
||||
|
||||
func (e *UsageError) Error() string { return e.Err.Error() }
|
||||
func (e *UsageError) Unwrap() error { return e.Err }
|
||||
|
||||
// Usage wraps err as a usage error; nil stays nil.
|
||||
func Usage(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &UsageError{Err: err}
|
||||
}
|
||||
|
||||
// cobraUsage are the prefixes of the usage errors cobra and pflag
|
||||
// produce themselves (unknown command, argument validators, flags).
|
||||
var cobraUsage = []string{
|
||||
"unknown command ",
|
||||
"unknown flag: ",
|
||||
"unknown shorthand flag: ",
|
||||
"flag needs an argument: ",
|
||||
"invalid argument ",
|
||||
"bad flag syntax: ",
|
||||
"required flag(s) ",
|
||||
"if any flags in the group ",
|
||||
"accepts ",
|
||||
"requires at least ",
|
||||
"requires at most ",
|
||||
}
|
||||
|
||||
// IsUsage reports whether err is a usage error: wrapped with Usage, or
|
||||
// one of cobra's/pflag's own argument and flag errors.
|
||||
func IsUsage(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var u *UsageError
|
||||
if errors.As(err, &u) {
|
||||
return true
|
||||
}
|
||||
msg := err.Error()
|
||||
for _, p := range cobraUsage {
|
||||
if strings.HasPrefix(msg, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Execute runs root and returns the exit code: 0, 2 for a usage error,
|
||||
// 1 for any other error. cobra prints the error itself unless the
|
||||
// command sets SilenceErrors.
|
||||
func Execute(root *cobra.Command) int {
|
||||
err := root.Execute()
|
||||
switch {
|
||||
case err == nil:
|
||||
return ExitOK
|
||||
case IsUsage(err):
|
||||
return ExitUsage
|
||||
default:
|
||||
return ExitProblem
|
||||
}
|
||||
}
|
||||
|
||||
// Completion replaces cobra's default completion command on root with
|
||||
// "completion <bash|zsh|fish|powershell>": exactly one argument, one of
|
||||
// Shells; anything else is a usage error. The script is cobra's own
|
||||
// (subcommands and flags, with descriptions), preceded by its install
|
||||
// line.
|
||||
func Completion(root *cobra.Command) {
|
||||
root.CompletionOptions.DisableDefaultCmd = true
|
||||
for _, c := range root.Commands() {
|
||||
if c.Name() == "completion" {
|
||||
root.RemoveCommand(c)
|
||||
}
|
||||
}
|
||||
name := root.Name()
|
||||
root.AddCommand(&cobra.Command{
|
||||
Use: "completion <" + strings.Join(Shells, "|") + ">",
|
||||
Short: "Print a shell completion script",
|
||||
Long: installHelp(name),
|
||||
ValidArgs: Shells,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) != 1 {
|
||||
return Usage(fmt.Errorf("%s completion: exactly one shell expected (%s)", name, strings.Join(Shells, ", ")))
|
||||
}
|
||||
for _, s := range Shells {
|
||||
if args[0] == s {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, args[0], strings.Join(Shells, ", ")))
|
||||
},
|
||||
DisableFlagsInUseLine: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return Script(root, args[0], cmd.OutOrStdout())
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Script writes root's completion script for shell to w.
|
||||
func Script(root *cobra.Command, shell string, w io.Writer) error {
|
||||
name := root.Name()
|
||||
switch shell {
|
||||
case "bash":
|
||||
fmt.Fprintf(w, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", name, name)
|
||||
return root.GenBashCompletionV2(w, true)
|
||||
case "zsh":
|
||||
// cobra's script starts with "#compdef", which must stay the
|
||||
// first line for zsh's fpath autoloading.
|
||||
if err := root.GenZshCompletion(w); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := fmt.Fprintf(w, "# Install with: source <(%s completion zsh) (after compinit)\n", name)
|
||||
return err
|
||||
case "fish":
|
||||
fmt.Fprintf(w, "# %s fish completion. Install with:\n# %s completion fish | source\n", name, name)
|
||||
return root.GenFishCompletion(w, true)
|
||||
case "powershell":
|
||||
fmt.Fprintf(w, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", name, name)
|
||||
return root.GenPowerShellCompletionWithDesc(w)
|
||||
default:
|
||||
return Usage(fmt.Errorf("%s completion: unknown shell %q (%s)", name, shell, strings.Join(Shells, ", ")))
|
||||
}
|
||||
}
|
||||
|
||||
func installHelp(name string) string {
|
||||
return fmt.Sprintf(`Print a completion script for bash, zsh, fish or PowerShell.
|
||||
|
||||
eval "$(%[1]s completion bash)" # ~/.bashrc
|
||||
source <(%[1]s completion zsh) # ~/.zshrc, after compinit
|
||||
%[1]s completion fish | source # ~/.config/fish/config.fish
|
||||
%[1]s completion powershell | Out-String | Invoke-Expression # $PROFILE`, name)
|
||||
}
|
||||
Reference in new issue
Block a user