Skip to content

Shell Completion Code Generation

Pre-release
Pre-release

Choose a tag to compare

@tanner0101 tanner0101 released this 26 Feb 21:21
ba1bd2a

Implements shell completion script generation for bash and zsh, and adds a flag to Commands to use it right out of the box:

// main.swift

// ...
var commands = Commands(enableAutocomplete: true)
// ...
let group = commands.group(help: "My command-line application")
try console.run(group, using: input)
// ...

The CommandGroup created will have an autocomplete command (a GenerateAutocompleteCommand) that can be used to generate shell completion scripts for the entire command hierarchy and its command-line arguments:

Usage: <executable> autocomplete [--shell,-s] [--output,-o] [--quiet,-q]

Generate shell completion scripts for the executable

Options:
   shell Generate a completion script for SHELL [ bash | zsh ].
         Defaults to the "SHELL" environment variable if possible.
  output Write the completion script to the file at OUTPUT, overwriting its contents.
         Defaults to printing to stdout.

Flags:
   quiet Suppress any informational console output

Option and Argument signature values can optionally provide a CompletionAction. For example, in GenerateAutocompleteCommand.Signature:

@Option(
    name: "shell", 
    // ...
    completion: .values(of: Shell.self)
)
var shell: Shell?

@Option(
    name: "output",
    // ...
    completion: .files()
)
var output: String?

CompletionAction currently provides static factory methods for completing files (including directories), directories (excluding regular files), and a list of string values, as well as a convenience method for creating a list of values from a CaseIterable and LosslessStringConvertible type.