Skip to content

Shell Completion

Cobra’s completion command is available on every cmdguard CLI; cmdguard does not disable it. Generate a script for your shell:

Terminal window
myapp completion bash > /etc/bash_completion.d/myapp
myapp completion zsh > "${fpath[1]}/_myapp"
myapp completion fish > ~/.config/fish/completions/myapp.fish
myapp completion powershell > myapp.ps1

Users also get completion for command names, aliases, and flags from the generated script.

WithCompletion sets the command’s ValidArgsFunction. It is called while the shell completes positional arguments:

package main
import (
"context"
"fmt"
"os"
v5 "github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5"
"github.com/spf13/cobra"
)
type AppConfig struct{}
type DoneFlags struct {
ID string `flag:"id" help:"Task ID"`
}
func main() {
cli, err := v5.NewCLI[AppConfig]("myapp", "My application", AppConfig{})
if err != nil {
fmt.Fprintf(os.Stderr, "create CLI: %v\n", err)
os.Exit(1)
}
doneCmd, err := v5.NewCommand("done", DoneFlags{},
func(ctx context.Context, cfg *AppConfig, flags DoneFlags) error {
fmt.Printf("marking %s done\n", flags.ID)
return nil
},
v5.WithShort("Mark a task done"),
v5.WithCompletion(func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{
"build\tBuild the binary",
"test\tRun the tests",
"lint\tLint the code",
}, cobra.ShellCompDirectiveNoFileComp
}),
)
b := v5.NewBuilder(cli)
v5.Try(b, doneCmd, err)
if err := b.Build(); err != nil {
fmt.Fprintf(os.Stderr, "register command: %v\n", err)
os.Exit(1)
}
cli.ExecuteAndExit(context.Background())
}

CompletionFunc is func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective). Each candidate may carry a description after a tab. cobra.ShellCompDirectiveNoFileComp stops the shell from also offering filenames.

cmdguard’s handler signature has no args parameter. Read them from the context:

func handler(ctx context.Context, cfg *AppConfig, _ v5.NoFlags) error {
args := v5.ArgsFromContext(ctx)
if len(args) == 0 {
return fmt.Errorf("missing path")
}
return process(args[0])
}

WithValidArgs supplies static completion candidates. It does not, by itself, reject other values: pair it with WithArgs(cobra.OnlyValidArgs) when the set must also be enforced.

setCmd, err := v5.NewCommand("set", v5.NoFlags{}, setHandler,
v5.WithShort("Set the log level"),
v5.WithValidArgs("debug", "info", "warn", "error"),
v5.WithArgs(cobra.OnlyValidArgs),
)

With both options, myapp set de<TAB> offers debug, and myapp set trace fails before the handler runs.

Option Behavior
WithArgs(fn) Custom cobra.PositionalArgs validator
WithExactArgs(n) Exactly n arguments
WithMinimumArgs(n) At least n arguments
WithMaximumArgs(n) At most n arguments
WithRangeArgs(min, max) Between min and max arguments, inclusive
WithNoArgs() Reject every positional argument
WithStrictPositionalArgs() Reject positionals when no other validator is set (since v5.1.0)
WithArgsPassthrough() Accept any positionals and ignore extras (since v5.1.0)

WithStrictPositionalArgs is opt-in today (both flags ship since v5.1.0 — they do not exist at a v5.0.0 pin). It only applies when no other validator was configured; an explicit WithExactArgs, WithNoArgs, or WithArgs wins. WithArgsPassthrough pins the current permissive behavior and will be the opt-out if the strict default lands.

Opt in per command when a zero-argument command must never silently swallow stray positionals:

doneCmd, err := v5.NewCommand("done", v5.NoFlags{}, doneHandler,
v5.WithShort("Mark a task done"),
v5.WithStrictPositionalArgs(),
)

With the strict option, myapp done 1 extra fails before the handler runs instead of dropping extra. To keep the old behavior for a command whose callers pipe extra tokens, pin it explicitly with v5.WithArgsPassthrough() — an explicit choice beats a silent default.

Flag value completion is a cobra hook, not a WithCompletion responsibility. After Build, find the command on the underlying root and register the function:

doneCobra, _, err := cli.RootCommand().Find([]string{"done"})
if err != nil {
return err
}
err = doneCobra.RegisterFlagCompletionFunc("id",
func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"build", "test", "lint"}, cobra.ShellCompDirectiveNoFileComp
},
)

Now myapp done --id <TAB> completes task IDs. Use cobra.ShellCompDirectiveDefault when filenames are also valid.