cli

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 12 Imported by: 11 modules, 3 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

cli-go

The pleme-io CLI framework for Go — the Go counterpart to the Rust clap / caixa-clap model. A named app, a tree of subcommands, per-flag validators, and a small multi-auth resolver — so every Go binary in the fleet dispatches, validates, and prints usage the same way.

No hand-rolled argv switch statements, no bespoke flag parsing per tool. Build an App, Add commands, hand it os.Args.

Why

Stdlib flag parses flags but stops there: no subcommands, no validators, no usage tree, no auth-selection convention. cli-go adds exactly those layers — and nothing else. The core package is pure standard library, zero dependencies (flag, context, errors, os, reflect, sort, strconv, strings), so it builds offline with a minimal closure. The dep-bearing integrations live in leaf sub-packages (cli-go/cfg, cli-go/exit) so the core stays weightless (Borealis Laws 6 & 8).

Borealis elevation (§2.2)

Under the Borealis Theory, cli-go is the fleet CLI authoring surface: it owns the typed grammar (a single source of truth), while presentation is owned by borealis. Help structure — flag types, enum sets, defaults, env names, the command listing — is DERIVED from the typed data and is never hand-formatted (Law 4). The elevated surface adds, additively over the original:

  • Flag[T] — validation-as-data. A generic, self-describing flag whose Name, Default, Env, OneOf, and typed Validate travel together. OneOf both validates and auto-documents the allowed set (the kong enum: model). Read a parsed, validated, typed value with Flag.Get().
  • FleetFlags — the persistent flag set, defined once. --auth (its value set auto-wired from AuthResolver.Kinds()), --profile, --gateway-url, --output json|yaml (table opt-in), --no-color/NO_COLOR, --verbose.
  • Raised Command. Aliases, Hidden, Category, Deprecated (derived into help) plus authored prose Long / Examples (typed data, rendered).
  • cli-go/cfg — config (Law 3, §3.5). cfg.WithConfig internally calls shikumi.For, runs the canonical precedence pipeline (args > env > file), selects the primitive's sub-struct, and hands it to the consumer's FromConfig. One loader, one consumer shape, wired in this leaf — never a second loader idiom.
  • cli-go/exit — exit codes (errors-go is the sole owner, §3.5). exit.Map maps ErrHelp → 0 and usage errors (ErrNoCommand, *ValidationError, unknown command/subcommand, parse failures) → EX_USAGE via errors.WithExitCode. It never calls os.Exit; the single funnel is errs.Exit(run()) at main.

Deferred (in-flight siblings): borealis.Execute(ctx, root, opts…) is the CLI entrypoint, owned by borealis (which pre-wires the color scheme); the root Command defined here is passed to it — cli-go does not redeclare Execute. Borealis-rendered styled help/errors are likewise deferred until borealis.Execute/Render lands. The core builds and tests green standalone.

Model

  • App — a named root with a version and description (functional options: WithVersion, WithDescription, WithOutput). Built-in --help/-h and --version/-v.
  • Command — {Name, Summary, Flags, Run, Sub}. Flags registers onto a fresh per-invocation *flag.FlagSet; Run receives the parsed, validated set and the positional args. Sub enables nested subcommands (≥ 1 level); a parent with its own Run acts as the default when no child matches.
  • Validators — register a Validator per flag with RegisterValidator inside the Flags callback. They run after Parse, before Run, and the first failure returns a typed *ValidationError. Bundled constructors: Required, OneOf, Range, NonEmptyURL, Predicate.
  • Multi-auth — AuthResolver selects exactly one AuthMethod from a registered set (api-key / token / aws-iam / azure-ad / gcp / k8s / …) via an explicit --auth selector or env-var auto-detection. Transport-free: it resolves which method and what inputs, not how to call any server.

Usage

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")
        fs.Int("limit", 100, "max results")
        cli.RegisterValidator(fs, "path", cli.Required())
        cli.RegisterValidator(fs, "limit", cli.Range(1, 1000))
    },
    Run: func(ctx context.Context, args []string, fs *flag.FlagSet) error {
        // fs is parsed and validated here.
        return nil
    },
})

// Nested: `clint auth login`
app.Add(cli.Command{
    Name:    "auth",
    Summary: "Authentication commands",
    Sub: []cli.Command{
        {Name: "login", Summary: "Log in", Run: doLogin},
    },
})

if err := app.Run(context.Background(), os.Args); err != nil &&
    !errors.Is(err, cli.ErrHelp) {
    log.Fatal(err)
}
Typed flags + fleet flags (elevated)
// Validation-as-data: name/default/env/OneOf/Validate travel together, and the
// allowed set auto-documents in --help (Law 4).
mode := cli.NewFlag[string]("mode", "fast", "execution mode").
    Env("TOOL_MODE").
    OneOf("fast", "slow")

port := cli.NewFlag[int]("port", 8080, "listen port").
    Validate(func(v int) error {
        if v < 1 || v > 65535 { return errors.New("out of range") }
        return nil
    })

// The fleet-standard persistent flag set — defined once; --auth's set is
// auto-wired from the resolver's Kinds().
fleet := cli.NewFleetFlags(resolver, cli.AllowTable())

app.Add(cli.Command{
    Name:     "run",
    Aliases:  []string{"r"},
    Category: "Core",
    Long:     "Runs the job against the selected gateway.",
    Examples: []string{"clint run -mode fast --output json"},
    Flags: func(fs *flag.FlagSet) {
        mode.Bind(fs)
        port.Bind(fs)
        fleet.Bind(fs)
    },
    Run: func(ctx context.Context, args []string, fs *flag.FlagSet) error {
        _ = mode.Get()             // typed, validated read
        _ = fleet.GatewayURL.Get()
        return nil
    },
})
Config (cli-go/cfg) and exit codes (cli-go/exit)
// One loader (shikumi.For), one consumer (FromConfig), wired in the cfg leaf.
build := cfg.WithConfig(
    "akeyless-foo",
    Root{},                                            // typed defaults
    func(r Root) logging.Config { return r.Logging },  // select sub-struct
    logging.FromConfig,                                // primitive's FromConfig
    cfg.WithEnvPrefix("AKL_FOO_"),
)
log, err := build(ctx)

// errors-go owns process exit; cli-go/exit only maps sentinels to codes.
func main() { errs.Exit(run()) }                       // the single funnel
func run() error {
    err := app.Run(context.Background(), os.Args)
    return exit.Map(err)                               // ErrHelp→0, usage→EX_USAGE
}
Multi-auth selection
r := cli.NewAuthResolver().
    Register(cli.AuthMethod{Kind: cli.AuthAPIKey, EnvVar: "AKEYLESS_ACCESS_KEY"}).
    Register(cli.AuthMethod{Kind: cli.AuthToken,  EnvVar: "AKEYLESS_TOKEN"}).
    Register(cli.AuthMethod{
        Kind:   cli.AuthAWS,
        EnvVar: "AWS_ROLE",
        Resolve: func(role string) (map[string]string, error) {
            return map[string]string{"role": role, "region": "us-east-1"}, nil
        },
    })

// Explicit --auth flag, or "" to auto-detect from whichever env var is present.
res, err := r.Resolve(authFlagValue)
// res.Kind, res.Credentials

Sentinel errors

App.Run returns ErrHelp when help was printed and ErrNoCommand when argv carried no subcommand — treat both as clean exits. A flag validator failure returns a *ValidationError (use errors.As); it carries the offending Flag and Value and unwraps to the validator's own error.

Build & test

go build ./...
go test ./...

The core package is pure standard library — nothing to vendor. The cli-go/cfg and cli-go/exit leaf sub-packages depend on the elevated siblings shikumi-go and errors-go respectively; during pre-publish development those resolve via temporary local replace directives in go.mod (removed at publish).

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

Constants

This section is empty.

Variables

View Source
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)
}
View Source
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

func RegisterValidator(fs *flag.FlagSet, name string, v Validator)

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 NewApp

func NewApp(name string, opts ...AppOption) *App

NewApp creates an App with the given program name and options.

func (*App) Add

func (a *App) Add(cmds ...Command) *App

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

func (a *App) Commands() []Command

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

func (a *App) Description() string

Description returns the App's one-line description (empty if unset).

func (*App) ExecCommand

func (a *App) ExecCommand(ctx context.Context, cmd Command, path string, args []string) error

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) Name

func (a *App) Name() string

Name returns the program name.

func (*App) Output

func (a *App) Output() io.Writer

Output returns the App's usage/version output writer (defaults to os.Stderr).

func (*App) Run

func (a *App) Run(ctx context.Context, argv []string) error

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.

func (*App) Version

func (a *App) Version() string

Version returns the configured version string (empty if unset).

type AppOption

type AppOption func(*App)

AppOption configures an App at construction time (the functional-options pattern). See WithVersion and WithDescription.

func WithDescription

func WithDescription(d string) AppOption

WithDescription sets the App's one-line description, shown in top-level usage.

func WithOutput

func WithOutput(w io.Writer) AppOption

WithOutput redirects the App's usage and version output. The default is os.Stderr, matching the flag package and standard CLI convention.

func WithVersion

func WithVersion(v string) AppOption

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.

const (
	AuthAPIKey AuthKind = "api-key"
	AuthToken  AuthKind = "token"
	AuthAWS    AuthKind = "aws-iam"
	AuthAzure  AuthKind = "azure-ad"
	AuthGCP    AuthKind = "gcp"
	AuthK8s    AuthKind = "k8s"
)

Common auth kinds. These are conveniences; AuthKind is a plain string and any value may be registered.

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

type AuthResult struct {
	Kind        AuthKind
	Credentials map[string]string
}

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

func NewFlag[T flagValue](name string, def T, usage string) *Flag[T]

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

func (f *Flag[T]) Bind(fs *flag.FlagSet)

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

func (f *Flag[T]) Env(name string) *Flag[T]

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]) EnvName

func (f *Flag[T]) EnvName() string

EnvName returns the configured env var name (empty if unset).

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]) Name

func (f *Flag[T]) Name() string

Name returns the flag's name (without leading dashes).

func (*Flag[T]) OneOf

func (f *Flag[T]) OneOf(allowed ...T) *Flag[T]

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

func (f *Flag[T]) Validate(check func(T) error) *Flag[T]

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

type Validator func(value string) error

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

func OneOf(allowed ...string) Validator

OneOf rejects any value not in the allowed set (case-sensitive). The allowed values are listed in the error message.

func Predicate

func Predicate(ok func(value string) bool, msg string) Validator

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.

func Range

func Range(min, max int) Validator

Range rejects an integer flag value outside the inclusive [min, max] bounds. It also rejects values that do not parse as integers, so it doubles as an int-shape check on string flags.

func Required

func Required() Validator

Required rejects an empty (or whitespace-only) flag value. Useful for flags that have no sensible default but must be set explicitly.

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.

Jump to

Keyboard shortcuts

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