Files
core/cobracmd/cobracmd.go
T
terminarandClaude Opus 5.5 5471863163 cobracmd: unknown subcommands of a command group are usage errors (exit 2)
cobra rejects an unknown subcommand only at the root; "prog group nosuch"
printed the group's help and exited 0. Execute now calls StrictGroups
first (found in yamase-ctl while rolling out cobracmd/v0.1.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:48:52 +01:00

209 lines
6.6 KiB
Go

// 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.
//
// Before running, it makes every command group below root strict (see
// StrictGroups): cobra itself rejects an unknown subcommand only at the
// root ("prog nosuch"), while "prog group nosuch" printed the group's
// help and exited 0.
func Execute(root *cobra.Command) int {
StrictGroups(root)
err := root.Execute()
switch {
case err == nil:
return ExitOK
case IsUsage(err):
return ExitUsage
default:
return ExitProblem
}
}
// StrictGroups makes every command below root that only groups
// subcommands (it has subcommands, no Run/RunE and no Args of its own)
// reject an unknown subcommand as a usage error; called without one it
// still prints its help (exit 0). Execute calls it; it is exported for
// programs that run root.Execute themselves.
func StrictGroups(root *cobra.Command) {
var walk func(c *cobra.Command)
walk = func(c *cobra.Command) {
for _, sub := range c.Commands() {
if sub.HasSubCommands() && !sub.Runnable() && sub.Args == nil {
sub.Args = func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return Usage(fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()))
}
return nil
}
sub.RunE = func(cmd *cobra.Command, _ []string) error { return cmd.Help() }
}
walk(sub)
}
}
walk(root)
}
// 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)
}