diff --git a/carapace.go b/carapace.go index 714139f69..736cfc42b 100644 --- a/carapace.go +++ b/carapace.go @@ -85,12 +85,19 @@ func (c Carapace) FlagCompletion(actions ActionMap) { } } +const annotation_standalone = "carapace_standalone" + // Standalone prevents cobra defaults interfering with standalone mode (e.g. implicit help command). func (c Carapace) Standalone() { c.cmd.CompletionOptions = cobra.CompletionOptions{ DisableDefaultCmd: true, } + if c.cmd.Annotations == nil { + c.cmd.Annotations = make(map[string]string) + } + c.cmd.Annotations[annotation_standalone] = "true" + c.PreRun(func(cmd *cobra.Command, args []string) { if f := cmd.Flag("help"); f == nil { cmd.Flags().Bool("help", false, "") diff --git a/command.go b/command.go index f58937f6e..b84fedabb 100644 --- a/command.go +++ b/command.go @@ -32,7 +32,13 @@ func addCompletionCommand(cmd *cobra.Command) { panic("missing parent command") // this should never happen } - if s, err := complete(cmd.Parent(), args); err != nil { + parentCmd := cmd.Parent() + if parentCmd.Annotations[annotation_standalone] == "true" { + // TODO how to handle an explicit `_carapace` command? + parentCmd.RemoveCommand(cmd) // don't complete local `_carapace` in standalone mode + } + + if s, err := complete(parentCmd, args); err != nil { fmt.Fprintln(io.MultiWriter(cmd.OutOrStderr(), LOG.Writer()), err.Error()) } else { fmt.Fprintln(io.MultiWriter(cmd.OutOrStdout(), LOG.Writer()), s)