Skip to content

Commit

Permalink
standalone: prevent local _carapace completion
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed Oct 2, 2023
1 parent a3d566d commit 3be13d4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
7 changes: 7 additions & 0 deletions carapace.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, "")
Expand Down
7 changes: 6 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ 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" {
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)
Expand Down

0 comments on commit 3be13d4

Please sign in to comment.