Documentation
¶
Overview ¶
Package cli is the Go representation of pleme-io's CLI framework — the Go counterpart to the Rust `clap` / `caixa-clap` model. It gives Go tools the same shape everywhere: a named App with a version and description, a tree of subcommands, per-flag validators run after parsing, and a small multi-auth resolver — all on the standard library's flag package, with zero external dependencies.
The mandate, like the Rust crates: no hand-rolled argv switch statements, no bespoke flag parsing per tool. Build an App, Add commands, hand it argv, and every binary in the fleet dispatches, validates, and prints usage the same way.
app := cli.NewApp("clint",
cli.WithVersion("5.0.22"),
cli.WithDescription("Akeyless CLI"),
)
app.Add(cli.Command{
Name: "list-secrets",
Summary: "List secrets under a path",
Flags: func(fs *flag.FlagSet) {
fs.String("path", "/", "secrets path")
},
Run: func(ctx context.Context, args []string, fs *flag.FlagSet) error {
// fs is parsed and validated here.
return nil
},
})
if err := app.Run(context.Background(), os.Args); err != nil {
log.Fatal(err)
}
Subcommands may nest one level via Command.Sub; the router dispatches on the first non-flag token and prints usage for an unknown command or --help/-h.
Borealis elevation (§2.2) ¶
This package is the fleet CLI *authoring* surface; under the Borealis Theory it carries the typed grammar (single source of truth) while presentation is owned by borealis. The elevated surface adds, additively over the original:
- Typed validation-as-data: Flag is a generic, self-describing flag whose name/default/env/OneOf/Validate travel together, so help STRUCTURE (types, enum sets, defaults, env names) is DERIVED from the typed data, never hand-formatted (Law 4). Read a parsed, validated, typed value with Flag.Get.
- The fleet-standard persistent flag set (FleetFlags): --auth (its value set auto-wired from AuthResolver.Kinds), --profile, --gateway-url, --output, --no-color (NO_COLOR), --verbose — defined once, inherited everywhere.
- A raised Command type: Aliases, Hidden, Category, Deprecated (derived into help) plus authored prose (Long, Examples — typed data, rendered).
The dep-bearing integrations live in leaf sub-packages so the core stays zero-dependency (Law 6/8): cli-go/cfg wires the canonical shikumi loader to a primitive's FromConfig (§3.5), and cli-go/exit maps the cli sentinels into errors-go exit codes (errors-go is the sole exit owner, §3.5). The borealis.Execute entrypoint and borealis-rendered styled help/errors are DEFERRED while borealis.Execute/Render is in-flight — the root Command defined here is what borealis.Execute will consume; this package does not (and must not) redeclare Execute.
Index ¶
- Variables
- func RegisterValidator(fs *flag.FlagSet, name string, v Validator)
- type App
- func (a *App) Add(cmds ...Command) *App
- func (a *App) Commands() []Command
- func (a *App) Description() string
- func (a *App) ExecCommand(ctx context.Context, cmd Command, path string, args []string) error
- func (a *App) Name() string
- func (a *App) Output() io.Writer
- func (a *App) Run(ctx context.Context, argv []string) error
- func (a *App) Version() string
- type AppOption
- type AuthKind
- type AuthMethod
- type AuthResolver
- type AuthResult
- type Command
- type Flag
- func (f *Flag[T]) Allowed() []T
- func (f *Flag[T]) Bind(fs *flag.FlagSet)
- func (f *Flag[T]) Default() T
- func (f *Flag[T]) Env(name string) *Flag[T]
- func (f *Flag[T]) EnvName() string
- func (f *Flag[T]) Get() T
- func (f *Flag[T]) Name() string
- func (f *Flag[T]) OneOf(allowed ...T) *Flag[T]
- func (f *Flag[T]) Validate(check func(T) error) *Flag[T]
- type FleetFlags
- type FleetOption
- type OutputFormat
- type ValidationError
- type Validator
Constants ¶
This section is empty.
Variables ¶
var ErrHelp = errors.New("cli: help requested")
ErrHelp is returned by App.Run (and command routing) when help output was requested via --help/-h and printed. Callers typically treat it as a clean, non-error exit:
if err := app.Run(ctx, os.Args); err != nil && !errors.Is(err, cli.ErrHelp) {
log.Fatal(err)
}
var ErrNoCommand = errors.New("cli: no command given")
ErrNoCommand is returned by App.Run when argv carries no subcommand at all (only the program name). The router prints top-level usage before returning it.
Functions ¶
func RegisterValidator ¶
RegisterValidator attaches a validator to a flag, to run after parsing and before the command's Run. Call it from within a command's Flags callback, after registering the flag itself:
Flags: func(fs *flag.FlagSet) {
fs.Int("port", 8080, "listen port")
cli.RegisterValidator(fs, "port", cli.Range(1, 65535))
},
A flag may carry multiple validators; they run in registration order and the first failure wins. Registering a validator outside a Flags callback is a no-op (there is no active command invocation to attach to).
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is a CLI application: a named root with a version, a description, and a registered set of top-level [Command]s. Construct one with NewApp and drive it with App.Run.
func (*App) Add ¶
Add registers one or more top-level commands. It returns the App for chaining. Commands are dispatched in registration order; later registrations of the same Name shadow earlier ones.
func (*App) Commands ¶
Commands returns the registered top-level commands in registration order. The cobra-lowering leaf (cli-go/cobrax) reads them to build the cobra command tree; the slice is the App's own backing store (do not mutate).
func (*App) Description ¶
Description returns the App's one-line description (empty if unset).
func (*App) ExecCommand ¶
ExecCommand runs a single leaf Command against args (parse + validate + Run), bypassing the stdlib router's argv-splitting. path is the human-readable command path used in usage and parse errors (e.g. "clint auth login"). args are the command's own arguments (flags + positionals), exactly as the stdlib router would hand them after stripping the command tokens.
It exists so the cobra-lowering leaf (cli-go/cobrax) can reuse the *same* typed-Flag parse/validate/Run engine the stdlib router uses, instead of re-implementing it (PRIME DIRECTIVE: duplication is a bug). The command must be runnable (Run != nil); a group-only command returns a not-runnable error, matching the router.
func (*App) Run ¶
Run parses argv and dispatches to the selected command. argv is the full process argument vector including the program name at index 0 (pass os.Args directly).
Behaviour:
- argv with no command (len <= 1) prints top-level usage and returns ErrNoCommand;
- "--help"/"-h"/"help" prints top-level usage and returns ErrHelp;
- "--version"/"version" prints the version and returns nil;
- an unknown command prints top-level usage and returns an "unknown command" error;
- a known command parses its flags, runs validators, and executes; a command's own "--help"/"-h" prints that command's usage and returns ErrHelp.
type AppOption ¶
type AppOption func(*App)
AppOption configures an App at construction time (the functional-options pattern). See WithVersion and WithDescription.
func WithDescription ¶
WithDescription sets the App's one-line description, shown in top-level usage.
func WithOutput ¶
WithOutput redirects the App's usage and version output. The default is os.Stderr, matching the flag package and standard CLI convention.
func WithVersion ¶
WithVersion sets the App's version string, surfaced by the built-in "version" command and the --version flag.
type AuthKind ¶
type AuthKind string
AuthKind names a supported authentication method. It mirrors the multi-auth surface of the Akeyless CLI (api-key, token, AWS IAM, Azure AD, GCP, K8s, …); the set is open — register whatever kinds a tool needs.
type AuthMethod ¶
type AuthMethod struct {
// Kind is the method's identity (e.g. AuthAPIKey).
Kind AuthKind
// EnvVar, if set and present in the environment, marks this method as
// available and supplies its primary credential as the env var's value.
EnvVar string
// Resolve gathers credential material for this method. It receives the
// value already discovered from EnvVar (empty if none) and returns the
// final credential map. If nil, a single-entry map keyed by the env value
// (when present) is used.
Resolve func(envValue string) (map[string]string, error)
}
AuthMethod describes one authentication method: how to recognise that it has been selected (a flag value and/or an env var) and how to gather its credential material once selected.
The abstraction is deliberately transport-free — it resolves *which* method and *what* inputs to use, not how to talk to any server. A tool wires the resolved AuthResult into its own client.
type AuthResolver ¶
type AuthResolver struct {
// contains filtered or unexported fields
}
AuthResolver selects exactly one AuthMethod from a registered set, using an explicit selector (typically the value of an --auth flag) with a fallback to whichever method's env var is present.
r := cli.NewAuthResolver().
Register(cli.AuthMethod{Kind: cli.AuthAPIKey, EnvVar: "AKEYLESS_ACCESS_KEY"}).
Register(cli.AuthMethod{Kind: cli.AuthToken, EnvVar: "AKEYLESS_TOKEN"})
res, err := r.Resolve(string(authFlag)) // authFlag may be ""
func NewAuthResolver ¶
func NewAuthResolver() *AuthResolver
NewAuthResolver creates an empty resolver.
func (*AuthResolver) Kinds ¶
func (r *AuthResolver) Kinds() []AuthKind
Kinds returns the registered kinds, sorted, for usage and error messages.
func (*AuthResolver) Register ¶
func (r *AuthResolver) Register(m ...AuthMethod) *AuthResolver
Register adds an auth method, returning the resolver for chaining. A later registration of the same Kind shadows an earlier one.
func (*AuthResolver) Resolve ¶
func (r *AuthResolver) Resolve(selector string) (AuthResult, error)
Resolve selects and materialises an auth method.
Selection order:
- if selector is non-empty, it must name a registered kind (else error);
- otherwise, the first registered method whose EnvVar is present in the environment is chosen;
- if nothing is selected and no env var matches, an error listing the available kinds is returned.
type AuthResult ¶
AuthResult is the outcome of AuthResolver.Resolve: the selected method's kind and its gathered credential material.
type Command ¶
type Command struct {
// Name is the token used to select this command on the command line. It
// must be non-empty and is matched case-sensitively.
Name string
// Summary is the one-line description shown in the parent's usage listing.
Summary string
// Flags, if set, registers flags onto the per-invocation FlagSet. Register
// validators here too via [RegisterValidator], or — preferred — bind typed
// [Flag] handles via [Flag.Bind], which carries validation-as-data and
// auto-documents OneOf/enum, defaults, and env names.
Flags func(fs *flag.FlagSet)
// Run executes the command. args holds the positional (non-flag) arguments
// left after parsing; fs is the parsed, validated flag set. Run is called
// only after parsing and validation succeed.
Run func(ctx context.Context, args []string, fs *flag.FlagSet) error
// Sub holds optional child commands, enabling one (or more) levels of
// nesting. When set, the router dispatches the next argv token to a child;
// if no child matches and Run is set, Run handles it, otherwise usage is
// printed.
Sub []Command
// Aliases are alternate selection tokens for this command, matched the same
// way as Name. They are listed in the command's usage so help stays the
// single source of truth (Law 4: derived, not authored).
Aliases []string
// Hidden, when true, omits this command from usage listings while leaving it
// fully dispatchable — the convention for internal/experimental commands.
Hidden bool
// Category groups this command under a heading in the parent's usage
// listing. Commands sharing a Category are listed together; the empty
// category sorts first under no heading.
Category string
// Deprecated, when non-empty, marks this command as deprecated and supplies
// the guidance shown in usage (e.g. "use `auth login` instead"). The command
// still runs; the notice is derived into help, never hand-formatted.
Deprecated string
// Long is authored multi-line prose describing the command in detail, shown
// in the command's own usage below the summary. It is typed data — rendered,
// never hand-formatted into the structural help.
Long string
// Examples are authored example invocations, shown verbatim in the command's
// usage. Typed data, rendered as a block; the structure around them (the
// "Examples:" heading, indentation) is derived.
Examples []string
}
Command is a single subcommand in an App's command tree.
A Command either runs (Run set) or groups child commands (Sub non-empty), or both — a parent command with its own Run acts as the default when no child is named. The router builds a fresh flag.FlagSet for each invocation, calls Flags to register flags onto it, parses the remaining argv, runs any registered validators, and finally calls Run with the parsed set.
Help is DERIVED, never hand-formatted (Law 4) ¶
The help *structure* — the command listing, the flag table, enum value sets, defaults, env names — is computed mechanically from this typed data and the registered Flag values; it is never assembled by hand. The only authored content is *prose* ([Summary], Command.Long, Command.Examples), which is typed data on the Command, rendered (never formatted) — eventually through borealis (deferred while borealis.Execute/Render is in-flight; the structural derivation runs today on the stdlib renderer).
type Flag ¶
type Flag[T flagValue] struct {
// contains filtered or unexported fields
}
Flag is a typed, generic flag declaration that carries its own validation as data (Law 5: generics + behaviour). It is the elevation of the bare stdlib-flag + side-channel-validator model into one self-describing value: the flag's name, usage, default, env-var name, allowed value set (OneOf), and a typed Validate hook all travel together, so the help *structure* — type, enum set, default, env name — is DERIVED from this data and can never drift from behaviour (Law 4).
The kong `enum:` insight is realised here: declaring OneOf both *validates* the value and *auto-documents* the allowed set in usage, collapsing what was a separate OneOf validator plus hand-written help text into one declaration.
mode := cli.NewFlag[string]("mode", "fast", "execution mode").
Env("TOOL_MODE").
OneOf("fast", "slow")
cmd := cli.Command{
Name: "run",
Flags: func(fs *flag.FlagSet) { mode.Bind(fs) },
Run: func(ctx context.Context, args []string, fs *flag.FlagSet) error {
switch mode.Get() { // typed, validated read
case "fast": …
}
return nil
},
}
Get reads the parsed, validated value (the typed equivalent of fs.Lookup(name).Value). When a shikumi precedence pipeline is wired (via the cli/cfg leaf sub-package), Flag reads through the same koanf instance so "did the flag or the file win?" has exactly one fleet answer; the core type stays zero-dependency and falls back to the bound flag value.
T is constrained to the value kinds the stdlib flag package natively parses, so binding never needs reflection or a bespoke parser.
func NewFlag ¶
NewFlag declares a typed flag with a name, default, and usage string. Chain Flag.Env, Flag.OneOf, and Flag.Validate to attach metadata, then bind it inside a command's Flags callback with Flag.Bind.
func (*Flag[T]) Allowed ¶
func (f *Flag[T]) Allowed() []T
Allowed returns the configured OneOf set (nil if unrestricted).
func (*Flag[T]) Bind ¶
Bind registers the flag onto fs and wires its validation into the command's validator registry. Call it inside a command's Flags callback. The default is seeded from the env var (if set and parseable) so the bare core honours env without the shikumi layer; the shikumi layer, when wired, overrides this with the full args > env > file precedence merge.
func (*Flag[T]) Default ¶
func (f *Flag[T]) Default() T
Default returns the configured default value.
func (*Flag[T]) Env ¶
Env sets the environment variable that seeds this flag's default when the flag is not given on the command line. The env name is derived into help so users see exactly which variable backs the flag (Law 4). The actual precedence (args > env > file) is applied by the shikumi layer (cli/cfg) when wired; the bare core uses Env only to seed the default and document it.
func (*Flag[T]) Get ¶
func (f *Flag[T]) Get() T
Get returns the parsed, validated value. It must be called after parsing (inside Run). Before Bind, or before parsing, it returns the default.
func (*Flag[T]) OneOf ¶
OneOf restricts the flag to an allowed set of values and, by the same declaration, auto-documents that set in usage (the kong `enum:` model). It is validation-as-data: no separate OneOf validator and no hand-written "(one of …)" help text — both are derived from this one call.
func (*Flag[T]) Validate ¶
Validate attaches a typed validation hook run after parsing, before the command's Run. It receives the already-typed value, so a port flag validates an int, not a string. Returning a non-nil error rejects the value with a typed ValidationError. Composes with OneOf (OneOf is checked first).
type FleetFlags ¶
type FleetFlags struct {
// Auth selects the authentication method; its allowed set is auto-wired from
// the AuthResolver passed to NewFleetFlags (so --auth documents exactly the
// methods the tool supports, Law 4 / §2.2).
Auth *Flag[string]
// Profile names a saved connection profile (provides a default gateway URL,
// credentials, etc.).
Profile *Flag[string]
// GatewayURL overrides the API endpoint; highest precedence over the
// profile's URL and the built-in default.
GatewayURL *Flag[string]
// Output selects the output rendering (json|yaml, table opt-in).
Output *Flag[string]
// NoColor disables styled output; also honours the NO_COLOR env convention
// via its Env binding.
NoColor *Flag[bool]
// Verbose raises log verbosity.
Verbose *Flag[bool]
}
FleetFlags is the fleet-standard persistent flag set, defined ONCE here so every binary inherits the same surface and the same help (Law 1: uniformity; Law 4: the --auth/--output value sets are derived, never hand-listed). Bind it onto a command's FlagSet with FleetFlags.Bind and read the resolved values through its typed handles after parsing.
fleet := cli.NewFleetFlags(resolver) // --auth set derived from resolver.Kinds()
root := cli.Command{
Name: "clint",
Flags: func(fs *flag.FlagSet) { fleet.Bind(fs) },
Run: func(ctx context.Context, args []string, fs *flag.FlagSet) error {
gw := fleet.GatewayURL.Get()
return nil
},
}
The flags are the §2.2 fleet flags: --auth (kinds auto-wired from the AuthResolver), --profile, --gateway-url, --output (json|yaml[|table]), --no-color (also honouring the NO_COLOR env convention), and -verbose. They are "backed, not decorative": --gateway-url > --profile's URL > the default is the precedence the auth/config layers consume.
func NewFleetFlags ¶
func NewFleetFlags(resolver *AuthResolver, opts ...FleetOption) *FleetFlags
NewFleetFlags builds the persistent flag set, deriving the --auth allowed set from resolver.Kinds() (pass nil to leave --auth unrestricted, e.g. for tools that resolve auth elsewhere). The returned value holds typed Flag handles; bind them with Bind and read them after parsing.
func (*FleetFlags) Bind ¶
func (f *FleetFlags) Bind(fs *flag.FlagSet)
Bind registers every persistent flag onto fs (call inside a command's Flags callback). After parsing, read the resolved values through the typed handles.
type FleetOption ¶
type FleetOption func(*fleetConfig)
FleetOption configures the persistent flag set at construction.
func AllowTable ¶
func AllowTable() FleetOption
AllowTable enables "table" as an --output value for this tool (off by default so scripting tools advertise only the structured formats).
func DefaultGatewayURL ¶
func DefaultGatewayURL(u string) FleetOption
DefaultGatewayURL sets the built-in --gateway-url default (lowest precedence).
func DefaultOutput ¶
func DefaultOutput(f OutputFormat) FleetOption
DefaultOutput sets the default --output format (defaults to json).
type OutputFormat ¶
type OutputFormat string
OutputFormat names a fleet-standard rendering of command output. The set is derived once here and auto-documented on the --output flag (Law 4): json and yaml are always available; table is opt-in per tool.
const ( // OutputJSON renders machine-readable JSON (the scripting default). OutputJSON OutputFormat = "json" // OutputYAML renders YAML. OutputYAML OutputFormat = "yaml" // OutputTable renders a human-readable table; opt-in per tool via // FleetFlags.AllowTable. OutputTable OutputFormat = "table" )
type ValidationError ¶
type ValidationError struct {
Flag string // flag name (without leading dashes)
Value string // the value that failed
Err error // the underlying validator error
}
ValidationError is the typed error returned when a flag validator rejects a value. It carries the offending flag name and value so callers can branch on them; the wrapped Err is the validator's own message.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface.
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
Unwrap exposes the underlying validator error for errors.Is/errors.As.
type Validator ¶
Validator inspects a parsed flag.Flag value and returns a non-nil error to reject it. Validators are registered per flag inside a command's Flags callback via RegisterValidator and run after flag parsing, before the command's Run.
func NonEmptyURL ¶
func NonEmptyURL() Validator
NonEmptyURL rejects a value that does not parse as an absolute URL with a scheme and host (e.g. https://api.akeyless.io).
func OneOf ¶
OneOf rejects any value not in the allowed set (case-sensitive). The allowed values are listed in the error message.
func Predicate ¶
Predicate adapts an arbitrary bool-returning check into a Validator, using msg as the rejection message. It is the escape hatch for one-off rules that do not warrant their own constructor.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cfg is the cli-go ↔ shikumi-go adapter leaf (Law 8): it provides the ONE config-consuming entry a CLI uses, wiring the canonical shikumi loader to a primitive's canonical [FromConfig] constructor.
|
Package cfg is the cli-go ↔ shikumi-go adapter leaf (Law 8): it provides the ONE config-consuming entry a CLI uses, wiring the canonical shikumi loader to a primitive's canonical [FromConfig] constructor. |
|
Package cobrax is the GATED LEAF that lowers cli-go's typed grammar tree (cli.App / cli.Command / cli.Flag) onto a *cobra.Command (Law 8: the cli-go CORE stays pure-stdlib zero-dependency; cobra is imported only here).
|
Package cobrax is the GATED LEAF that lowers cli-go's typed grammar tree (cli.App / cli.Command / cli.Flag) onto a *cobra.Command (Law 8: the cli-go CORE stays pure-stdlib zero-dependency; cobra is imported only here). |
|
Package exit is the cli-go ↔ errors-go adapter leaf (Law 8): it maps the cli-go control-flow sentinels — cli.ErrHelp, cli.ErrNoCommand, and the typed *cli.ValidationError / "unknown command|subcommand" usage errors — into the errors-go exit-code vocabulary.
|
Package exit is the cli-go ↔ errors-go adapter leaf (Law 8): it maps the cli-go control-flow sentinels — cli.ErrHelp, cli.ErrNoCommand, and the typed *cli.ValidationError / "unknown command|subcommand" usage errors — into the errors-go exit-code vocabulary. |