diff --git a/README.md b/README.md index 483a636..c79130f 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ yetano.dev/yetano/core/doctor yetano.dev/yetano/core/configcmd yetano.dev/yetano/core/version yetano.dev/yetano/core/secretref +yetano.dev/yetano/core/cobracmd (separate module) yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z) yetano.dev/yetano/core/gui/assets @@ -373,6 +374,17 @@ options of other programs), and `create`/`upgrade` keep working on the program's own file. `KnownKey(schema, "a.b[0].c")` tells whether a dotted key is an option of a config struct. +## core/cobracmd: cobra programs (separate module) + +`yetano.dev/yetano/core/cobracmd` (own `go.mod`, tags `cobracmd/vX.Y.Z`, +so the main module stays free of cobra) fixes the two places where cobra +behaves differently from the standard: `cobracmd.Completion(root)` +replaces cobra's default `completion` command with one that takes exactly +`bash|zsh|fish|powershell` (cobra's own exits 0 for `completion tcsh`), +and `os.Exit(cobracmd.Execute(root))` maps errors to the standard exit +codes -- 2 for usage errors (unknown command, flag or shell, wrong +argument count, or an error wrapped with `cobracmd.Usage`), 1 otherwise. + ## core/version: " version [--json]" The values stay in each program's `internal/version` (stamped with diff --git a/cobracmd/cobracmd.go b/cobracmd/cobracmd.go new file mode 100644 index 0000000..dd0d35f --- /dev/null +++ b/cobracmd/cobracmd.go @@ -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 ": 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) +} diff --git a/cobracmd/cobracmd_test.go b/cobracmd/cobracmd_test.go new file mode 100644 index 0000000..46728a7 --- /dev/null +++ b/cobracmd/cobracmd_test.go @@ -0,0 +1,106 @@ +package cobracmd + +import ( + "bytes" + "errors" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func newRoot() *cobra.Command { + root := &cobra.Command{Use: "yatool", SilenceUsage: true, SilenceErrors: true} + root.AddCommand(&cobra.Command{Use: "serve", RunE: func(*cobra.Command, []string) error { return nil }}) + root.AddCommand(&cobra.Command{Use: "one ", Args: cobra.ExactArgs(1), RunE: func(*cobra.Command, []string) error { return nil }}) + root.AddCommand(&cobra.Command{Use: "fail", RunE: func(*cobra.Command, []string) error { return errors.New("broken") }}) + root.AddCommand(&cobra.Command{Use: "bad", RunE: func(*cobra.Command, []string) error { return Usage(errors.New("wrong")) }}) + Completion(root) + return root +} + +func run(args ...string) (int, string) { + root := newRoot() + var out bytes.Buffer + root.SetOut(&out) + root.SetErr(&out) + root.SetArgs(args) + return Execute(root), out.String() +} + +func TestExitCodes(t *testing.T) { + for _, tc := range []struct { + args []string + want int + }{ + {[]string{"serve"}, ExitOK}, + {[]string{"fail"}, ExitProblem}, + {[]string{"bad"}, ExitUsage}, + {[]string{"nosuch"}, ExitUsage}, + {[]string{"serve", "--nosuch"}, ExitUsage}, + {[]string{"one"}, ExitUsage}, + {[]string{"one", "a", "b"}, ExitUsage}, + {[]string{"completion"}, ExitUsage}, + {[]string{"completion", "tcsh"}, ExitUsage}, + {[]string{"completion", "bash", "zsh"}, ExitUsage}, + } { + if got, out := run(tc.args...); got != tc.want { + t.Errorf("%v: exit %d, want %d (%s)", tc.args, got, tc.want, out) + } + } +} + +func TestCompletionScripts(t *testing.T) { + for shell, want := range map[string][]string{ + "bash": {`eval "$(yatool completion bash)"`, "__start_yatool"}, + "zsh": {"#compdef yatool", "source <(yatool completion zsh)"}, + "fish": {"yatool completion fish | source", "complete -c yatool"}, + "powershell": {"Invoke-Expression", "Register-ArgumentCompleter"}, + } { + code, out := run("completion", shell) + if code != ExitOK { + t.Fatalf("%s: exit %d", shell, code) + } + for _, w := range want { + if !strings.Contains(out, w) { + t.Errorf("%s script lacks %q", shell, w) + } + } + } + if _, out := run("completion", "zsh"); !strings.HasPrefix(out, "#compdef") { + t.Errorf("zsh script must start with #compdef: %.40q", out) + } +} + +func TestCompletionReplacesDefault(t *testing.T) { + root := newRoot() + n := 0 + for _, c := range root.Commands() { + if c.Name() == "completion" { + n++ + } + } + if n != 1 { + t.Fatalf("%d completion commands, want 1", n) + } + // Calling it twice (e.g. a shared root builder) still leaves one. + Completion(root) + n = 0 + for _, c := range root.Commands() { + if c.Name() == "completion" { + n++ + } + } + if n != 1 { + t.Fatalf("after a second Completion: %d completion commands, want 1", n) + } +} + +func TestIsUsage(t *testing.T) { + if IsUsage(nil) || IsUsage(errors.New("disk full")) { + t.Error("plain errors are no usage errors") + } + if !IsUsage(Usage(errors.New("x"))) || Usage(nil) != nil { + t.Error("Usage wrapping") + } +} diff --git a/cobracmd/go.mod b/cobracmd/go.mod new file mode 100644 index 0000000..eca9d3c --- /dev/null +++ b/cobracmd/go.mod @@ -0,0 +1,10 @@ +module yetano.dev/yetano/core/cobracmd + +go 1.25.0 + +require github.com/spf13/cobra v1.10.2 + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) diff --git a/cobracmd/go.sum b/cobracmd/go.sum new file mode 100644 index 0000000..a6ee3e0 --- /dev/null +++ b/cobracmd/go.sum @@ -0,0 +1,10 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/completion/completion.go b/completion/completion.go index 2b5fdd6..b8785c0 100644 --- a/completion/completion.go +++ b/completion/completion.go @@ -97,7 +97,7 @@ func Script(program, shell string, tree Tree) (string, error) { var b strings.Builder switch shell { case "bash": - fmt.Fprintf(&b, "# %s bash completion. Install with:\n# source <(%s completion bash)\n", program, program) + 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\")); return ;;\n", e.prefix, strings.Join(e.words, " "))