// Package carapace is a command argument completion generator for spf13/cobra
package carapace import ( ) // Carapace wraps cobra.Command to define completions. type Carapace struct { cmd *cobra.Command } // Option configures completion for a command. // Options are applied to the storage entry keyed by the command, // so successive Gen() calls on the same command accumulate. type Option func(*entry) // WithSubcommands configures multi-completer support. // The listed commands serve as independent completers within one binary. // The binary name is automatically included as a pseudo-subcommand for self-completion. // When set, Snippet() produces a multi-completer snippet and Execute() handles arg rewriting. func ( ...*cobra.Command) Option { return func( *entry) { .subcommands = := uid.Executable() := make([]string, 0, len()+1) = append(, ) for , := range { = append(, .Name()) } .subcommandNames = if .defaultName == "" { .defaultName = } } } // WithDefault sets the name used for the shell completer function // in multi-completer snippets (e.g. _carapace_<name>_completer). // Defaults to the executable name. No-op without WithSubcommands. func ( string) Option { return func( *entry) { .defaultName = } } // WithSnippetFuncs adds custom shell code to snippets. // The map key is the shell name; the value is the code to inject. // Multiple calls accumulate per shell in order. func ( map[string]string) Option { return func( *entry) { if .snippetFuncs == nil { .snippetFuncs = make(map[string][]string) } for , := range { .snippetFuncs[] = append(.snippetFuncs[], ) } } } // Gen initializes Carapace for given command. // Options configure snippet enrichment, multi-completer routing, etc. func ( *cobra.Command, ...Option) *Carapace { addCompletionCommand() storage.bridge() := storage.get() for , := range { () } return &Carapace{ cmd: , } } // PreRun sets a function to be run before completion. func ( Carapace) ( func( *cobra.Command, []string)) { if := storage.get(.cmd); .prerun != nil { := .prerun .prerun = func( *cobra.Command, []string) { // TODO yuck - probably best to append to a slice in storage (, ) (, ) } } else { .prerun = } } // PreInvoke sets a function to alter actions before they are invoked. func ( Carapace) ( func( *cobra.Command, *pflag.Flag, Action) Action) { if := storage.get(.cmd); .preinvoke != nil { := .preinvoke .preinvoke = func( *cobra.Command, *pflag.Flag, Action) Action { return (, , (, , )) } } else { .preinvoke = } } // PositionalCompletion defines completion for positional arguments using a list of Actions. func ( Carapace) ( ...Action) { storage.get(.cmd).positional = } // PositionalAnyCompletion defines completion for any positional arguments not already defined. func ( Carapace) ( Action) { storage.get(.cmd).positionalAny = & } // DashCompletion defines completion for positional arguments after dash (`--`) using a list of Actions. func ( Carapace) ( ...Action) { storage.get(.cmd).dash = } // DashAnyCompletion defines completion for any positional arguments after dash (`--`) not already defined. func ( Carapace) ( Action) { storage.get(.cmd).dashAny = & } // FlagCompletion defines completion for flags using a map consisting of name and Action. func ( Carapace) ( ActionMap) { := storage.get(.cmd) .flagMutex.Lock() defer .flagMutex.Unlock() if .flag == nil { .flag = } else { maps.Copy(.flag, ) } } const annotation_standalone = "carapace_standalone" // Standalone prevents cobra defaults interfering with standalone mode (e.g. implicit help command). func ( Carapace) () { .cmd.CompletionOptions = cobra.CompletionOptions{ DisableDefaultCmd: true, } if .cmd.Annotations == nil { .cmd.Annotations = make(map[string]string) } .cmd.Annotations[annotation_standalone] = "true" .PreRun(func( *cobra.Command, []string) { if := .Flag("help"); == nil { .Flags().Bool("help", false, "") .Flag("help").Hidden = true } else if .Annotations != nil { if , := .Annotations[cobra.FlagSetByCobraAnnotation]; { .Flag("help").Hidden = true } } }) .cmd.SetHelpCommand(&cobra.Command{Use: "_carapace_help", Hidden: true, Deprecated: "fake help command to prevent default"}) } // Snippet creates completion script for given shell. // For multi-completers, produces a multi-completer snippet (all commands at once). // For single completers, produces a standard single-command snippet. func ( Carapace) ( string) (string, error) { := storage.get(.cmd) if len(.subcommands) > 0 { return multi.Snippet(, .subcommandNames, .defaultName, .snippetFuncs) } , := shell.Snippet(.cmd, ) if != nil { return , } if .snippetFuncs != nil { if , := .snippetFuncs[]; && len() > 0 { = strings.Join(, "\n") + "\n" + } } return , nil } // Execute intercepts os.Args for multi-completer routing and then // calls cmd.Execute(). Call this instead of cmd.Execute(). // For single completers (no WithSubcommands), this just calls cmd.Execute(). func ( Carapace) () error { if := storage.get(.cmd); len(.subcommands) > 0 { .rewriteArgs() } return .cmd.Execute() } // IsCallback returns true if current program invocation is a callback. func () bool { return len(os.Args) > 1 && os.Args[1] == "_carapace" } // rewriteArgs intercepts os.Args for multi-completer routing. // Directly adapted from carapace-magick's root.go Execute(). func ( Carapace) ( *entry) { := uid.Executable() := func( string) bool { return slices.Contains(.subcommandNames, ) } := func( string) bool { for , := range .cmd.Commands() { if .Name() == { return true } } return false } // Root-level _carapace: multi-completer snippet + bridge routing if len(os.Args) > 1 && os.Args[1] == "_carapace" { if len(os.Args) < 4 { := "" if len(os.Args) > 2 { = os.Args[2] } fmt.Println(multi.SnippetOrEmpty(, .subcommandNames, .defaultName, .snippetFuncs)) os.Exit(0) } // Route completion/export requests to the correct subcommand. // bridge.ActionCarapace("binary", "identify") calls: // binary _carapace export "" identify -verbose image.png // Rewrite to: // binary identify _carapace export "" -verbose image.png // // bridge.ActionCarapace("binary") calls: // binary _carapace export "" "" // Rewrite to: // binary binary _carapace export "" "" // (pseudo-subcommand form for self-completion) if len(os.Args) > 4 && (os.Args[4]) && os.Args[4] != { os.Args = append( []string{os.Args[0], os.Args[4], "_carapace", os.Args[2], os.Args[3]}, os.Args[5:]..., ) } else { os.Args = append( []string{os.Args[0], , "_carapace"}, os.Args[2:]..., ) } } // Pseudo-subcommand "binary" — handle without a cobra command. // Provides root-level completion (subcommand names) and single-command snippet. if len(os.Args) > 2 && os.Args[1] == && os.Args[2] == "_carapace" { if len(os.Args) < 4 { return } if os.Args[3] == "export" { // Export format: binary binary _carapace export <shell> "" <args...> if len(os.Args) > 6 && (os.Args[6]) { // Route to the actual subcommand os.Args = append( []string{os.Args[0], os.Args[6], "_carapace", os.Args[3], os.Args[4], os.Args[5]}, os.Args[7:]..., ) } else { // Root-level completion — strip pseudo-subcommand and let rootCmd handle it os.Args = append([]string{os.Args[0]}, os.Args[2:]...) } } else { // Shell format: binary binary _carapace <shell> [args...] if len(os.Args) < 5 { // Snippet request only fmt.Println(multi.SingleSnippetOrEmpty(os.Args[3], , .subcommandNames, .defaultName, .snippetFuncs)) os.Exit(0) } if (os.Args[4]) { // Route to the actual subcommand os.Args = append( []string{os.Args[0], os.Args[4], "_carapace", os.Args[3]}, os.Args[5:]..., ) } else { // Root-level completion — strip pseudo-subcommand and let rootCmd handle it os.Args = append([]string{os.Args[0]}, os.Args[2:]...) } } } // Subcommand-level snippet request: binary <subcommand> _carapace [shell] if len(os.Args) > 2 && (os.Args[1]) && os.Args[2] == "_carapace" { if len(os.Args) < 5 { := "" if len(os.Args) > 3 { = os.Args[3] } fmt.Println(multi.SingleSnippetOrEmpty(, os.Args[1], .subcommandNames, .defaultName, .snippetFuncs)) os.Exit(0) } } } // Test verifies the configuration (e.g. flag name exists) // // func TestCarapace(t *testing.T) { // carapace.Test(t) // } func ( interface{ ( ...any) }) { for , := range storage.check() { .() } }