commander

package
v0.0.0-...-6f3d572 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: MIT Imports: 24 Imported by: 6

Documentation

Index

Constants

View Source
const (
	// FlagNoShortName is the rune value for flags that indicates no short flag should be included.
	FlagNoShortName rune = constants.FlagNoShortName // Runes are actually int32. Negative values indicate unknown rune

	// FlagStop is a string indicating that no further flag values should be processed.
	FlagStop = "--"
)
View Source
const (
	DebugEnvVar = "LEEP_FROG_DEBUG"
)
View Source
const (
	// GetwdKey is the `command.Data` key used by `Getwd`.
	GetwdKey = "GETWD"
)
View Source
const (
	// RuntimeCallerKey is the `command.Data` key used by `RuntimeCaller`.
	RuntimeCallerKey = "RUNTIME_CALLER"
)

Variables

View Source
var (
	// MultiFlagRegex is the regex used to determine a multi-flag (`-qwer -> -q -w -e -r`).
	// It explicitly doesn't allow short number flags.
	MultiFlagRegex = regexp.MustCompile("^-[a-zA-Z]{2,}$")
	ShortFlagRegex = regexp.MustCompile("^[a-zA-Z0-9]$")
)
View Source
var (
	CacheDefaultHistory = 100
)
View Source
var (
	// Getwd is a `GetProcessor` that retrieves the current working directory.
	Getwd = &GetProcessor[string]{
		SuperSimpleProcessor(func(i *command.Input, d *command.Data) error {
			s, err := stubs.OSGetwd()
			if err != nil {
				return fmt.Errorf("failed to get current directory: %v", err)
			}
			d.Set(GetwdKey, s)
			return nil
		}),
		GetwdKey,
	}
)
View Source
var (
	// SetupArg is an argument that points to the filename containing the output of the Setup command.
	// Note: for some reason in windows (for history at least), this has a ton of null characters (\x00)
	// that need to be removed in the CLI itself.
	SetupArg = FileArgument("SETUP_FILE", "file used to run setup for command", HiddenArg[string]())
)
View Source
var (
	// ShortcutArg is the `Arg` used to check for shortcuts.
	ShortcutArg = Arg[string]("SHORTCUT", "Name of the shortcut", MinLength[string, string](1))
)

Functions

func Autocomplete

func Autocomplete(n command.Node, compLine string, passthroughArgs []string, os command.OS) (*command.Autocompletion, error)

Autocomplete returns the completion suggestions for the provided command.Node, `COMP_LINE`, and `passthroughArgs` (`passthroughArgs` are used for `Aliaser` statements). The returned slice is a list of autocompletion suggestions, and the returned error indicates if there was an issue. The error can be sent to stderr without causing any autocompletion issues.

func BoolValueFlag

func BoolValueFlag[T any](name string, shortName rune, desc string, trueValue T) *boolFlag[T]

BoolValueFlag creates a boolean `FlagInterface` whose data value gets set to `trueValue` if the flag is provided.

func BoolValuesFlag

func BoolValuesFlag[T any](name string, shortName rune, desc string, trueValue, falseValue T) *boolFlag[T]

BoolValuesFlag creates a boolean `FlagInterface` whose data value gets set to `trueValue` if the flag is provided. Otherwise, it gets set to `falseValue`

func BranchSynonyms

func BranchSynonyms(m map[string][]string) map[string]string

BranchSynonyms converts a map from branching argument to synonyms to a branching synonym map.

func CacheNode

func CacheNode(name string, c CachableCLI, n command.Node, opts ...CacheOption) command.Node

CacheNode returns a node that caches any execution of downstream commands. A `CacheNode` introduces new branches, hence the requirement for it to be a `command.Node` and not just a `command.Processor`.

func CreateFile

func CreateFile(name string, contents []string, ps fs.FileMode) error

CreateFile creates a file from the provided string slice.

func DataTransformer

func DataTransformer[I, O any](key string, f func(I) (O, error)) command.Processor

DataTransformer transforms the value in command.Data under `key` using the provided function.

func DebugMode

func DebugMode() bool

DebugMode returns whether or not debug mode is active.

func Debugf

func Debugf(o command.Output, s string, i ...interface{})

func Description

func Description(desc string) command.Processor

Description creates a `command.Processor` that adds a command description to the usage text.

func Descriptionf

func Descriptionf(s string, a ...interface{}) command.Processor

Descriptionf is like `Description`, but with formatting options.

func EchoExecuteDataf

func EchoExecuteDataf(format string) command.Processor

EchoExecuteDataf returns a `command.Processor` that sends the `command.ExecuteData` contents to stdout with the provided format

func ExecutableProcessor

func ExecutableProcessor(f func(command.Output, *command.Data) ([]string, error)) command.Processor

ExecutableProcessor returns a `command.Processor` that adds to the command's `Executable`. Below are some tips when writing bash outputs for this: 1. Be sure to initialize variables with `local` to avoid overriding variables used in sourcerer scripts. 2. Use `return` rather than `exit` when terminating a session early.

func Execute

func Execute(n command.Node, input *command.Input, output command.Output, os command.OS) (*command.ExecuteData, error)

Execute executes a node with the provided `command.Input` and `command.Output`.

func FileContents

func FileContents(name, desc string, opts ...ArgumentOption[string]) command.Processor

FileContents converts a filename into the file's contents.

func FileNumberInputTransformer

func FileNumberInputTransformer(UpToIndexInclusive int) *command.InputTransformer

FileNumberInputTransformer transforms input arguments of the format "input.go:123" into ["input.go" "123"]. This allows CLIs to transform provided arguments and use regular string and int `Argument`s for parsing arguments.

func FlagProcessor

func FlagProcessor(fs ...FlagInterface) *flagProcessor

FlagProcessor returns a `command.Processor` that iterates over the remaining command line arguments and processes any flags that are present.

func FunctionWrap

func FunctionWrap() command.Processor

FunctionWrap sets command.ExecuteData.FunctionWrap to true.

func If

If runs the provided processor if the function argunment returns true in the relevant complete and execute contexts.

func IfData

func IfData(dataArg string, p command.Processor) command.Processor

IfData runs `command.Processor` p if the argument name is present in command.Data. If the argument's type is a boolean, then it also must not be false.

func IfElse

func IfElse(t, f command.Processor, fn func(i *command.Input, d *command.Data) bool) command.Processor

IfElse runs `command.Processor` t if the function argunment returns true in the relevant complete and execute contexts. Otherwise, `command.Processor` f is run.

func IfElseData

func IfElseData(dataArg string, t, f command.Processor) command.Processor

IfElseData runs `command.Processor` t if the argument name is present in command.Data. If the argument's type is a boolean, then it also must not be false. Otherwise, `command.Processor` f is run.

func IsBranchingError

func IsBranchingError(err error) bool

IsBranchingError returns whether or not the provided error is a branching error.

func IsNotEnoughArgsError

func IsNotEnoughArgsError(err error) bool

IsNotEnoughArgsError returns whether or not the provided error is a `NotEnoughArgs` error.

func IsUsageError

func IsUsageError(err error) bool

IsUsageError returns whether or not the provided error is a usage-related error.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError returns whether or not the provided error is a validation error.

func NodeRepeater

func NodeRepeater(n command.Node, minN, optionalN int) command.Processor

NodeRepeater is a `command.Processor` that runs the provided command.Node at least `minN` times and up to `minN + optionalN` times. It should work with most node types, but hasn't been tested with branch nodes and flags really. Additionally, any argument nodes under it should probably use `CustomSetter` arg options.

func NotEnoughArgs

func NotEnoughArgs(name string, req, got int) error

NotEnoughArgs returns a custom error for when not enough arguments are provided to the command.

func PrintlnProcessor

func PrintlnProcessor(v string) command.Processor

PrintlnProcessor returns a `command.Processor` that runs `output.Stdoutln(v)`.

func Prompt

func Prompt(output command.Output, question string) chan string

Prompt prompts the user for input.

func ReadFile

func ReadFile(name string) ([]string, error)

ReadFile reads the file into a slice of strings

func RunArgumentCompleter

func RunArgumentCompleter[T any](c Completer[T], value T, data *command.Data) (*command.Completion, error)

RunArgumentCompleter generates a `command.Completion` object from the provided `Completer` and inputs.

func RunArgumentCompletion

func RunArgumentCompletion[T any](completion *command.Completion, value T, data *command.Data) (*command.Completion, error)

RunArgumentCompletion generates a `command.Completion` object from the provided `command.Completion` and inputs.

func SerialNodes

func SerialNodes(ps ...command.Processor) command.Node

SerialNodes returns a graph that iterates serially over nodes with the provided `command.Processor` objects.

func SetEnvVarProcessor

func SetEnvVarProcessor(envVar, value string) command.Processor

SetEnvVarProcessor returns a `command.Processor` that sets the environment variable to the provided value.

func SetupOutputContents

func SetupOutputContents(d *command.Data) ([]string, error)

SetupOutputString returns the file contents, as a string slice, of the setup file for the command.

func SetupOutputFile

func SetupOutputFile(d *command.Data) string

SetupOutputFile returns the name of the setup file for the command.

func SetupOutputString

func SetupOutputString(d *command.Data) (string, error)

SetupOutputString returns the file contents, as a string, of the setup file for the command.

func ShortcutNode

func ShortcutNode(name string, sc ShortcutCLI, n command.Node) command.Node

ShortcutNode wraps the provided node with a shortcut node. It is important to note that any argument transformers should be idempotent (e.g. for some string variable `s`, `transformer.F(s) == transformer.F(transformer.F(s))`) as the transformer will run when the shortcut values are added to a shortcut *and* after the shortcut values are popped when using the shortcut with those values. The transformation when adding the shortcut was intentionally implemented mostly for file arguments, so that if you use a relative path for a file argument when creating your shortcut, it will still work with the same file when executing your shortcut from another directory. The second transformation wasn't intentionally added, but removing it requires multiple isolated types to know the inner workings of each other (mainly `ShorcutNode`, `Argument`, `Flag`, and `Input`). That makes all of those implementations more closely tied together and less independent and robust which is why there will not be work done to remove/fix the second transformation occurrence.

func SimpleExecutableProcessor

func SimpleExecutableProcessor(sl ...string) command.Processor

SimpleExecutableProcessor returns a `command.Processor` that adds to the command's `Executable`.

func SimpleProcessor

SimpleProcessor creates a `command.Processor` from execution and completion functions.

func Stat

func Stat(name string) (os.FileInfo, error)

Stat runs os.Stat on the provided file and returns (nil, nil) if the file does not exist.

func StaticCLI

func StaticCLI(name string, commands ...string) *staticCLI

StaticCLI returns a static CLI.

func StaticCLIs

func StaticCLIs(m map[string][]string) []*staticCLI

StaticCLIs returns a set of static CLIs.

func StringListListProcessor

func StringListListProcessor(name, desc, breakSymbol string, minN, optionalN int, opts ...ArgumentOption[[]string]) command.Processor

StringListListProcessor parses a two-dimensional slice of strings, with each slice being separated by `breakSymbol`

func StubRuntimeCaller

func StubRuntimeCaller(t *testing.T, s string, ok bool)

func SuperSimpleProcessor

func SuperSimpleProcessor(f func(*command.Input, *command.Data) error) command.Processor

SuperSimpleProcessor returns a processor from a single function that is run in both the execution and completion contexts.

func UnsetEnvVarProcessor

func UnsetEnvVarProcessor(envVar string) command.Processor

UnsetEnvVarProcessor returns a `command.Processor` that unsets the environment variable.

Types

type Argument

type Argument[T any] struct {
	// contains filtered or unexported fields
}

Argument is a type that implements `command.Processor`. It can be created via `Arg[T]` and `ListArg[T]` functions.

func Arg

func Arg[T any](name, desc string, opts ...ArgumentOption[T]) *Argument[T]

Arg creates an argument `command.Processor` that requires exactly one input.

func BoolArg

func BoolArg(name, desc string) *Argument[bool]

BoolArg creates a boolean argument.

func FileArgument

func FileArgument(argName, desc string, opts ...ArgumentOption[string]) *Argument[string]

FileArgument creates an `Argument` processor for a file object. The `Argument` returned by this function only relates to existing files (for execution and completion). For more granular control of the specifics, make your own `Arg(...)` with file-relevant `ArgumentOptions` (such as `FileCompleter`, `FileExists`, `IsDir`, `FileTransformer`, etc.)

func FileListArgument

func FileListArgument(argName, desc string, minN, optionalN int, opts ...ArgumentOption[[]string]) *Argument[[]string]

FileListArgument creates an `ArgList` node for file objects.

func ListArg

func ListArg[T any](name, desc string, minN, optionalN int, opts ...ArgumentOption[[]T]) *Argument[[]T]

ListArg creates a list argument that requires at least `minN` arguments and at most `minN`+`optionalN` arguments. Use UnboundedList for `optionalN` to allow an unlimited number of arguments.

func MenuArg[T comparable](name, desc string, choices ...T) *Argument[T]

MenuArg returns an `Arg` that is required to be one of the provided choices.

func OptionalArg

func OptionalArg[T any](name, desc string, opts ...ArgumentOption[T]) *Argument[T]

OptionalArg creates an argument `command.Processor` that accepts zero or one input arguments.

func (*Argument[T]) AddOptions

func (an *Argument[T]) AddOptions(opts ...ArgumentOption[T]) *Argument[T]

AddOptions adds options to an `Argument`. Although chaining isn't conventional in go, it is done here because args are usually declared as package-level variables.

func (*Argument[T]) Complete

func (an *Argument[T]) Complete(input *command.Input, data *command.Data) (*command.Completion, error)

Complete fulfills the `command.Processor` interface for `Argument`.

func (*Argument[T]) Desc

func (an *Argument[T]) Desc() string

Desc returns the description of the argument.

func (*Argument[T]) Execute

func (an *Argument[T]) Execute(i *command.Input, o command.Output, data *command.Data, eData *command.ExecuteData) error

Execute fulfills the `command.Processor` interface for `Argument`.

func (*Argument[T]) Get

func (an *Argument[T]) Get(data *command.Data) T

Get fetches the `Argument`'s value from the `command.Data` object.

func (*Argument[T]) GetOrDefault

func (an *Argument[T]) GetOrDefault(data *command.Data, dflt T) T

GetOrDefault fetches the `Argument`'s value from the `command.Data` object, or returns the `dflt` value provided if the `Argument` has not been set.

func (*Argument[T]) GetOrDefaultFunc

func (an *Argument[T]) GetOrDefaultFunc(data *command.Data, dfltFunc func(*command.Data) (T, error)) (T, error)

GetOrDefaultFunc fetches the `Argument`'s value from the `command.Data` object, or returns the `dflt` value provided if the `Argument` has not been set.

func (*Argument[T]) Name

func (an *Argument[T]) Name() string

Name returns the name of the argument.

func (*Argument[T]) Provided

func (an *Argument[T]) Provided(data *command.Data) bool

Provided returns whether or not the argument has been set in `command.Data`.

func (*Argument[T]) Set

func (an *Argument[T]) Set(v T, data *command.Data)

Set sets the argument key in the given `command.Data` object.

func (*Argument[T]) Usage

func (an *Argument[T]) Usage(i *command.Input, d *command.Data, u *command.Usage) error

command.Usage adds the command info to the provided `command.Usage` object.

type ArgumentOption

type ArgumentOption[T any] interface {
	// contains filtered or unexported methods
}

ArgumentOption is an interface for modifying `Argument` objects.

func Default

func Default[T any](v T) ArgumentOption[T]

Default is an `ArgumentOption` that sets a default value for an `Arg` node. Note, this package explicitly does not support a `DefaultFunc` `ArgumentOption`. Instead, use the `Argument.GetOrDefaultFunc` method inside of your `Node`'s executor logic.

func HiddenArg

func HiddenArg[T any]() ArgumentOption[T]

HiddenArg is an `ArgumentOption` that hides an argument from a command's usage text.

func ShortcutOpt

func ShortcutOpt[T any](name string, ac ShortcutCLI) ArgumentOption[T]

ShortcutOpt is an `ArgumentOption` that checks for shortcut substitution.

type BranchNode

type BranchNode struct {
	// Branches is a map from branching argument to `command.Node` that should be
	// executed if that branching argument is provided.
	Branches map[string]command.Node
	// Synonyms are synonyms for branching arguments.
	Synonyms map[string]string
	// Default is the `command.Node` that should be executed if the branching argument
	// does not match of any of the branches.
	Default command.Node
	// BranchCompletions is whether or not branch arguments should be completed
	// or if the completions from the Default `command.Node` should be used.
	// This is only relevant when the branching argument is the argument
	// being completed. Otherwise, this node is executed as normal.
	DefaultCompletion bool
	// BranchUsageOrder allows you to set the order for branch usage docs.
	// If this is nil, then branches are sorted in alphabetical order.
	// If this is an empty list, then no branch usage is shown.
	BranchUsageOrder []string
	// contains filtered or unexported fields
}

BranchNode implements a node that branches on specific string arguments. If the argument does not match any branch, then the `Default` node is traversed.

func (*BranchNode) Complete

func (bn *BranchNode) Complete(input *command.Input, data *command.Data) (*command.Completion, error)

func (*BranchNode) Execute

func (bn *BranchNode) Execute(input *command.Input, output command.Output, data *command.Data, eData *command.ExecuteData) error

func (*BranchNode) IsBranch

func (bn *BranchNode) IsBranch(s string) bool

IsBranch returns whether or not the provided string is a branching value.

func (*BranchNode) Next

func (bn *BranchNode) Next(input *command.Input, data *command.Data) (command.Node, error)

func (*BranchNode) Usage

func (bn *BranchNode) Usage(input *command.Input, data *command.Data, u *command.Usage) error

func (*BranchNode) UsageNext

func (bn *BranchNode) UsageNext(input *command.Input, data *command.Data) (command.Node, error)

type CachableCLI

type CachableCLI interface {
	// GetCache returns a map from cache name to the last commands run for the CLI.
	Cache() map[string][][]string
	// MarkChanged marks the CLI as changed.
	MarkChanged()
}

CachableCLI is an interface for CLIs that can store cached executions.

type CacheOption

type CacheOption interface {
	// contains filtered or unexported methods
}

CacheOption is an option interface for modifying `CacheNode` objects.

func CacheHistory

func CacheHistory(n int) CacheOption

CacheHistory is a `CacheOption` for specifying the number of command executions that should be saved.

type Completer

type Completer[T any] interface {
	Complete(T, *command.Data) (*command.Completion, error)
	// contains filtered or unexported methods
}

Completer is an autocompletion object that can be used as an `ArgumentOption`.

func AsCompleter

func AsCompleter[T any](c *command.Completion) Completer[T]

AsCompleter converts the `command.Completion` object into a `Completer` interface. This function is useful for constructing simple completers. To create a simple list, for example: ```go &command.Completion{Suggestions: []{"abc", "def", ...}}.AsCompleter ```

func BoolCompleter

func BoolCompleter() Completer[bool]

BoolCompleter is a completer for all boolean strings.

func CompleterFromFunc

func CompleterFromFunc[T any](f func(T, *command.Data) (*command.Completion, error)) Completer[T]

CompleterFromFunc returns a `Completer` object from the provided function.

func CompleterList

func CompleterList[T any](c Completer[T]) Completer[[]T]

CompleterList changes a single arg completer (`Completer[T]`) into a list arg completer (`Completer[[]T]`).

func CompleterWithOpts

func CompleterWithOpts[T any](cr Completer[T], cn *command.Completion) Completer[T]

CompleterWithOpts sets the relevant options in the `command.Completion` object returned by the `Completer`.

func DeferredCompleter

func DeferredCompleter[T any](graph command.Node, completer Completer[T]) Completer[T]

DeferredCompleter returns an argument/flag `Completer` that defers completion until after the provided graph is run. See the `DeferredCompletion` object for more info.

func ShellCommandCompleter

func ShellCommandCompleter[T any](name string, args ...string) Completer[T]

ShellCommandCompleter creates a completer object that completes a command graph with the output from the provided shell command.

func ShellCommandCompleterWithOpts

func ShellCommandCompleterWithOpts[T any](opts *command.Completion, name string, args ...string) Completer[T]

ShellCommandCompleterWithOpts creates a completer object that completes a command graph with the output from the provided command info.

func SimpleCompleter

func SimpleCompleter[T any](s ...string) Completer[T]

SimpleCompleter returns a completer that suggests the provided strings for command autocompletion.

func SimpleDistinctCompleter

func SimpleDistinctCompleter[T any](s ...string) Completer[T]

SimpleDistinctCompleter returns a completer that distinctly suggests the provided strings for command autocompletion.

type Complexecute

type Complexecute[T any] struct {
	// Lenient indicates whether a no-match should result in error or not.
	// Default behavior (false) means that an error will be thrown if the completion
	// argument doesn't exactly match one of the completion values and if the number
	// of completion suggestions isn't exactly one.
	Lenient bool
}

Complexecute (Complete for Execute) is an arg option for arg execution. If a command execution is run, then the last value for this arg will be completed using its `Complete` logic. Exactly one suggestion must be returned.

The type parameter is needed because it implements `ArgumentOption[T]`.

type CustomSetter

type CustomSetter[T any] struct {
	F func(T, *command.Data)
}

CustomSetter is an `ArgumentOption` to specify a custom setting function when setting argument data.

type EchoExecuteDataProcessor

type EchoExecuteDataProcessor struct {
	// Stderr is whether or not the output should be written to Stderr instead.
	Stderr bool
	// Format
	Format string
}

EchoExecuteDataProcessor is a `command.Processor` that outputs the current command.ExecuteData contents.

func EchoExecuteData

func EchoExecuteData() *EchoExecuteDataProcessor

EchoExecuteData returns a `command.Processor` that sends the `command.ExecuteData` contents to stdout.

func (*EchoExecuteDataProcessor) Complete

func (*EchoExecuteDataProcessor) Execute

func (*EchoExecuteDataProcessor) Usage

type ExecutorProcessor

type ExecutorProcessor struct {
	F func(command.Output, *command.Data) error
}

ExecuteErrNode creates a simple execution node from the provided error-able function.

func (*ExecutorProcessor) Complete

func (*ExecutorProcessor) Execute

func (*ExecutorProcessor) Usage

type FileCompleter

type FileCompleter[T any] struct {
	// Regexp is the regexp that all suggested files must satisfy.
	Regexp *regexp.Regexp
	// Directory is the directory in which to search for files.
	Directory string
	// Distinct is whether or not each argument has to be unique.
	// Separate from command.Completion.Distinct because file completion
	// does more complicated custom logic (like only comparing
	// base names even though other arguments may have folder paths too).
	Distinct bool
	// FileTypes is the set of file suffixes to allow.
	FileTypes []string
	// IgnoreFiles indicates whether we should only consider directories.
	IgnoreFiles bool
	// IgnoreDirectories indicates whether we should only consider files.
	IgnoreDirectories bool
	// IgnoreFunc is a function that indicates whether a suggestion should be ignored.
	IgnoreFunc func(fullPath string, basename string, data *command.Data) bool
	// ExcludePwd is whether or not the current working directory path should be excluded
	// from completions.
	ExcludePwd bool
	// MaxDepth is the maximum depth for files allowed. If less than or equal to zero,
	// then no limit is applied.
	MaxDepth int
}

FileCompleter is a `Completer` implementer specifically for file args.

func (*FileCompleter[T]) Complete

func (ff *FileCompleter[T]) Complete(value T, data *command.Data) (*command.Completion, error)

Complete creates a `command.Completion` object with the relevant set of files.

type FlagInterface

type FlagInterface interface {
	// Name is the name of the flag. "--name" is the flags indicator
	Name() string
	// Desc is the description of the flag.
	Desc() string
	// ShortName indicates the shorthand version of the flag. "-s" is the short hand flag indicator.
	ShortName() rune
	// command.Processor returns a node `command.Processor` that processes arguments after the flag indicator.
	Processor() command.Processor
	// FlagUsage runs the usage command for the flag
	FlagUsage(*command.Data, *command.Usage) error

	// Options returns the set of additional options for this flag.
	// Returning a separate type (rather than enumerating functions here)
	// allows us to update the options without breaking existing code.
	Options() *FlagOptions
}

FlagInterface defines a flag argument that is parsed regardless of it's position in the provided command line arguments.

type FlagOptions

type FlagOptions struct {
	// Combinable indicates whether or not the short flag can be combined
	// with other flags (`-qwer` = `-q -w -e -r`, for example).
	// When used as a combinable flag, the flag will be evaluated with
	// an empty `command.Input` object.
	Combinable bool
	// AllowsMultiple returns whether or not the flag can be provided multiple times.
	AllowsMultiple bool
	// ProcessMissing processes the flag when it is not provided
	ProcessMissing func(*command.Data) error
	// PostProcess runs after the entire flag processor has been processed.
	PostProcess func(*command.Input, command.Output, *command.Data, *command.ExecuteData) error
}

FlagOptions contains optional data for flags

type FlagWithType

type FlagWithType[T any] interface {
	FlagInterface
	// Get returns the flags value from a `command.Data` object.
	Get(*command.Data) T
	// GetOrDefault returns the flags value from a `command.Data` object, if the flag was set.
	// Otherwise, it returns the provided input.
	GetOrDefault(*command.Data, T) T
	// Provided returns whether or not the flag was provided
	Provided(*command.Data) bool

	// AddOptions adds options to a `FlagWithType`. Although chaining isn't
	// conventional in go, it is done here because flags are usually declared as
	// package-level variables.
	AddOptions(...ArgumentOption[T]) FlagWithType[T]
}

func BoolFlag

func BoolFlag(name string, shortName rune, desc string) FlagWithType[bool]

BoolFlag creates a `FlagInterface` for a boolean argument.

func Flag

func Flag[T any](name string, shortName rune, desc string, opts ...ArgumentOption[T]) FlagWithType[T]

Flag creates a `FlagInterface` from argument info.

func ItemizedListFlag

func ItemizedListFlag[T any](name string, shortName rune, desc string, opts ...ArgumentOption[[]T]) FlagWithType[[]T]

ItemizedListFlag creates a flag that can be set with separate flags (e.g. `cmd -i value-one -i value-two -b other-flag -i value-three`).

func ListFlag

func ListFlag[T any](name string, shortName rune, desc string, minN, optionalN int, opts ...ArgumentOption[[]T]) FlagWithType[[]T]

ListFlag creates a `FlagInterface` from list argument info.

func MenuFlag[T comparable](name string, shortName rune, desc string, choices ...T) FlagWithType[T]

MenuFlag returns an `Arg` that is required to be one of the provided choices.

func OptionalFlag

func OptionalFlag[T any](name string, shortName rune, desc string, defaultValue T, opts ...ArgumentOption[T]) FlagWithType[T]

OptionalFlag is a flag that can accept an optional parameter. Unlike `OptionalArg`, it actually has three different outcomes: Example with `OptionalFlag[string]("optStr", 'o', "description", "default-value")` 1. `Args=["--optStr"]`: The flag's value is set to "default-value" in data. 2. `Args=[]`: The flag's value isn't set (or is set to commander.Default(...) option if provided). 3. `Args=["--optStr", "custom-value"]`: The flag's value is set to "custom-value" in data.

type GetProcessor

type GetProcessor[T any] struct {
	command.Processor
	Name string
}

GetProcessor is a simple interface that extends the `command.Processor` interface and allows users to use a single object both as a command.Processor and to retrieve data (similar to the `Arg` and `Flag` types).

func EnvArg

func EnvArg(name string) *GetProcessor[string]

EnvArg loads the provided environment variable's value into `command.Data`. The provided `name` is also used as the `command.Data` key.

func RuntimeCaller

func RuntimeCaller() *GetProcessor[string]

RuntimeCaller is a `GetProcessor` that retrieves the filepath of the file that

func (*GetProcessor[T]) Get

func (gp *GetProcessor[T]) Get(d *command.Data) T

Get returns the value, if it has been set in `command.Data`; panics otherwise. Use `GetProcessor.Provided(*command.Data)` before calling this when it is not guaranteed to have been set.

func (*GetProcessor[T]) Provided

func (gp *GetProcessor[T]) Provided(d *command.Data) bool

Provided returns whether or not the argument has been set in `command.Data`.

type Lengthable

type Lengthable[T any] interface {
	string | []T
}

type ListBreaker

type ListBreaker[T any] struct {
	// Validators is the list of validators
	Validators []*ValidatorOption[T]
	// Discard is whether the culprit character should be removed
	Discard bool
	// UsageFunc modifies the usage doc
	UsageFunc func(*command.Data, *command.Usage) error
}

ListBreaker is a type that implements `command.InputBreaker` as well as `ArgumentOtion[T]`.

func ListUntil

func ListUntil[T any](validators ...*ValidatorOption[T]) *ListBreaker[[]T]

ListUntil returns a `ListBreaker` node that breaks when any of the provided `ValidatorOptions` are not satisfied.

func ListUntilSymbol

func ListUntilSymbol[T comparable](symbol T) *ListBreaker[[]T]

ListUntilSymbol returns an unbounded list node that ends when a specific symbol is parsed.

func (*ListBreaker[T]) Break

func (lb *ListBreaker[T]) Break(s string, d *command.Data) bool

func (*ListBreaker[T]) DiscardBreak

func (lb *ListBreaker[T]) DiscardBreak(s string, d *command.Data) bool

func (*ListBreaker[T]) Usage

func (lb *ListBreaker[T]) Usage(d *command.Data, u *command.Usage) error

command.Usage updates the provided `command.Usage` object.

func (*ListBreaker[T]) Validate

func (lb *ListBreaker[T]) Validate(t T, d *command.Data) error

type MapFlargument

type MapFlargument[K constraints.Ordered, V any] struct {
	*Argument[K]
	// contains filtered or unexported fields
}

MapFlargument is an `Argument` (or `Flag` if included in a `FlagProcessor(...)`) that retrieves data from a provided map. Use the `MapArg` to construct it.

func MapArg

func MapArg[K constraints.Ordered, V any](name, desc string, m map[K]V, allowMissing bool) *MapFlargument[K, V]

MapArg returns a `command.Processor` that converts an input key into it's value.

func MapFlag

func MapFlag[K constraints.Ordered, V any](name string, shortName rune, desc string, m map[K]V, allowMissing bool) *MapFlargument[K, V]

MapFlag returns a `Flag` that converts an input key into it's value.

func (*MapFlargument[K, V]) AddOptions

func (man *MapFlargument[K, V]) AddOptions(opts ...ArgumentOption[V]) FlagWithType[V]

func (*MapFlargument[K, V]) FlagUsage

func (man *MapFlargument[K, V]) FlagUsage(d *command.Data, u *command.Usage) error

func (*MapFlargument[K, V]) Get

func (man *MapFlargument[K, V]) Get(d *command.Data) V

Get overrides the Arg.Get function to return V (rather than type K).

func (*MapFlargument[K, V]) GetKey

func (man *MapFlargument[K, V]) GetKey() K

GetKey returns the key that was set by the am

func (*MapFlargument[K, V]) GetOrDefault

func (man *MapFlargument[K, V]) GetOrDefault(d *command.Data, dflt V) V

GetOrDefault overrides the Arg.GetOrDefault function to return V (rather than type K).

func (*MapFlargument[K, V]) Hit

func (man *MapFlargument[K, V]) Hit() bool

Hit returns whether the key provided was actually present in the map.

func (*MapFlargument[K, V]) Options

func (man *MapFlargument[K, V]) Options() *FlagOptions

func (*MapFlargument[K, V]) Processor

func (man *MapFlargument[K, V]) Processor() command.Processor

func (*MapFlargument[K, V]) Provided

func (man *MapFlargument[K, V]) Provided(d *command.Data) bool

func (*MapFlargument[K, V]) ShortName

func (man *MapFlargument[K, V]) ShortName() rune

type MutableProcessor

type MutableProcessor[P command.Processor] struct {
	Processor *P
}

func NewMutableProcessor

func NewMutableProcessor[P command.Processor](p P) *MutableProcessor[P]

func (*MutableProcessor[P]) Complete

func (rp *MutableProcessor[P]) Complete(i *command.Input, d *command.Data) (*command.Completion, error)

func (*MutableProcessor[P]) Execute

func (*MutableProcessor[P]) Usage

func (rp *MutableProcessor[P]) Usage(i *command.Input, d *command.Data, u *command.Usage) error

type ShellCommand

type ShellCommand[T any] struct {
	// ArgName is the argument name to use if stored in `command.Data`.
	ArgName string
	// Command is the command to forward to `exec.Command`.
	CommandName string
	// Args are the args to forward to `exec.Command`.
	Args []string
	// Desc is the description of this shell command. Used for the CLI usage doc.
	Desc string
	// Dir is the directory in which to run the command. Defaults to the current directory.
	Dir string
	// Stdin is the `io.Reader` to forward for use in `exec.Command`
	Stdin io.Reader

	// Validators contains a list of validators to run with the shell command output.
	Validators []*ValidatorOption[T]
	// HideStderr is whether or not the stderr of the command should be sent to actual stderr or not.
	HideStderr bool
	// ForwardStdout indicates whether the output should also be displayed (originally, it is just parsed into a value).
	ForwardStdout bool
	// DontRunOnComplete indicates whether or not the shell command should be run when we are completing a command arg.
	DontRunOnComplete bool
	// OutputStreamProcessor is a function that will be run with every item written to stdout.
	OutputStreamProcessor func(command.Output, *command.Data, []byte) error
	// EchoCommand, if true, forwards the command being run (with args) to Stdout.
	EchoCommand bool
	// contains filtered or unexported fields
}

ShellCommand can run the provided command `Contents` in the shell and stores the response as a value in data with the provided type and `ArgName`.

func (*ShellCommand[T]) Complete

func (bn *ShellCommand[T]) Complete(input *command.Input, data *command.Data) (*command.Completion, error)

Complete fulfills the `command.Processor` interface for `ShellCommand`.

func (*ShellCommand[T]) Execute

func (bn *ShellCommand[T]) Execute(input *command.Input, output command.Output, data *command.Data, eData *command.ExecuteData) error

Execute fulfills the `command.Processor` interface for `ShellCommand`.

func (*ShellCommand[T]) Get

func (bn *ShellCommand[T]) Get(d *command.Data) T

Get fetches the relevant shell output from the provided `command.Data` object.

func (*ShellCommand[T]) Name

func (bn *ShellCommand[T]) Name() string

Name returns the arg name of the `ShellCommand`

func (*ShellCommand[T]) Run

func (bn *ShellCommand[T]) Run(output command.Output, data *command.Data) (T, error)

Run runs the `ShellCommand` with the provided `command.Output` object.

func (*ShellCommand[T]) Usage

func (bn *ShellCommand[T]) Usage(i *command.Input, d *command.Data, u *command.Usage) error

command.Usage fulfills the `command.Processor` interface for `ShellCommand`.

type ShellCommandDataStringer

type ShellCommandDataStringer[T any] interface {
	ToString(d *command.Data) (string, error)
}

func CustomShellCommandDataStringer

func CustomShellCommandDataStringer[T any](f func(*command.Data) (string, error)) ShellCommandDataStringer[T]

func NewShellCommandDataStringer

func NewShellCommandDataStringer[T, A any](arg *Argument[A], delimiter string) ShellCommandDataStringer[T]

type ShortcutCLI

type ShortcutCLI interface {
	// ShortcutMap returns a map from "shortcut type" to "shortcut name" to an array of "shortcut expansion".
	// This structure easily allows for one CLI to have multiple shortcut commands.
	ShortcutMap() map[string]map[string][]string
	// MarkChanged is called when a change has been made to the shortcut map.
	MarkChanged()
}

ShortcutCLI is the interface required for integrating with shortcut nodes.

type SimpleEdge

type SimpleEdge struct {
	// N is the next `command.Node` to visit.
	N command.Node
}

SimpleEdge implements the `Edge` interface and points to the provided `command.Node`.

func (*SimpleEdge) Next

func (*SimpleEdge) UsageNext

func (se *SimpleEdge) UsageNext(input *command.Input, data *command.Data) (command.Node, error)

type SimpleNode

type SimpleNode struct {
	Processor command.Processor
	Edge      command.Edge
}

SimpleNode implements the `command.Node` interface from a provided `command.Processor` and `Edge`.

func (*SimpleNode) Complete

func (sn *SimpleNode) Complete(input *command.Input, data *command.Data) (*command.Completion, error)

func (*SimpleNode) Execute

func (sn *SimpleNode) Execute(input *command.Input, output command.Output, data *command.Data, exData *command.ExecuteData) error

func (*SimpleNode) Next

func (sn *SimpleNode) Next(i *command.Input, d *command.Data) (command.Node, error)

func (*SimpleNode) Usage

func (sn *SimpleNode) Usage(i *command.Input, d *command.Data, u *command.Usage) error

func (*SimpleNode) UsageNext

func (sn *SimpleNode) UsageNext(input *command.Input, data *command.Data) (command.Node, error)

type Transformer

type Transformer[T any] struct {
	F func(T, *command.Data) (T, error)
}

Transformer is an `ArgumentOption` that transforms an argument.

func FileTransformer

func FileTransformer() *Transformer[string]

FileTransformer returns a transformer that transforms a string into its full file-path.

func TransformerList

func TransformerList[T any](t *Transformer[T]) *Transformer[[]T]

TransformerList changes a single-arg transformer (`Transformer[T]`) to a list-arg transformer (`Transformer[[]T]`).

type ValidatorOption

type ValidatorOption[T any] struct {
	Validate func(T, *command.Data) error
	Usage    string
}

ValidatorOption is an `ArgumentOption` and `BashOption` for validating arguments.

func Between

func Between[T constraints.Ordered](start, end T, inclusive bool) *ValidatorOption[T]

Between [`ValidatorOption`] validates an argument is between two numbers.

func Contains

func Contains(s string) *ValidatorOption[string]

Contains [`ValidatorOption`] validates an argument contains the provided string.

func EQ

func EQ[T comparable](n T) *ValidatorOption[T]

EQ [`ValidatorOption`] validates an argument equals `n`.

func FileDoesNotExist

func FileDoesNotExist() *ValidatorOption[string]

FileDoesNotExist [`ValidatorOption`] validates the file or directory does not exist. This is useful when you need `Arguments` that create new files or directories.

func FileExists

func FileExists() *ValidatorOption[string]

FileExists [`ValidatorOption`] validates the file or directory exists.

func GT

func GT[T constraints.Ordered](n T) *ValidatorOption[T]

GT [`ValidatorOption`] validates an argument is greater than `n`.

func GTE

func GTE[T constraints.Ordered](n T) *ValidatorOption[T]

GTE [`ValidatorOption`] validates an argument is greater than or equal to `n`.

func InList

func InList[T comparable](choices ...T) *ValidatorOption[T]

InList [`ValidatorOption`] validates an argument is one of the provided choices.

func IsDir

func IsDir() *ValidatorOption[string]

IsDir [`ValidatorOption`] validates an argument is a directory.

func IsFile

func IsFile() *ValidatorOption[string]

IsFile [`ValidatorOption`] validates an argument is a file.

func IsRegex

func IsRegex() *ValidatorOption[string]

IsRegex [`ValidatorOption`] validates an argument is a valid regex.

func LT

func LT[T constraints.Ordered](n T) *ValidatorOption[T]

LT [`ValidatorOption`] validates an argument is less than `n`.

func LTE

func LTE[T constraints.Ordered](n T) *ValidatorOption[T]

LTE [`ValidatorOption`] validates an argument is less than or equal to `n`.

func Length

func Length[K any, T Lengthable[K]](length int) *ValidatorOption[T]

Length [`ValidatorOption`] validates an argument is exactly length.

func ListifyValidatorOption

func ListifyValidatorOption[T any](vo *ValidatorOption[T]) *ValidatorOption[[]T]

ListifyValidatorOption changes a single-arg validator (`ValidatorOption[T]`) to a list-arg validator (`ValidatorOption[[]T]`) for the same type. Note: we can't do this as a method because it causes an instantiation cycle: ValidatorOption[T] -> defines method `ValidatorOption[T].Listify() *ValidatorOption[[]T]` ValidatorOption[[]T] -> defines method `ValidatorOption[[]T].Listify() *ValidatorOption[[][]T]` etc.

func MatchesRegex

func MatchesRegex(pattern ...string) *ValidatorOption[string]

MatchesRegex [`ValidatorOption`] validates an argument matches the provided regexes.

func MaxLength

func MaxLength[K any, T Lengthable[K]](length int) *ValidatorOption[T]

MaxLength [`ValidatorOption`] validates an argument is at most `length` long.

func MinLength

func MinLength[K any, T Lengthable[K]](length int) *ValidatorOption[T]

MinLength [`ValidatorOption`] validates an argument is at least `length` long.

func NEQ

func NEQ[T comparable](n T) *ValidatorOption[T]

NEQ [`ValidatorOption`] validates an argument does not equal `n`.

func Negative

func Negative[T constraints.Ordered]() *ValidatorOption[T]

Negative [`ValidatorOption`] validates an argument is negative.

func NonNegative

func NonNegative[T constraints.Ordered]() *ValidatorOption[T]

NonNegative [`ValidatorOption`] validates an argument is non-negative.

func Not

func Not[T any](vo *ValidatorOption[T]) *ValidatorOption[T]

Not [`ValidatorOption`] inverts the provided validator.

func Positive

func Positive[T constraints.Ordered]() *ValidatorOption[T]

Positive [`ValidatorOption`] validates an argument is positive.

func (*ValidatorOption[T]) RunValidation

func (vo *ValidatorOption[T]) RunValidation(arg validatable, t T, d *command.Data) error

Jump to

Keyboard shortcuts

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