cli-kit

module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT

README

cli-kit

Go Reference Test

cli-kit is the plumbing for Go command-line tools: deciding whether a stream is a terminal and may be painted, interactive pickers and prompts, tables and structured output, live status lines and progress bars, credentials, self-updates, shell completion and version information.

Every package keeps output plain when it does not go to a terminal, so pipes, files and tests see no escape sequences. Packages take their settings as options; the only process-wide settings are the color mode and the theme.

Installation

go get github.com/mittwald/cli-kit

cli-kit supports Go 1.27 and newer on Linux, macOS and Windows. It is one module: import only the packages you need, and only their dependencies are compiled into your binary.

Packages

Package What it does
term Terminal detection and size, the --color mode with NO_COLOR and TERM=dumb, visible text width, truncation, padding, word wrapping, OSC 8 hyperlinks and when to write them, 24-bit color detection, and untrusted output made safe to show
theme SGR styles, styles parsed from user settings ("fg=white:bg=#aa0000:bold"), regular expression matches painted into painted text, the color roles the other packages paint with, unified diffs painted the way git paints them, painted JSON, and a stable color per name
pick Interactive list selection with filtering, views and ranges, per-row and in-cell painting, an adjustable look, switches, and line-edited text and secret input
live Blocks of lines redrawn in place, detail/result output separation, and cursor and terminal restore on exit, panic and signals
progress A gradient progress bar with a stall countdown that steps aside for log lines
table Tables in plain, framed and Markdown styles, and CSV/TSV records, with spreadsheet formulas escaped on request
format An --output flag value, JSON/YAML writers driven by the same struct tags, and compact ages ("3h", "5mo")
ics An RFC 5545 iCalendar writer
secret Credentials from flags, files, environment, stdin, the OS keyring or a hidden prompt, and redaction of known and recognizable secrets
selfupdate Self-updates from GitHub Releases or a GitLab package registry, checked against the release's checksums file
cobrax Cobra helpers: --color and other auto/always/never flags, enum flags, deprecated flag spellings as hidden aliases, hardened, cached and prefix-filtered shell completion with an optional --install or a script written to a path, version command
fsx Files replaced atomically with a chosen mode, refusing a symbolic link in their place
browser A web page opened in the user's browser, http and https URLs only, without a shell
logx A log/slog handler writing plain, redacted lines for --verbose
clipboard Text copied to the system clipboard through the platform's helper commands, without cgo
buildinfo Version, commit and date from -ldflags or the Go build information

Examples

Color and terminal
cobrax.AddColorFlag(root, "when to use color: auto, always or never")
links := cobrax.AddModeFlag(root, "links", "when to make links: auto, always or never")
cobrax.AddFlagAlias(root, root.PersistentFlags(), // the old spelling, hidden, with a note
	cobrax.FlagAlias{Old: "no-links", New: "links", Value: "never"})

if term.Colored(os.Stdout) {
	fmt.Println(theme.Active().Success.Paint("done"))
}
width := term.Columns(os.Stdout, 80)
fmt.Println(term.Truncate(longLine, width))

th := theme.Active().For(os.Stdout) // theme.Plain where stdout takes no color
fmt.Print(th.PaintDiff(term.Plain(diff))) // a diff from elsewhere: made plain first
fmt.Println(term.Sanitize(jobLog))        // its colors kept, every other escape gone
fmt.Println(term.PlainLine(name))         // one line, no escape sequence, no color
fmt.Println(th.PaintJSON(string(data)))   // JSON from encoding/json: keys, strings, numbers, literals
author := theme.Hashed(name, nil)         // the same color for the same name, on every run
if term.ShouldLink(links.Mode(), os.Stdout) {
	fmt.Println(term.Hyperlink(url, term.PlainLine(name)))
}
style, ok := theme.ParseStyle(os.Getenv("EXAMPLE_COLOR_ERROR")) // "red:bold", "245", "bg=#aa0000"
fmt.Println(style.For(os.Stdout).PaintMatches(line, errorPattern)) // the line keeps its own colors
Tables and structured output
var out format.Format
root.PersistentFlags().VarP(format.NewValue(&out, format.Text, nil), "output", "o",
	"output format: "+format.Default.String())

if out.IsStructured() {
	return format.Write(os.Stdout, out, items) // json tags drive JSON and YAML alike
}
t := table.New(os.Stdout, []string{"Name", "Status"},
	table.UppercaseHeaders(), table.WithStyle(table.Rounded), table.WithFormat(out))
for _, item := range items {
	t.Append(item.Name, item.Status)
}
return t.Render()
Picking from a list
i, err := pick.Select(os.Stdin, os.Stderr, pick.Options{
	Title:   "Deploy which version of %s?",
	Subject: "api",
	Items: []pick.Item{
		{Cells: []string{"1.4.2", "latest"}, Action: "deploy"},
		{Cells: []string{"1.4.1", "current"}, Muted: true},
	},
})
switch {
case errors.Is(err, pick.ErrNotATerminal):
	// Not interactive: ask for a --version flag instead.
case errors.Is(err, pick.ErrAborted):
	return nil // Esc or Ctrl-C
}

token, err := pick.Input(os.Stdin, os.Stderr, pick.InputOptions{Prompt: "Token: ", Secret: true})

Type to filter, arrows and paging keys to move, Enter to choose. Lists can offer views (Tab), ranges, typed answers and per-column truncation; see the package documentation. Text handed to a prompt is shown as plain text, so a name from elsewhere cannot carry an escape sequence to the terminal, and the terminal is restored when the prompt ends, also by a signal.

Live output and progress
defer live.InstallSignalRestore()() // never leave the cursor hidden

bar := progress.New(os.Stderr, progress.Options{})
logger := log.New(bar.Writer(os.Stderr), "", 0) // log lines step around the bar
bar.Start(len(steps), 30*time.Second)
for _, step := range steps {
	bar.Advance(step.Name)
	done := bar.BeginWait() // shows a countdown if the step stalls
	step.Run(logger)
	done()
}
bar.Finish(true)
bar.Clear()

The signal handler shows hidden cursors again before the process ends, and runs whatever live.OnRestore registered, which is how the prompts of pick and secret put the terminal back into its mode. The bar follows the width of the terminal as it changes, holds a log line back until its newline arrives, and uses 24-bit color only where COLORTERM announces it.

Credentials
files, _ := secret.NewFileStore("example")
r := &secret.Resolver{
	Name:    "API token",
	Account: "default",
	Env:     "EXAMPLE_TOKEN",
	Store:   secret.Fallback(secret.Keyring{Service: "example"}, files),
}
token, from, err := r.Resolve() // file flag, env, piped stdin, store, then a hidden prompt
// When the server accepts the token: r.Save(token).
// When it rejects it: r.Forget(from), then resolve again.

A Resolver reads a secret from stdin whenever stdin is not a terminal. In a command that may run inside a loop reading stdin, in a Git hook or over ssh without a terminal, set StdinBusy so that stdin is left alone.

Self-update
u := &selfupdate.Updater{
	Source:  &selfupdate.GitHub{Owner: "example", Repo: "tool"},
	Current: buildinfo.Get().Version,
	Asset:   selfupdate.VersionedAssets("tool"),
}
res, err := u.Update(ctx, false) // checks the archive against checksums.txt; refuses package-managed installs

The checksum detects a corrupted or altered download. It does not protect against someone who can write the release's files, because the checksums file is published in the same place. The archive must hold an executable for the platform, and a credential is only sent to an https API address.

Files, browser and logs
err := fsx.WriteFile(configPath, data, 0o644) // atomic; secret.WriteFile for a token cache

fmt.Fprintln(os.Stderr, "Opening", term.PlainLine(loginURL)) // say it, in case nothing opens
_ = browser.Open(ctx, loginURL)                               // http and https only

level := slog.LevelInfo
if verbose {
	level = slog.LevelDebug
}
logger := slog.New(logx.NewLineHandler(os.Stderr, &logx.Options{Level: level}))
logger.Debug("sent a request", "path", path, "status", status) // plain, credentials redacted
Shell completion and version
cobrax.SetVersion(root, buildinfo.Get())
root.AddCommand(cobrax.NewVersionCommand(buildinfo.Get()))
cobrax.NoFileCompletions(root)
cobrax.AddCompletionInstall(cobrax.HardenCompletion(root)) // "completion bash --install"
cobrax.WriteCompletionScript(root, "zsh", legacyPath)      // where an older version kept it
root.SetArgs(cobrax.JoinSpacedBoolValues(root, os.Args[1:]))

Stamp the version at build time, for example in .goreleaser.yaml:

ldflags:
  - -s -w
  - -X github.com/mittwald/cli-kit/buildinfo.Version={{ .Version }}
  - -X github.com/mittwald/cli-kit/buildinfo.Commit={{ .FullCommit }}
  - -X github.com/mittwald/cli-kit/buildinfo.Date={{ .Date }}

Versioning

cli-kit follows semantic versioning. While it is v0.x, minor releases may change APIs; such changes are listed first in the release notes.

Contributing

Contributions are welcome. See CONTRIBUTING.md for how to build, test and submit changes, and SECURITY.md for reporting vulnerabilities.

License

Copyright (c) 2026 Mittwald CM Service GmbH & Co. KG and contributors

This project is licensed under the MIT License; see the LICENSE file for details.

Directories

Path Synopsis
Package browser opens a web page in the user's browser, such as the sign-in page of an OAuth flow.
Package browser opens a web page in the user's browser, such as the sign-in page of an OAuth flow.
Package buildinfo reports which build of a command is running.
Package buildinfo reports which build of a command is running.
Package clipboard copies text to the system clipboard.
Package clipboard copies text to the system clipboard.
Package cobrax collects the cobra and pflag wiring command-line tools keep rewriting: a --color[=WHEN] flag and other flags that take auto, always or never (AddModeFlag), enumerated flags that complete their values, older spellings of flags kept as hidden switches (AddFlagAlias), file completion switched off where no file is expected, a hardened completion command that can install its scripts for the current user or write them to a path of the tool's choice, completion candidates cached on disk, filtered by prefix (CompletePrefix) and kept free of control characters (SafeCompletions), the "--flag false" spelling of boolean flags, and version output.
Package cobrax collects the cobra and pflag wiring command-line tools keep rewriting: a --color[=WHEN] flag and other flags that take auto, always or never (AddModeFlag), enumerated flags that complete their values, older spellings of flags kept as hidden switches (AddFlagAlias), file completion switched off where no file is expected, a hardened completion command that can install its scripts for the current user or write them to a path of the tool's choice, completion candidates cached on disk, filtered by prefix (CompletePrefix) and kept free of control characters (SafeCompletions), the "--flag false" spelling of boolean flags, and version output.
Package format names the output formats a command-line tool offers through an --output flag and writes the structured ones.
Package format names the output formats a command-line tool offers through an --output flag and writes the structured ones.
Package fsx holds file system helpers the standard library leaves out.
Package fsx holds file system helpers the standard library leaves out.
Package ics writes iCalendar (RFC 5545) files: a VCALENDAR holding VEVENT components, as calendar clients import or subscribe to them.
Package ics writes iCalendar (RFC 5545) files: a VCALENDAR holding VEVENT components, as calendar clients import or subscribe to them.
internal
atomicfile
Package atomicfile replaces a file atomically.
Package atomicfile replaces a file atomically.
Package live draws terminal output that changes in place, and keeps the terminal usable when the program drawing it stops unexpectedly.
Package live draws terminal output that changes in place, and keeps the terminal usable when the program drawing it stops unexpectedly.
Package logx holds log/slog handlers for command-line tools.
Package logx holds log/slog handlers for command-line tools.
Package pick draws keyboard-driven prompts on a terminal: the interactive counterpart of a flag the user did not pass.
Package pick draws keyboard-driven prompts on a terminal: the interactive counterpart of a flag the user did not pass.
Package progress draws a single-line progress bar on a terminal.
Package progress draws a single-line progress bar on a terminal.
Package secret finds the passwords and tokens a command-line tool needs, and keeps them between runs without writing them anywhere in plain sight.
Package secret finds the passwords and tokens a command-line tool needs, and keeps them between runs without writing them anywhere in plain sight.
Package selfupdate replaces a running command-line tool with its latest release.
Package selfupdate replaces a running command-line tool with its latest release.
Package table renders rows of cells as an aligned text table, a framed table, a markdown pipe table, or CSV/TSV records.
Package table renders rows of cells as an aligned text table, a framed table, a markdown pipe table, or CSV/TSV records.
Package term answers the questions every command-line tool asks about its terminal: whether a stream is a terminal at all, how large it is, whether it may be painted in color, and how wide a piece of text is once it is drawn there.
Package term answers the questions every command-line tool asks about its terminal: whether a stream is a terminal at all, how large it is, whether it may be painted in color, and how wide a piece of text is once it is drawn there.
Package theme holds the colors the packages of this module paint with.
Package theme holds the colors the packages of this module paint with.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL