Go guide

Go API

Package clyops is declarative, one-line-per-option CLI parsing for Go: validation, help text, a JSON schema of the interface, config files, environment variables, logging and shell completion. Behavior follows spec/SPEC.md in https://github.com/wankdanker/clyops.

cli := clyops.New()
cli.Arg("input", "Input file", "", "path")
cli.Opt("PORT", "port", "p", "8080", "Server port", "Network", "port")
cli.Opt("VERBOSE", "verbose", "v", "flag", "Verbose output")
v := cli.Run()
fmt.Println(v.String("input"), v.Int("PORT"), v.Bool("VERBOSE"))

Version

const Version = "0.3.0"

Version is the clyops version this package implements.

DescribeRule

func DescribeRule(rule string) string

DescribeRule is the help text for a validation rule (spec section 5).

Die

func Die(code int, format string, args ...any)

Die logs an error (never suppressed) and exits with code.

Error

func Error(format string, args ...any)

Error logs an error to stderr.

Info

func Info(format string, args ...any)

Info logs an informational message to stderr.

ResolvePath

func ResolvePath(value, base string, searchDirs []string) string

ResolvePath resolves a path value against base (spec section 6), trying searchDirs for bare names that don't exist under base.

SetSilent

func SetSilent(value bool)

SetSilent suppresses Info/Warn/Error/Success output (Die and parse errors still print).

Success

func Success(format string, args ...any)

Success logs a success message to stderr.

Validate

func Validate(value, rule, name string) (any, error)

Validate checks value against rule and returns its typed form: int for int* and port, float64 for float*, bool for bool, string otherwise.

Warn

func Warn(format string, args ...any)

Warn logs a warning to stderr.

WrapText

func WrapText(text string, width int) []string

WrapText is a greedy word wrap that keeps existing line breaks (spec section 7).

Cli

type Cli struct {
	Name   string            // program name (default: the executable's base name)
	Root   string            // base for default path values (default: Cwd)
	Cwd    string            // base for command-line path values (default: the working directory)
	Env    map[string]string // environment (default: the process environment)
	Values Values
	// contains filtered or unexported fields
}

Cli is a program's command-line interface. Register options and arguments, then call Run (or Parse).

New

func New() *Cli

New returns an empty Cli for the running program.

Cli.Arg

func (c *Cli) Arg(name, description, def string, rule ...string) *Cli

Arg registers a positional argument. An empty def makes it required.

Cli.ArgVariadic

func (c *Cli) ArgVariadic(name, description string, rule ...string) *Cli

ArgVariadic registers a final positional argument that collects the remaining tokens.

Cli.Command

func (c *Cli) Command(name, description string) *Cli

Command registers a command (spec section 1.7) and returns it, to register its options and arguments on.

Cli.CommandPath

func (c *Cli) CommandPath() []string

CommandPath is the command words selected by the last parse, e.g. ["db", "migrate"].

Cli.CompletionData

func (c *Cli) CompletionData(words ...string) string

CompletionData is the tab-separated completion records (spec section 9). words are the words typed after the program name; a program with commands follows them.

Cli.CompletionScript

func (c *Cli) CompletionScript(shell string) (script string, ok bool)

CompletionScript is the shell script that enables completion for this program (spec section 9): eval "$(prog --completion bash)". ok is false for an unknown shell.

Cli.Exclusive

func (c *Cli) Exclusive(longs ...string) *Cli

Exclusive says at most one of these options may be given.

Cli.Get

func (c *Cli) Get(name string) any

Get is a resolved value by option variable or argument name.

Cli.IsExplicitlySet

func (c *Cli) IsExplicitlySet(long string) bool

IsExplicitlySet reports whether the option came from the command line, a config file or the environment.

Cli.IsSet

func (c *Cli) IsSet(long string) bool

IsSet reports whether the option was given on the command line.

Cli.JSONSchema

func (c *Cli) JSONSchema() string

JSONSchema is the JSON description of the CLI (spec section 8).

Cli.OneOf

func (c *Cli) OneOf(longs ...string) *Cli

OneOf says at least one of these options must be given.

Cli.Opt

func (c *Cli) Opt(variable, long, short, def, description string, groupAndRule ...string) *Cli

Opt registers an option. def is a value, "flag", "optional", or "" (required). groupAndRule is an optional group (default "Options") and validation rule.

Cli.OptArray

func (c *Cli) OptArray(variable, long, short, description string, groupAndRule ...string) *Cli

OptArray registers a repeatable option whose values accumulate into a list.

Cli.Parse

func (c *Cli) Parse(argv []string) ParseResult

Parse parses argv without exiting. Values are in c.Values when Status is "ok".

Cli.RequireCommand

func (c *Cli) RequireCommand(name, description, installHint string) *Cli

RequireCommand declares an external command the program needs.

Cli.Requires

func (c *Cli) Requires(long string, longs ...string) *Cli

Requires says that when long is given, the others must be too.

Cli.Run

func (c *Cli) Run() Values

Run parses os.Args like a CLI: it handles --help, --help-json-schema, --completion and --bash-completion, prints errors and exits on failure, and returns the values.

Cli.RunArgs

func (c *Cli) RunArgs(argv []string) Values

RunArgs is Run with an explicit argv (without the program name).

Cli.SetConfig

func (c *Cli) SetConfig(option, prefixes string) *Cli

SetConfig names the option holding a config file path; prefixes is comma-separated.

Cli.SetDescription

func (c *Cli) SetDescription(text string) *Cli

SetDescription sets the text shown under the usage line.

Cli.SetEffects

func (c *Cli) SetEffects(effects ...string) *Cli

SetEffects declares what running the program does: read-only, idempotent, destructive, network.

Cli.SetEpilog

func (c *Cli) SetEpilog(text string) *Cli

SetEpilog sets the text shown at the end of the help.

Cli.SetPathSearch

func (c *Cli) SetPathSearch(long, dirs string) *Cli

SetPathSearch gives fallback directories (colon-separated, relative to Root) for bare relative values of a path option.

Cli.SetStdin

func (c *Cli) SetStdin(description, contentType string) *Cli

SetStdin declares what the program reads on stdin; contentType is a MIME type or a comma-separated list.

Cli.SetStdout

func (c *Cli) SetStdout(description, contentType string) *Cli

SetStdout declares what the program writes on stdout; undeclared means text.

Cli.Source

func (c *Cli) Source(long string) string

Source is where an option's value came from: cli, config, env, default or unset.

Cli.Usage

func (c *Cli) Usage() string

Usage is the help text (spec section 7), for the selected command.

Cli.ValuesJSON

func (c *Cli) ValuesJSON() string

ValuesJSON is the resolved values as JSON (spec section 10), in registration order.

ParseResult

type ParseResult struct {
	Status    string
	Error     string
	ShowUsage bool
	Detail    []string
}

ParseResult is the outcome of Parse: Status is "ok", "help" or "error".

ValidationError

type ValidationError struct{ Message string }

ValidationError carries the spec's error text for a value that fails its rule.

ValidationError.Error

func (e *ValidationError) Error() string

Error returns the validation failure message, implementing error.

Values

type Values map[string]any

Values holds resolved values, keyed by option variable and argument name. Types follow spec section 10: bool for flags, int, float64, string, a []any for arrays and variadics, nil when unset.

Values.Bool

func (v Values) Bool(name string) bool

Bool is the value as a bool (false when unset).

Values.Float

func (v Values) Float(name string) float64

Float is the value as a float64 (0 when unset).

Values.Int

func (v Values) Int(name string) int

Int is the value as an int (0 when unset or not an integer).

Values.List

func (v Values) List(name string) []any

List is an array option's or variadic argument's values.

Values.String

func (v Values) String(name string) string

String is the value as a string ("" when unset).

Values.Strings

func (v Values) Strings(name string) []string

Strings is an array option's or variadic argument's values as strings.