clikit

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

clikit-go

CI Go Reference Go Report Card

A thin layer over cobra for command-line tools that have two audiences: a person at a terminal, and a program parsing the output.

go get github.com/xlshcn/clikit-go

Why this exists

A CLI usually starts as something a person types. Then a deploy script calls it. Then CI branches on its exit code. Then an agent tries to discover what it can do. Each of those readers wants something different, and the usual result is a tool that serves the first one well and the rest by accident:

  • output mixes human decoration into the stream a script has to parse
  • every failure exits 1, so callers cannot tell "you typed it wrong" from "the upload failed" without matching on error strings
  • the only machine-readable description of the tool is its help text, so anything automating it ends up scraping prose
  • colour and spinners leak into CI logs as escape-sequence noise

Cobra solves the parsing problem completely, and fang makes cobra's help and errors look good. Neither addresses the list above, because neither is meant to: they are about defining and presenting commands, not about what a command returns.

clikit-go fills exactly that gap and nothing else:

Need What clikit adds
A script must parse the output --json mode: results, errors and help share one envelope
CI must branch on the outcome Typed errors with real exit codes — 2 bad invocation, 1 failed run, 130 interrupted
A program must discover the CLI --json --help returns a command schema, not prose
Humans still want good output Console, tables, spinners and prompts that degrade for pipes, CI and NO_COLOR

It stays deliberately thin. App.Root is a plain *cobra.Command: nothing is wrapped, nothing is hidden, every cobra and fang feature remains available, and you can stop using clikit for any part you would rather do yourself.

When to use it

Reach for clikit-go when your tool is called by something other than a person — CI, a Makefile, another service, an agent — and you want that path to be a designed interface rather than an accident.

When not to

If your CLI is only ever typed by humans, plain cobra plus fang is already the right answer and clikit adds nothing you need. If you want a completely different command model (struct tags, declarative specs), look at kong or urfave/cli instead — clikit is committed to cobra's.

Requirements

Go 1.25 or newer.


Usage

Quick start
package main

import (
	"context"

	"github.com/spf13/cobra"
	"github.com/xlshcn/clikit-go"
)

func main() {
	root := &cobra.Command{Use: "greet", Short: "A tiny clikit demonstration"}
	root.AddCommand(&cobra.Command{
		Use:   "hello NAME",
		Short: "Greet someone",
		RunE: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return clikit.Usagef("hello needs a name")
			}
			clikit.NewConsole(cmd.ErrOrStderr()).Success("Hello, " + args[0] + "!")
			return clikit.Emit(cmd, map[string]any{"name": args[0]})
		},
	})
	clikit.New(root, clikit.WithVersion(clikit.BuildVersion())).Run(context.Background())
}

The import path ends in clikit-go but the package is named clikit, so calls read clikit.New(...). No import alias is needed — Go takes the identifier from the package clause, not the path — and goimports resolves it for you.

That one program serves both audiences. For a person:

$ greet hello ada
✓ Hello, ada!

$ greet hello
ERROR  Hello needs a name.          # exit 2

For a program:

$ greet hello ada --json
{"ok":true,"command":["hello"],"data":{"name":"ada"},"meta":{}}

$ greet hello --json
{"ok":false,"command":["hello"],"error":{"kind":"usage_error","message":"hello needs a name"},"meta":{}}

$ greet hello --json --help
{"ok":true,"command":["hello"],"data":{"name":"hello","options":[...],"subcommands":[...]},"meta":{}}

A complete runnable version lives in examples/greet:

go run ./examples/greet hello ada grace --json
Building the application

clikit.New takes a cobra command tree you built the usual way, plus options. Run executes it and exits; Execute returns the exit code instead, which is what you want in tests.

app := clikit.New(root,
	clikit.WithVersion(clikit.BuildVersion()),  // --version
	clikit.WithFang(fang.WithoutManpage()),     // pass options through to fang
)
app.Run(ctx)
Option Effect
WithVersion(string) Sets the string --version reports. Empty disables the flag.
WithArgs(...string) Replaces os.Args[1:]. For tests and embedding.
WithOutput(out, err) Redirects the application's stdout and stderr.
WithJSONFlag(name, shorthand) Changes --json and -j; an empty shorthand disables the short form.
WithFang(...fang.Option) Passes through to fang: theming, signals, disabling the generated manpage or completions.

BuildVersion reports whatever Go embedded in the binary — a real module version for go install module@v1.2.3, or a pseudo-version carrying the commit, date and a +dirty marker for go build inside a checkout. Prefer a linker-supplied version when your build sets one.

Returning results

Emit is the only call a command needs to become machine-readable. In --json mode it writes the success envelope to stdout; otherwise it does nothing, on the assumption that the command already printed for humans. A RunE can return it directly so encoding errors are not discarded:

return clikit.Emit(cmd, results)

Attach anything a caller might want that is not the result itself as meta:

return clikit.Emit(cmd, results, map[string]any{"took": elapsed.String()})

Every response — success, failure, help — has one shape:

{"ok": true,  "command": ["prompts", "import"], "data": {...},  "meta": {}}
{"ok": false, "command": ["prompts", "import"], "error": {...}, "meta": {}}

All envelopes use stdout; stderr remains available for diagnostics. In JSON mode App buffers command stdout and publishes it only after validating that it contains exactly one success envelope for the executed command. Missing or repeated Emit calls, or raw text mixed into stdout, become a single execution_error envelope and exit 1.

command is the path with the program name stripped, so a consumer reads ["prompts","import"] rather than ["mycli","prompts","import"].

Guard decorative output with clikit.JSONRequested(cmd), or simply write it to cmd.ErrOrStderr() so stdout stays parseable either way:

if !clikit.JSONRequested(cmd) {
	console.Heading("Importing")
}
Failing usefully
return clikit.Usagef("--since must be before --until")     // exit 2
return clikit.Failf("upload failed").With("bundle", name)  // exit 1

Wrap Cobra's positional validators so they share the same usage semantics; required flags and flag-group validation are classified automatically:

Args: clikit.UsageArgs(cobra.ExactArgs(1)),

Usagef means "you typed it wrong", Failf means "it ran and could not finish" — the distinction shell scripts and CI actually branch on. With adds fields that survive into the JSON error object:

{"ok":false,"command":["upload"],"error":{"kind":"execution_error","message":"upload failed","bundle":"prod"},"meta":{}}
Situation Exit code
Success 0
Failf, or any other error 1
Usagef, or a flag parse failure 2
Cancelled context, or an aborted prompt 130

Flag errors are mapped to usage_error automatically, so mycli --nonsense exits 2 without you writing anything. Use Wrap to keep an underlying cause for errors.Is and errors.As, and ExitCode(err) if you need the mapping yourself.

Machine-readable help

mycli sub --json --help returns the command as data — name, usage, description, aliases, options (local and inherited, with types, defaults and whether they are required), arguments, subcommands and examples. That is what lets another program, or an agent, discover the CLI without scraping help text. clikit.Schema(cmd) produces the same map if you want it elsewhere.

Console output
console := clikit.NewConsole(cmd.ErrOrStderr())  // or clikit.NewStderrConsole()

console.Heading("Bundles")
console.Table([]string{"name", "version"}, rows)
console.KeyValues("Summary", []clikit.Pair{{Key: "imported", Value: "12"}})
console.Sections([]clikit.Pair{{Key: "Notes", Value: "…"}})

console.Success("done")
console.Warn("3 bundles unchanged")
console.Error("2 bundles failed")
console.Verbose("skipped 4 unchanged files")
console.Debug("resolved endpoint " + endpoint)
console.Printf("%d bundles", count)

Colour is handled by a colour-profile writer: it downsamples to what the terminal supports and strips styling entirely for pipes, CI logs and NO_COLOR. You never have to ask whether you are on a TTY. Set console.Compact = true for tab-separated, border-free output when a table's borders would be noise.

KeyValues and Sections take an ordered []Pair rather than a map, because Go map iteration order would shuffle your output between runs.

Spinners

For work of unknown duration, the one-line form:

err := clikit.Wait("importing prompts", func() error {
	return importAll(ctx)
})

Or hold one open and drive it:

spinner := clikit.NewSpinner("importing", clikit.SpinnerConsole(console)).Start()
spinner.Update("importing bundle 3/12")
err := importAll(ctx)
spinner.Stop(err)

Deferring the stop needs a closure, because defer spinner.Stop(err) would capture err as it is now — nil:

defer func() { spinner.Stop(err) }()

On a TTY it animates in place; anywhere else it prints one line and stops, so logs stay readable. With a SpinnerConsole it prints a success or error line on exit depending on the error passed to Stop. Stop is safe to call twice, so a defer after an explicit stop will not panic.

Prompts raised while a spinner is running pause it first — the detail that makes "spinner, then a confirmation question" work at all. spinner.Pause(fn) does the same for anything else that needs the cursor.

Prompts
ok, err := clikit.Confirm("Overwrite the live bundle?", false)
name, err := clikit.Ask("Bundle name", "default")
secret, err := clikit.AskPassword("API token")
env, err := clikit.Choose("Environment", []string{"dev", "prod"}, 0)

Built on huh. The last argument is the fallback used when stdin is not a terminal, so these calls are safe in CI: they return the fallback instead of hanging or failing. AskPassword is the exception — it errors, because silently continuing without a credential is worse than stopping. clikit.Interactive() reports whether prompting can succeed at all.

Testing your CLI

WithArgs and WithOutput make a command tree testable without touching the process:

var out, errOut bytes.Buffer
code := clikit.New(root,
	clikit.WithArgs("upload", "bundle.yaml", "--json"),
	clikit.WithOutput(&out, &errOut),
).Execute(context.Background())

if code != clikit.ExitOK {
	t.Fatalf("exit %d: %s", code, out.String())
}

Asserting on the JSON envelope is far more stable than asserting on help text or styled output.

API summary
Application New, App.Run, App.Execute, WithVersion, WithArgs, WithOutput, WithJSONFlag, WithFang, BuildVersion
Output Emit, JSONRequested, Envelope, Schema, JSONFlag
Errors Usagef, UsageArgs, Failf, Error.With, Error.Wrap, ExitCode, ExitOK, ExitFailure, ExitUsage, ExitAbort
Console NewConsole, NewStderrConsole, Console, Pair
Spinner Wait, NewSpinner, Spinner, SpinnerOutput, SpinnerConsole, SpinnerEnabled, SpinnerInterval
Prompts Confirm, Ask, AskPassword, Choose, Interactive

Full documentation: pkg.go.dev.


License

clikit-go is released under the MIT License. You may use, copy, modify, merge, publish, distribute, sublicense and sell it, in open-source or commercial work, provided the copyright notice and permission notice are included. It is provided as-is, without warranty.

Dependencies

Every dependency compiled into a binary is permissively licensed. There is no copyleft anywhere in the tree.

License Count Notable
MIT 28 fang, huh, lipgloss, bubbletea, colorprofile, uniseg
BSD-3-Clause 5 spf13/pflag, golang.org/x/{sync,sys,text}
Apache-2.0 2 spf13/cobra, inconshreveable/mousetrap (Windows only)

The two Apache-2.0 dependencies remain Apache-2.0; MIT covers only clikit-go's own code. Neither ships a NOTICE file, so the only obligation that travels with them is including their license text — and that falls on whoever distributes a compiled binary, not on clikit-go itself, since Go consumers resolve dependencies for themselves.

This is enforced, not just documented: TestDependencyLicensesArePermissive walks every module that compiles into a binary on Linux, macOS and Windows, classifies its license from the operative wording, and fails the build on anything copyleft or unrecognised.


Prior art

clikit-go is a Go port of an internal, unpublished Python clikit, at roughly half the size. Where the Go ecosystem already had a good answer it uses it rather than reimplementing: cobra for the command tree, fang for styled help, lipgloss for styling and tables, huh for prompts. What remains is the part none of them cover.

Not related to the PyPI package of the same name. clikit on PyPI is Sébastien Eustace's Python CLI toolkit — a dependency of Cleo 0.8, and through it of older Poetry releases, though current Cleo no longer uses it and its last release was in 2020. The names collide and the one-line descriptions read alike, but this project is not a port of it, shares no code or API with it, and is not affiliated with it. The -go suffix here is the usual Go answer to a name already in use elsewhere, which is also why the import path ends in clikit-go while the package is clikit.

Contributing

See CONTRIBUTING.md. Changes are tracked in CHANGELOG.md.

Documentation

Overview

Package clikit is a thin layer over github.com/spf13/cobra that adds the three things a production CLI needs and cobra deliberately leaves out:

  • a machine-readable output mode (--json) covering results, errors and help
  • typed errors with meaningful process exit codes
  • a console/spinner/prompt toolkit for the human-facing half

Everything else — the command tree, flag parsing, "did you mean", shell completions, man pages, styled help — is cobra and charm.land/fang/v2. clikit does not hide them: App.Root is a plain *cobra.Command, so any cobra or fang feature stays available.

A minimal application:

root := &cobra.Command{Use: "hello", Short: "greet someone"}
root.RunE = func(cmd *cobra.Command, args []string) error {
	clikit.NewConsole(cmd.OutOrStdout()).Success("hi there")
	return clikit.Emit(cmd, map[string]any{"greeted": true})
}
clikit.New(root).Run(context.Background())

Run as `hello` it prints a styled success line; run as `hello --json` it prints {"ok":true,"command":[],"data":{"greeted":true},"meta":{}} and nothing else.

Index

Constants

View Source
const (
	ExitOK      = 0
	ExitFailure = 1
	ExitUsage   = 2
	ExitAbort   = 130
)

Exit codes. They follow the common shell convention: 0 success, 1 runtime failure, 2 the caller typed something wrong, 130 interrupted.

View Source
const JSONFlag = "json"

JSONFlag is the default persistent flag name App installs to switch a command tree into machine-readable mode.

Variables

This section is empty.

Functions

func Ask

func Ask(question, fallback string) (string, error)

Ask asks for a line of text. Empty input, or no TTY, yields fallback.

func AskPassword

func AskPassword(question string) (string, error)

AskPassword asks for a secret without echoing it. It has no fallback: a missing TTY is an error, because silently proceeding without a credential is worse than stopping.

func BuildVersion

func BuildVersion() string

BuildVersion reports the version Go embedded in the binary: the module version for `go install module@v1.2.3`, or the pseudo-version Go derives from the repository for `go build` inside a checkout (which already carries the commit, the date and a +dirty marker). Source without VCS information — a tarball, or -buildvcs=false — yields "unknown".

Prefer a linker-supplied version when the build sets one:

var version string // -ldflags "-X main.version=$(git describe --tags)"

if version == "" {
	version = clikit.BuildVersion()
}
clikit.New(root, clikit.WithVersion(version)).Run(ctx)

func Choose

func Choose(question string, options []string, fallback int) (string, error)

Choose offers a single choice from options. fallback is the index selected when there is no TTY; pass a negative index to make that an error instead.

func Confirm

func Confirm(question string, fallback bool) (bool, error)

Confirm asks a yes/no question. Without a TTY it returns fallback.

func Emit

func Emit(cmd *cobra.Command, data any, meta ...map[string]any) error

Emit publishes a command's result. In --json mode it writes the success envelope to the command's stdout; otherwise it does nothing, on the assumption that the command already printed for humans.

A RunE can end with `return clikit.Emit(cmd, data)` so encoding errors are not discarded.

func ExitCode

func ExitCode(err error) int

ExitCode maps an error to a process exit code: nil is 0, a *Error uses its own Code, cancellation and aborted prompts are 130, anything else is 1.

func Interactive

func Interactive() bool

Interactive reports whether stdin is a terminal, i.e. whether prompting can succeed at all.

func JSONRequested

func JSONRequested(cmd *cobra.Command) bool

JSONRequested reports whether the caller asked for machine-readable output. Commands should consult it before printing anything decorative.

func Schema

func Schema(cmd *cobra.Command) map[string]any

Schema describes a command as plain data: what it is, what it accepts and what lives under it. `mycli sub --json --help` returns exactly this, which is what lets another program (or an agent) drive the CLI without scraping help text.

func UsageArgs added in v0.1.2

func UsageArgs(validate cobra.PositionalArgs) cobra.PositionalArgs

UsageArgs adapts a cobra positional-argument validator so validation failures use the same usage_error and exit code 2 as flag parse failures.

func Wait

func Wait(message string, fn func() error) error

Wait runs fn behind a spinner on stderr and reports the outcome. It is the one-line form:

err := clikit.Wait("importing prompts", func() error { return importAll(ctx) })

Types

type App

type App struct {
	// Root is the command tree. Configure it with cobra directly.
	Root *cobra.Command
	// Version is reported by --version. Empty disables the flag.
	Version string
	// Args overrides os.Args[1:]; useful in tests.
	Args []string
	// Out and Err default to os.Stdout and os.Stderr.
	Out io.Writer
	Err io.Writer
	// contains filtered or unexported fields
}

App runs a cobra command tree. It is a thin shell: Root stays a plain *cobra.Command that you build with ordinary cobra calls, and App only owns the process boundary — argv, the --json switch, and the exit code.

func New

func New(root *cobra.Command, options ...Option) *App

New builds an App around an existing cobra command tree.

func (*App) Execute

func (a *App) Execute(ctx context.Context) int

Execute runs the application and returns the exit code instead of exiting, so it can be called from tests.

func (*App) Run

func (a *App) Run(ctx context.Context)

Run executes the application and terminates the process with its exit code.

type Console

type Console struct {
	// Compact drops table borders and renders key/value pairs as plain lines.
	Compact bool
	// contains filtered or unexported fields
}

Console writes human-facing output. Colour is handled by the underlying colour-profile writer, which downsamples to whatever the terminal supports and strips styling entirely for pipes, CI logs and NO_COLOR — so callers never have to ask "is this a TTY".

func NewConsole

func NewConsole(w io.Writer) *Console

NewConsole writes to w. Pass cmd.ErrOrStderr() to keep decorative output off stdout, which matters when stdout is being piped into another program.

func NewStderrConsole

func NewStderrConsole() *Console

NewStderrConsole is the common case: humans read stderr, machines read stdout.

func (*Console) Debug

func (c *Console) Debug(message string)

Debug writes diagnostic detail.

func (*Console) Error

func (c *Console) Error(message string)

Error marks a failure.

func (*Console) Heading

func (c *Console) Heading(message string)

Heading writes a section title.

func (*Console) KeyValues

func (c *Console) KeyValues(title string, pairs []Pair)

KeyValues renders ordered fields, as a two-column table or, in compact mode, as `key: value` lines.

func (*Console) Print

func (c *Console) Print(message string)

Print writes a line verbatim.

func (*Console) Printf

func (c *Console) Printf(format string, args ...any)

Printf writes a formatted line verbatim.

func (*Console) Sections

func (c *Console) Sections(sections []Pair)

Sections writes titled blocks separated by blank lines.

func (*Console) Success

func (c *Console) Success(message string)

Success marks a completed step.

func (*Console) Table

func (c *Console) Table(headers []string, rows [][]string)

Table renders rows under the given headers. Pass a nil headers slice to omit the header row.

func (*Console) Verbose

func (c *Console) Verbose(message string)

Verbose writes de-emphasised detail.

func (*Console) Warn

func (c *Console) Warn(message string)

Warn marks something the user should notice but that did not stop the run.

type Envelope

type Envelope struct {
	OK      bool           `json:"ok"`
	Command []string       `json:"command"`
	Data    any            `json:"data,omitempty"`
	Error   map[string]any `json:"error,omitempty"`
	Meta    map[string]any `json:"meta"`
}

Envelope is the single shape every --json response takes, success or failure, so callers can branch on one field.

type Error

type Error struct {
	Kind    string         // stable machine-readable category, e.g. "usage_error"
	Message string         // human-readable summary
	Code    int            // process exit code
	Details map[string]any // extra fields merged into the JSON error object
	Cause   error
}

Error is a command failure carrying an exit code and structured details that survive into the --json error envelope.

func Failf

func Failf(format string, args ...any) *Error

Failf reports that the command ran but could not complete. Exits 1.

func Usagef

func Usagef(format string, args ...any) *Error

Usagef reports that the invocation itself was wrong: a bad flag, a missing argument, an unknown value. Exits 2.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

func (*Error) With

func (e *Error) With(key string, value any) *Error

With attaches one detail field and returns the error, for chaining.

func (*Error) Wrap

func (e *Error) Wrap(cause error) *Error

Wrap records the underlying cause, keeping kind and exit code.

type Option

type Option func(*App)

Option configures an App.

func WithArgs

func WithArgs(args ...string) Option

WithArgs replaces os.Args[1:], for tests and embedded use.

func WithFang

func WithFang(options ...fang.Option) Option

WithFang passes options through to fang, which renders help and errors in human mode. See fang.Option for theming, signal handling and disabling the generated manpage or completions.

func WithJSONFlag added in v0.1.2

func WithJSONFlag(name, shorthand string) Option

WithJSONFlag changes the machine-readable output flag. An empty shorthand disables the short form.

func WithOutput

func WithOutput(out, err io.Writer) Option

WithOutput redirects the application's stdout and stderr.

func WithVersion

func WithVersion(version string) Option

WithVersion sets the version string reported by --version.

type Pair

type Pair struct {
	Key   string
	Value string
}

Pair is one ordered key/value row. A slice is used rather than a map so the caller controls the order.

type Spinner

type Spinner struct {
	// contains filtered or unexported fields
}

Spinner is a waiting indicator for work of unknown duration. On a TTY it animates in place; anywhere else it degrades to a single line so logs stay readable.

func NewSpinner

func NewSpinner(message string, options ...SpinnerOption) *Spinner

NewSpinner builds a spinner. It does not draw anything until Start.

func (*Spinner) Pause

func (s *Spinner) Pause(fn func())

Pause suspends the draw loop for the duration of fn, so an interactive prompt is not overwritten by the next frame. Safe to call on a disabled or stopped spinner, where it simply runs fn.

func (*Spinner) Start

func (s *Spinner) Start() *Spinner

Start begins animating and returns the spinner, so it can be chained with a deferred Stop.

func (*Spinner) Stop

func (s *Spinner) Stop(err error)

Stop ends the animation. A non-nil err prints an error line instead of a success line when the spinner has a console.

func (*Spinner) Update

func (s *Spinner) Update(message string)

Update changes the message while the spinner is running.

type SpinnerOption

type SpinnerOption func(*Spinner)

SpinnerOption configures a Spinner.

func SpinnerConsole

func SpinnerConsole(c *Console) SpinnerOption

SpinnerConsole makes the spinner print a final success or error line when it stops. Without one, stopping just clears the animation.

func SpinnerEnabled

func SpinnerEnabled(enabled bool) SpinnerOption

SpinnerEnabled forces animation on or off, overriding TTY detection.

func SpinnerInterval

func SpinnerInterval(interval time.Duration) SpinnerOption

SpinnerInterval sets the frame duration.

func SpinnerOutput

func SpinnerOutput(w io.Writer) SpinnerOption

SpinnerOutput sets the stream the animation is drawn on (default os.Stderr).

Directories

Path Synopsis
examples
greet command
Command greet is a runnable tour of clikit: a command tree with a subcommand, a typed error, human output and the matching --json envelope.
Command greet is a runnable tour of clikit: a command tree with a subcommand, a typed error, human output and the matching --json envelope.

Jump to

Keyboard shortcuts

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