app

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 16 Imported by: 1 module, 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.

Documentation

Overview

Package app wraps cobra so terminull apps never touch it directly.

An App owns the root command, five global flags, and the boot order: debug switch, output validation, renderer selection, config load. Handlers receive a *Context (config, logger, IO, typed flag getters) instead of cobra types. Commands declare Flags on app.FlagSet, Args with app validators, and completions with app directives. Only two intentional hatches exist: App.Raw escapes to the engine command and FlagSet.Unwrap escapes to the engine flag set.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ArbitraryArgs added in v1.1.2

func ArbitraryArgs(args []string) error

ArbitraryArgs never returns an error.

func NoArgs added in v1.1.2

func NoArgs(args []string) error

NoArgs returns an error if any args are included.

Types

type App

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

App owns the root cobra command. Build one per process with New, register commands with Add, run with Execute.

func New

func New(name string, opts ...Option) *App

New builds an App with the five global flags (no shorthands, so subcommands own -f -o -e -v freely):

--config, --output table|json|yaml, --no-color, --verbose, --debug

func (*App) Add

func (a *App) Add(c Command)

Add registers a top-level command (which may carry Children groups).

func (*App) Execute

func (a *App) Execute(ctx context.Context, args []string) error

Execute runs args against a signal-scoped ctx (see core.SignalContext). Parse and setup failures return ExitCodeError(2); handler errors pass through for core.ExitCodeOf mapping by main.

func (*App) Raw

func (a *App) Raw() *cobra.Command

Raw escapes to the underlying cobra command for advanced use. Prefer Add/Execute; Raw exists so the wrapper never blocks you.

func (*App) SetErr

func (a *App) SetErr(w io.Writer)

SetErr redirects standard error.

func (*App) SetIn

func (a *App) SetIn(r io.Reader)

SetIn redirects standard input (prompts read here).

func (*App) SetOut

func (a *App) SetOut(w io.Writer)

SetOut redirects standard output (tests capture help and results here).

type Command

type Command struct {
	// Use is the one-line usage, e.g. "deploy --env prod".
	Use string
	// Short is the short help shown in command lists.
	Short string
	// Long is the full help text.
	Long string
	// Example shows usage examples under an Examples heading.
	Example string
	// Args validates positional args (e.g. MaximumNArgs(1)).
	Args PositionalArgs
	// ValidArgs lists static shell completions for positional args.
	ValidArgs []string
	// ValidArgsFunction computes dynamic completions from args and the
	// prefix; the framework owns the command, so no engine type leaks.
	ValidArgsFunction CompletionFunc
	// Hidden removes the command from help lists without disabling it,
	// for internal and deprecated commands.
	Hidden bool
	// Flags registers command-local flags. Read them back with
	// Context.String/Bool/Int/StringSlice.
	Flags func(*FlagSet)
	// Children builds a command group; they share the parent's flags.
	Children []Command
	// Run executes the command. Nil on a group parent prints help.
	Run func(*Context) error
}

Command describes one CLI command. Children build groups like `worker {run|pause}`; a parent without Run prints its help.

Every type here is terminull-owned: define commands importing only app, never cobra or pflag. The framework maps to the engine inside build; App.Raw escapes for advanced use.

type CompletionFunc added in v1.1.2

type CompletionFunc func(args []string, toComplete string) ([]string, ShellCompDirective)

CompletionFunc computes positional completions. It drops cobra's *Command parameter: handlers complete from args and the prefix only, the framework owns the rest.

type Context

type Context struct {
	context.Context

	Config *config.Config
	Logger *render.Logger
	Out    io.Writer
	// ErrOut receives error output. Named to avoid shadowing the
	// embedded context's Err method, so *Context itself satisfies
	// context.Context and passes directly to cancellable helpers.
	ErrOut io.Writer
	In     io.Reader
	// Output is the validated --output value: table, json, or yaml.
	Output string
	// NoColor mirrors --no-color.
	NoColor bool
	// Verbose mirrors --verbose or --debug.
	Verbose bool
	// contains filtered or unexported fields
}

Context is what Run handlers receive: cancellation, layered config, a scoped-capable logger, IO, and typed flag access. It satisfies context.Context, so pass it directly to cancellable helpers.

func (*Context) Args

func (c *Context) Args() []string

Args returns the positional args after flag parsing.

func (*Context) Bool

func (c *Context) Bool(name string) (bool, error)

Bool returns the --name flag value.

func (*Context) Changed

func (c *Context) Changed(name string) bool

Changed reports whether --name was passed explicitly.

func (*Context) Int

func (c *Context) Int(name string) (int, error)

Int returns the --name flag value.

func (*Context) PauseDrawing added in v1.1.0

func (c *Context) PauseDrawing()

PauseDrawing freezes live tree redraws for foreign terminal output (prompts, spinners, bars) and ResumeDrawing continues afterwards. Both are safe no-ops on non-interactive renderers. Always pair them:

ctx.PauseDrawing()
defer ctx.ResumeDrawing()

func (*Context) ResumeDrawing added in v1.1.0

func (c *Context) ResumeDrawing()

ResumeDrawing unfreezes live tree redraws after PauseDrawing.

func (*Context) StopDrawing added in v1.1.0

func (c *Context) StopDrawing()

StopDrawing drains pending log entries, then completes the tree and finalizes terminal output. Call it before printing result tables so nothing redraws over them; the deferred stop in RunE remains as a backstop. Safe to call twice and a no-op on non-interactive renderers or a nil logger.

func (*Context) String

func (c *Context) String(name string) (string, error)

String returns the --name flag value (local or inherited global).

func (*Context) StringSlice

func (c *Context) StringSlice(name string) ([]string, error)

StringSlice returns the --name flag value.

type FlagSet added in v1.1.2

type FlagSet struct {
	*pflag.FlagSet
}

FlagSet is the terminull flag surface. It embeds *pflag.FlagSet, so every registration and query method works with zero re-implementation and zero drift: user code imports only app, never pflag.

Exotic cases (custom Value types referenced by name, AddFlagSet merges) still need the pflag import in that one file; Unwrap hands back the underlying set for them.

func (*FlagSet) Unwrap added in v1.1.2

func (f *FlagSet) Unwrap() *pflag.FlagSet

Unwrap returns the underlying pflag set for cases the facade does not name, such as custom Value implementations and set merges.

type Option

type Option func(*App)

Option tunes an App at construction.

func WithLong added in v1.1.0

func WithLong(long string) Option

WithLong sets the full description shown atop help.

func WithShort added in v1.1.0

func WithShort(short string) Option

WithShort sets the one-line description shown atop help.

func WithSymbolsOnly added in v1.1.1

func WithSymbolsOnly() Option

WithSymbolsOnly forces ASCII spinners and statuses on terminals that could render emoji. Use it for deterministic output and house styles that prefer the classic look; default follows terminal capability.

func WithVersion

func WithVersion(version string) Option

WithVersion sets the --version string (default core.FullVersion()).

type PositionalArgs added in v1.1.2

type PositionalArgs func(args []string) error

PositionalArgs validates positional args. It takes only args, unlike cobra's hook: the framework owns the command, so validators stay pure functions over argv. Count messages match cobra's wording.

func ExactArgs added in v1.1.2

func ExactArgs(n int) PositionalArgs

ExactArgs returns an error if there are not exactly n args.

func MatchAll added in v1.1.2

func MatchAll(pargs ...PositionalArgs) PositionalArgs

MatchAll combines validators, reporting the first failure.

func MaximumNArgs added in v1.1.2

func MaximumNArgs(n int) PositionalArgs

MaximumNArgs returns an error if there are more than n args.

func MinimumNArgs added in v1.1.2

func MinimumNArgs(n int) PositionalArgs

MinimumNArgs returns an error if there are fewer than n args.

func OnlyValidArgs added in v1.1.2

func OnlyValidArgs(valid []string) PositionalArgs

OnlyValidArgs returns an error for args outside valid. Unlike cobra's version it takes the list explicitly instead of reading command state, so it stays a pure function. Tab-suffixed descriptions are stripped before comparing, matching cobra's ValidArgs convention.

func RangeArgs added in v1.1.2

func RangeArgs(min, max int) PositionalArgs

RangeArgs returns an error if the arg count is outside [min, max].

type ShellCompDirective added in v1.1.2

type ShellCompDirective int

ShellCompDirective controls shell completion behavior. Values are bit-identical to cobra's directives (asserted in tests), so behavior matches exactly while user code imports only app.

const (
	// ShellCompDirectiveError discards completions on error.
	ShellCompDirectiveError ShellCompDirective = 1 << iota
	// ShellCompDirectiveNoSpace skips the trailing space after a
	// single completion.
	ShellCompDirectiveNoSpace
	// ShellCompDirectiveNoFileComp disables file completion when no
	// completion is provided.
	ShellCompDirectiveNoFileComp
	// ShellCompDirectiveFilterFileExt filters files by the provided
	// extensions.
	ShellCompDirectiveFilterFileExt
	// ShellCompDirectiveFilterDirs completes directory names only.
	ShellCompDirectiveFilterDirs
	// ShellCompDirectiveKeepOrder preserves completion order.
	ShellCompDirectiveKeepOrder
	// ShellCompDirectiveDefault lets the shell use default behavior.
	ShellCompDirectiveDefault ShellCompDirective = 0
)

Jump to

Keyboard shortcuts

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