Skip to content

Add shell completion to a CLI

In this tutorial, we will add shell completion to cloudctl. CONGA completes commands and flags from the structs on its own, and we will complete values from a tag, a type, and an API call. We continue in the cloudctl directory from Test a CLI.

By the end, --image completes with the images the API lists for the service being deployed:

Bash
$ ./cloudctl deploy web --image <Tab><Tab><Tab>
nginx:1.26 nginx:1.27

<Tab> marks a Tab press, and the lines under the command are the shell’s output.

Add EnableCompletion to the builder in newApp:

main.go
func newApp() *conga.App[CLI] {
return conga.New[CLI]().
Name("cloudctl").
Description("Manage services in the cloud").
Version("0.1.0").
EnableCompletion().
EnvPrefix("CLOUDCTL").
RegisterDecoder(".yaml", yaml.Decode).
ConfigOptions(conga.ConfigPaths("."))
}

Build the program, and look at its help:

Terminal window
go build
Terminal window
$ ./cloudctl --help
Manage services in the cloud
Usage:
cloudctl <command> [flags]
Commands:
deploy Deploy a service
status Show service status
completion Generate shell completion scripts
Flags:
-r, --region="us-east-1" Region to work in [env: CLOUDCTL_REGION]
--help Show help
--version Show version

EnableCompletion adds a completion command that prints a completion script for each shell. Load the script:

Bash
source <(./cloudctl completion bash)

Load or install the completion script covers loading it in every new shell, and in fish, PowerShell, Elvish, and Nushell.

Commands complete from the conga.Command fields, each described by its summary tag:

Bash
$ ./cloudctl <Tab><Tab>
completion (Generate shell completion scripts) status (Show service status)
deploy (Deploy a service)

Flags complete from the fields of the command and its parents, so deploy offers the root’s --region too. Each is described by its help tag. In zsh, CONGA colors the flags that take a value:

Bash
$ ./cloudctl deploy --<Tab><Tab>
--help (Show help) --region (Region to work in) --yes (Deploy without asking)
--image (Container image to run) --replicas (Number of copies to run)

--region accepts four regions. Add an enum tag that lists them:

main.go
type CLI struct {
Region conga.OptionalFlag[string] `default:"us-east-1" enum:"us-east-1,us-west-2,eu-west-1,ap-south-1" help:"Region to work in" short:"r"`
Deploy conga.Command[DeployCmd] `summary:"Deploy a service"`
Status conga.Command[StatusCmd] `summary:"Show service status"`
}

Build the program, and complete --region:

Terminal window
go build
Bash
$ ./cloudctl deploy web --region <Tab><Tab>
ap-south-1 eu-west-1 us-east-1 us-west-2

The enum tag gave --region a predictor that offers the four regions.

conga.File is CONGA’s type for a path to a file, and its predictor offers file names. We will add an --env-file flag that names a file of environment variables for the deployed service. Add the field to DeployCmd, and print the file when it is set:

main.go
type DeployCmd struct {
Service conga.RequiredArg[string] `help:"Service to deploy"`
Image conga.RequiredFlag[string] `help:"Container image to run"`
Replicas conga.OptionalFlag[int] `default:"2" help:"Number of copies to run"`
existing rejects a path that doesn't exist, and glob offers only names that match.
EnvFile conga.OptionalFlag[conga.File] `existing:"true" glob:"*.env"`
Yes conga.OptionalFlag[bool] `help:"Deploy without asking" short:"y"`
}
func (d *DeployCmd) Run(ctx context.Context, session *conga.Session) error {
root := session.Root[CLI]()
if !d.Yes.Get() {
// ...
}
fmt.Fprintf(session.Stdout(), "deploying %s (%s) to %s with %d replicas\n", d.Service.Get(), d.Image.Get(), root.Region.Get(), d.Replicas.Get())
if d.EnvFile.IsSet() {
fmt.Fprintf(session.Stdout(), "environment from %s\n", d.EnvFile.Get())
}
return nil
}

Create a file for the web service, build the program, and complete --env-file:

Terminal window
touch web.env
go build
Bash
$ ./cloudctl deploy web --env-file <Tab>
$ ./cloudctl deploy web --env-file web.env

The glob tag filters the candidates to web.env, leaving out main.go and cloudctl.yaml. EnvFile has no help tag, so CONGA writes the description from the type and its tags.

Deploy with the file:

Terminal window
$ ./cloudctl deploy web -y --env-file web.env
deploying web (nginx:1.27) to eu-west-1 with 3 replicas
environment from web.env

Write a predictor that fetches the services

Section titled “Write a predictor that fetches the services”

The services change as teams add them, so a list in a tag would go out of date. Instead, we will write our own predictor, which fetches the services from an API when the shell completes a service name. CONGA uses the predictor of a type that implements conga.Predictable for every field of that type, so we give service names their own type, Service.

For this tutorial, the CONGA docs site plays the API, at https://docs.conga.sh/tutorials/api/v1. GET /services.json lists the services, each with a description:

{
"services": [
{ "name": "api", "description": "Public API" },
{ "name": "web", "description": "Website" },
{ "name": "worker", "description": "Background jobs" }
]
}

cloudctl needs an internet connection to reach it.

Create predict.go with a getJSON function that calls the API, and a services function that turns the answer into candidates. In main.go, add the Service type, use it for deploy’s argument, and give status an optional argument of the same type:

main.go
import (
"context"
"errors"
"fmt"
"time"
"github.com/conga-sh/conga"
"github.com/conga-sh/conga/decoder/yaml"
"github.com/conga-sh/conga/predict"
)
// ...
type Service string
Service implements conga.Predictable, so CONGA uses this predictor for every field of type Service.
func (s Service) Predict() predict.Predictor {
return predict.Callback(services).Timeout(2 * time.Second)
}
type DeployCmd struct {
Service conga.RequiredArg[Service] `help:"Service to deploy"`
// ...
}
// ...
type StatusCmd struct {
A container for an optional positional argument.
Service conga.OptionalArg[Service] `help:"Service to check"`
}
func (s *StatusCmd) Run(ctx context.Context, session *conga.Session) error {
root := session.Root[CLI]()
if s.Service.IsSet() {
fmt.Fprintf(session.Stdout(), "%s healthy in %s\n", s.Service.Get(), root.Region.Get())
return nil
}
fmt.Fprintf(session.Stdout(), "all services healthy in %s\n", root.Region.Get())
return nil
}

predict.Callback turns the services function into a predictor, and CONGA calls the function when the shell asks for a service. services fetches the current list, and predict.Items returns each name with its description.

CONGA gives a callback 250 milliseconds, and returns no candidates after that. A request across the internet can take longer, so Timeout gives services two seconds.

Build the program, and complete status’s argument:

Terminal window
go build
Bash
$ ./cloudctl status <Tab><Tab>
api (Public API) web (Website) worker (Background jobs)

Notice that neither field has a predictor tag, and deploy’s argument completes with the same three services.

status now reports on one service:

Terminal window
$ ./cloudctl status web
web healthy in eu-west-1

Complete a value from the rest of the command line

Section titled “Complete a value from the rest of the command line”

The images --image can offer depend on the service being deployed, so its predictor reads the service from the command line. The images also change with every push, so the predictor fetches them from the API. GET /services/{service}/images.json lists the images of one service. For web, it returns:

{
"images": ["nginx:1.26", "nginx:1.27"]
}

Image is a plain string, so it has no type to carry a predictor. Instead, we register the predictor on the builder under a name, and point the field at it with a predictor tag. Add the images function to predict.go, and the tag and the registration to main.go:

main.go
type DeployCmd struct {
Service conga.RequiredArg[Service] `help:"Service to deploy"`
Image conga.RequiredFlag[string] `help:"Container image to run" predictor:"images"`
// ...
}
// ...
func newApp() *conga.App[CLI] {
return conga.New[CLI]().
Name("cloudctl").
Description("Manage services in the cloud").
Version("0.1.0").
EnableCompletion().
EnvPrefix("CLOUDCTL").
RegisterDecoder(".yaml", yaml.Decode).
ConfigOptions(conga.ConfigPaths(".")).
Predictor("images", predict.Callback(images).Timeout(2*time.Second))
}

CONGA passes each callback a predict.Context with the command line typed so far. Arg reads the positional arguments, and FlagValue reads the flags. images reads the service with Arg(0) and asks the API for that service’s images.

Build the program, and complete --image for two services:

Terminal window
go build
Bash
$ ./cloudctl deploy web --image <Tab><Tab><Tab>
nginx:1.26 nginx:1.27
Bash
$ ./cloudctl deploy api --image <Tab><Tab><Tab>
api:1.4 api:1.5

The service has to come first. Before it is on the command line, Arg(0) is empty, so images returns no candidates and a hint set with Usage. A predictor’s own hint replaces the flag’s help text:

Bash
$ ./cloudctl deploy --image <Tab><Tab>

We now have a cloudctl that completes its commands, flags, and values. Each list of values came from a predictor. The regions came from the enum tag, the env files from the conga.File type, the services from Service, which implements conga.Predictable, and the images from the images function, registered by name.