Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

standalone: prevent local _carapace completion #926

Merged
merged 1 commit into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
12 changes: 9 additions & 3 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,16 @@ func addCompletionCommand(cmd *cobra.Command) {
panic("missing parent command") // this should never happen
}

if s, err := complete(cmd.Parent(), args); err != nil {
fmt.Fprintln(io.MultiWriter(cmd.OutOrStderr(), LOG.Writer()), err.Error())
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(parentCmd.OutOrStderr(), LOG.Writer()), err.Error())
} else {
fmt.Fprintln(io.MultiWriter(cmd.OutOrStdout(), LOG.Writer()), s)
fmt.Fprintln(io.MultiWriter(parentCmd.OutOrStdout(), LOG.Writer()), s)
}
},
FParseErrWhitelist: cobra.FParseErrWhitelist{
Expand Down
Loading