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
- func Ask(question, fallback string) (string, error)
- func AskPassword(question string) (string, error)
- func BuildVersion() string
- func Choose(question string, options []string, fallback int) (string, error)
- func Confirm(question string, fallback bool) (bool, error)
- func Emit(cmd *cobra.Command, data any, meta ...map[string]any) error
- func ExitCode(err error) int
- func Interactive() bool
- func JSONRequested(cmd *cobra.Command) bool
- func Schema(cmd *cobra.Command) map[string]any
- func UsageArgs(validate cobra.PositionalArgs) cobra.PositionalArgs
- func Wait(message string, fn func() error) error
- type App
- type Console
- func (c *Console) Debug(message string)
- func (c *Console) Error(message string)
- func (c *Console) Heading(message string)
- func (c *Console) KeyValues(title string, pairs []Pair)
- func (c *Console) Print(message string)
- func (c *Console) Printf(format string, args ...any)
- func (c *Console) Sections(sections []Pair)
- func (c *Console) Success(message string)
- func (c *Console) Table(headers []string, rows [][]string)
- func (c *Console) Verbose(message string)
- func (c *Console) Warn(message string)
- type Envelope
- type Error
- type Option
- type Pair
- type Spinner
- type SpinnerOption
Constants ¶
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.
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 AskPassword ¶
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 ¶
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 Emit ¶
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 ¶
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 ¶
JSONRequested reports whether the caller asked for machine-readable output. Commands should consult it before printing anything decorative.
func Schema ¶
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.
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.
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 ¶
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) KeyValues ¶
KeyValues renders ordered fields, as a two-column table or, in compact mode, as `key: value` lines.
func (*Console) Table ¶
Table renders rows under the given headers. Pass a nil headers slice to omit the header row.
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 Usagef ¶
Usagef reports that the invocation itself was wrong: a bad flag, a missing argument, an unknown value. Exits 2.
type Option ¶
type Option func(*App)
Option configures an App.
func WithFang ¶
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
WithJSONFlag changes the machine-readable output flag. An empty shorthand disables the short form.
func WithOutput ¶
WithOutput redirects the application's stdout and stderr.
func WithVersion ¶
WithVersion sets the version string reported by --version.
type Pair ¶
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 ¶
Start begins animating and returns the spinner, so it can be chained with a deferred Stop.
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).
Source Files
¶
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. |