helper

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 14 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.

Documentation

Overview

Package helper provides the flag type resolution and output helpers shared by the command line commands.

Index

Constants

View Source
const (
	// ExitFailure is the exit code of a failure with no more specific code (also bad usage).
	ExitFailure = 1
	// ExitInvalid is the exit code of invalid input: documents, flags or a configuration file.
	ExitInvalid = 2
	// ExitConflict is the exit code of a lost race: another publisher changed the manifest. Nothing visible changed.
	ExitConflict = 3
	// ExitTransport is the exit code of a failed call to the store (network, access, throttling). Repeating is safe.
	ExitTransport = 4
	// ExitVerify is the exit code of a verification that found problems in the bucket.
	ExitVerify = 5
	// ExitUnknown is the exit code of a change whose outcome is not known (the reply was lost): look before repeating.
	ExitUnknown = 6
)

The exit codes of the commands that report more than success or failure. A command returns an ExitError to choose one; every other error exits with ExitFailure.

View Source
const HelpWidth = 80

HelpWidth is the upper bound on help text wrapping width so output does not depend on terminal width.

Variables

View Source
var (
	ErrEarlyExit = errors.New("early exit")
)

ErrEarlyExit is returned from a BeforeReset flag hook (such as HelpFlag) to stop parsing with exit code 0 before validation runs.

View Source
var ErrUsage = errors.New("usage")

ErrUsage marks a failure of the command line itself: a missing or extra argument, a flag that does not parse, flags that cannot be combined. It exits with ExitFailure and is named "usage" in the JSON error object.

Functions

func DecodeString added in v0.2.0

func DecodeString(ctx *kong.DecodeContext, target reflect.Value) error

DecodeString decodes kong string values, stripping one leading "=" from short-flag tails such as "-c=cfg.yaml" or "-o=json" while preserving literal leading "=" in separated or long-flag values.

func ExitCodeOf added in v0.2.0

func ExitCodeOf(err error) int

ExitCodeOf returns the exit code that err asks for, ExitFailure when it asks for none.

func FatalPrinter added in v0.2.0

func FatalPrinter(stderr io.Writer) *pterm.PrefixPrinter

FatalPrinter returns the printer of the final error line of every command: it writes to stderr, so that stdout carries results only.

func FlagTypeFromVariations

func FlagTypeFromVariations(variations map[string]*any) (model.FlagType, error)

FlagTypeFromVariations returns the flag type inferred from the values of the variations.

func JSONErrorName added in v0.2.0

func JSONErrorName(code int) string

JSONErrorName is the stable name of an exit code in the JSON error object.

func LegacyWarner

func LegacyWarner() *legacy.Warner

LegacyWarner returns the Warner of a CLI command: the use of a legacy name is logged once, through the default logger of the process.

func LegacyWarnerTo

func LegacyWarnerTo(logger func() *slog.Logger) *legacy.Warner

LegacyWarnerTo is LegacyWarner with the logger it writes to: logger is called for every warning, so a default logger replaced after the warner was built is still honoured.

func MarkReported added in v0.2.0

func MarkReported(err error) error

MarkReported marks err as already written to stdout as the result of the command, so that ReportJSONError does not write an error object for it. It keeps the error and its exit code.

func Parse added in v0.2.0

func Parse(parser *kong.Kong, args []string) (*kong.Context, bool, error)

Parse runs parser.Parse(args) and translates ErrEarlyExit into (nil, true, nil).

func PrintFatal

func PrintFatal(printer *pterm.PrefixPrinter, exit func(int), err error)

PrintFatal prints err with printer, then calls exit with the code of the error (ExitCodeOf). The printer and the exit function are parameters so that the callers that must not stop the process (tests) can pass their own.

func PrintFatalAndExit

func PrintFatalAndExit(err error)

PrintFatalAndExit prints err as an error on stderr and exits the process with the code of the error (ExitCodeOf), 1 for an error that asks for none.

func RegisterHelpFlag added in v0.2.0

func RegisterHelpFlag(app *kong.Kong) error

RegisterHelpFlag sets kong's Model.HelpFlag to the explicit "help" flag after building the parser so kong's default help footer ("Run \"<app> <command> --help\" for more information on a command.") is still printed even when kong.NoDefaultHelp is enabled. Pass it to kong.PostBuild.

func ReportJSONError added in v0.2.0

func ReportJSONError(stdout io.Writer, enabled bool, details func(error) []string, err error) error

ReportJSONError ensures err carries an ExitError (defaulting to ExitFailure) and, when enabled is true and err has not been marked with MarkReported, writes one JSON error object to stdout before returning err.

func ScanOutputFlag added in v0.2.0

func ScanOutputFlag(flags []*kong.Flag, args []string) (string, bool)

ScanOutputFlag scans raw command-line arguments using Kong's flag metadata to find the last value given to --output or -o, even when an unknown or malformed flag stops Kong's parser before --output is reached. Unknown flags and malformed tokens are skipped, "--" stops scanning, and values belonging to known non-boolean flags are consumed so flag-like values (such as "--config=-otext") are not misread.

func WithExitCode added in v0.2.0

func WithExitCode(err error, code int) error

WithExitCode wraps err so that the process exits with code. A nil err stays nil.

func WriteJSONError added in v0.2.0

func WriteJSONError(w io.Writer, code string, err error, details []string) error

WriteJSONError writes the error of a failed command as one JSON object on w:

{"error": {"code": "invalid", "message": "...", "details": ["..."]}}

code is one of invalid, conflict, transport, bad-state, usage or failure. details is never null. The message and the details come from the error text, which never holds a secret.

Types

type ExitError added in v0.2.0

type ExitError struct {
	// Err is the error to print.
	Err error
	// Code is the exit code.
	Code int
}

ExitError is an error that carries the exit code of the process.

func (*ExitError) Error added in v0.2.0

func (e *ExitError) Error() string

Error implements error.

func (*ExitError) Unwrap added in v0.2.0

func (e *ExitError) Unwrap() error

Unwrap returns the wrapped error.

type HelpFlag added in v0.2.0

type HelpFlag bool

HelpFlag is a kong --help / -h flag that honours --help=false and exits parsing via ErrEarlyExit without panicking.

func (HelpFlag) BeforeReset added in v0.2.0

func (HelpFlag) BeforeReset(ctx *kong.Context) error

BeforeReset prints kong help when the flag decoded to true and returns ErrEarlyExit.

type Level

type Level = string

Level is the severity of a line of command output.

const (
	// WarnLevel is the severity of a warning line of command output.
	WarnLevel Level = "WARNING"
	// InfoLevel is the severity of an informational diagnostic (progress, notes): it goes to stderr.
	InfoLevel Level = "INFO"
	// StatusLevel is the severity of a line that is the result of the command (for example "Valid Semaphore
	// configuration"): it is printed like an info line, on stdout.
	StatusLevel Level = "STATUS"
	// ErrorLevel is the severity of an error line of command output.
	ErrorLevel Level = "ERROR"
	// DefaultLevel is the severity of an output line when none is given.
	DefaultLevel Level = "DEFAULT"
)

type Output

type Output struct {
	Lines []OutputLine
}

Output collects the lines printed by a command.

func (*Output) Add

func (o *Output) Add(line string, level Level) Output

Add appends a line with the given level to the output and returns it.

func (*Output) PrintLines

func (o *Output) PrintLines(stdout, stderr io.Writer) error

PrintLines writes the collected lines to stdout and stderr. stdout carries results only: StatusLevel and DefaultLevel lines go to stdout; every diagnostic (InfoLevel, WarnLevel, ErrorLevel) goes to stderr.

type OutputLine

type OutputLine struct {
	Text  string
	Level Level
}

OutputLine is a line of command output with its severity.

type Streams added in v0.2.0

type Streams struct {
	Stdout io.Writer
	Stderr io.Writer
}

Streams holds the output writers injected into CLI commands.

Jump to

Keyboard shortcuts

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