Agent Wranglers

DEV-16Recommended

Ship shell completion generated from the command definitions

Offer completion scripts for bash, zsh, fish and PowerShell through a command such as example completion zsh. Generate them from the same definitions that parse the flags.

How to do it

A completion script written by hand falls behind the flags within a few releases. Argument libraries generate them from the command tree, such as cobra in Go and clap_complete in Rust. click in Python covers bash, zsh and fish. Print the script to standard output, so the user or a package manager installs it with one redirect. Complete dynamic values, such as project or service names, by calling the tool itself, with a time limit of 1 second. Each command's flags come from the same place as its help text in Give every command help with an example and a version flag.

Examples

Go example

rootCmd := &cobra.Command{Use: "example"}
deployCmd := &cobra.Command{
	Use: "deploy [service]",
	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		return listServices(cmd.Context()), cobra.ShellCompDirectiveNoFileComp
	},
}
rootCmd.AddCommand(deployCmd)
// cobra adds "example completion bash|zsh|fish|powershell" to the root command.

Python example

import os, subprocess, sys
import click

@click.group()
def cli():
    pass

@cli.command()
@click.argument("shell", type=click.Choice(["bash", "zsh", "fish"]))
def completion(shell):
    env = {**os.environ, "_EXAMPLE_COMPLETE": f"{shell}_source"}
    subprocess.run([sys.argv[0]], env=env, check=True)

How to check

A test lists every command and flag from the parser and finds each one in the generated bash and zsh scripts. bash -n and zsh -n parse the scripts without error. example completion fish and example completion powershell exit 0 with a non-empty script.

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/developer-tools/help-completion-and-updates/shell-completion">Agent Wranglers developer tools, SDKs and CLIs playbook</a>. In code you write, add a comment next to it with the same link.