Documentation ¶
Index ¶
- Constants
- Variables
- func Autocomplete(n command.Node, compLine string, passthroughArgs []string, os command.OS) (*command.Autocompletion, error)
- func BoolValueFlag[T any](name string, shortName rune, desc string, trueValue T) *boolFlag[T]
- func BoolValuesFlag[T any](name string, shortName rune, desc string, trueValue, falseValue T) *boolFlag[T]
- func BranchSynonyms(m map[string][]string) map[string]string
- func CacheNode(name string, c CachableCLI, n command.Node, opts ...CacheOption) command.Node
- func ClosureProcessor(f func(i *command.Input, d *command.Data) command.Processor) command.Processor
- func CreateFile(name string, contents []string, ps fs.FileMode) error
- func DataTransformer[I, O any](key string, f func(I) (O, error)) command.Processor
- func DebugMode() bool
- func Debugf(o command.Output, s string, i ...interface{})
- func Description(desc string) command.Processor
- func Descriptionf(s string, a ...interface{}) command.Processor
- func EchoExecuteDataf(format string) command.Processor
- func ExecutableProcessor(f func(command.Output, *command.Data) ([]string, error)) command.Processor
- func Execute(n command.Node, input *command.Input, output command.Output, os command.OS) (*command.ExecuteData, error)
- func FileContents(name, desc string, opts ...ArgumentOption[string]) command.Processor
- func FileNumberInputTransformer(UpToIndexInclusive int) *command.InputTransformer
- func FlagProcessor(fs ...FlagInterface) *flagProcessor
- func FunctionWrap() command.Processor
- func If(p command.Processor, fn func(i *command.Input, d *command.Data) bool) command.Processor
- func IfData(dataArg string, p command.Processor) command.Processor
- func IfElse(t, f command.Processor, fn func(i *command.Input, d *command.Data) bool) command.Processor
- func IfElseData(dataArg string, t, f command.Processor) command.Processor
- func IsBranchingError(err error) bool
- func IsNotEnoughArgsError(err error) bool
- func IsUsageError(err error) bool
- func IsValidationError(err error) bool
- func NodeRepeater(n command.Node, minN, optionalN int) command.Processor
- func NotEnoughArgs(name string, req, got int) error
- func PrintlnProcessor(v string) command.Processor
- func Prompt(output command.Output, question string) chan string
- func ReadFile(name string) ([]string, error)
- func RunArgumentCompleter[T any](c Completer[T], value T, data *command.Data) (*command.Completion, error)
- func RunArgumentCompletion[T any](completion *command.Completion, value T, data *command.Data) (*command.Completion, error)
- func SerialNodes(ps ...command.Processor) command.Node
- func SetEnvVarProcessor(envVar, value string) command.Processor
- func SetupOutputContents(d *command.Data) ([]string, error)
- func SetupOutputFile(d *command.Data) string
- func SetupOutputString(d *command.Data) (string, error)
- func ShortcutNode(name string, sc ShortcutCLI, n command.Node) command.Node
- func SimpleExecutableProcessor(sl ...string) command.Processor
- func SimpleProcessor(...) command.Processor
- func Stat(name string) (os.FileInfo, error)
- func StaticCLI(name string, commands ...string) *staticCLI
- func StaticCLIs(m map[string][]string) []*staticCLI
- func StringListListProcessor(name, desc, breakSymbol string, minN, optionalN int, ...) command.Processor
- func StubRuntimeCaller(t *testing.T, s string, ok bool)
- func SuperSimpleProcessor(f func(*command.Input, *command.Data) error) command.Processor
- func UnsetEnvVarProcessor(envVar string) command.Processor
- type Argument
- func Arg[T any](name, desc string, opts ...ArgumentOption[T]) *Argument[T]
- func BoolArg(name, desc string) *Argument[bool]
- func FileArgument(argName, desc string, opts ...ArgumentOption[string]) *Argument[string]
- func FileListArgument(argName, desc string, minN, optionalN int, opts ...ArgumentOption[[]string]) *Argument[[]string]
- func ListArg[T any](name, desc string, minN, optionalN int, opts ...ArgumentOption[[]T]) *Argument[[]T]
- func MenuArg[T comparable](name, desc string, choices ...T) *Argument[T]
- func OptionalArg[T any](name, desc string, opts ...ArgumentOption[T]) *Argument[T]
- func (an *Argument[T]) AddOptions(opts ...ArgumentOption[T]) *Argument[T]
- func (an *Argument[T]) Complete(input *command.Input, data *command.Data) (*command.Completion, error)
- func (an *Argument[T]) Desc() string
- func (an *Argument[T]) Execute(i *command.Input, o command.Output, data *command.Data, ...) error
- func (an *Argument[T]) Get(data *command.Data) T
- func (an *Argument[T]) GetOrDefault(data *command.Data, dflt T) T
- func (an *Argument[T]) GetOrDefaultFunc(data *command.Data, dfltFunc func(*command.Data) (T, error)) (T, error)
- func (an *Argument[T]) Name() string
- func (an *Argument[T]) Provided(data *command.Data) bool
- func (an *Argument[T]) Set(v T, data *command.Data)
- func (an *Argument[T]) Usage(i *command.Input, d *command.Data, u *command.Usage) error
- type ArgumentOption
- type BranchNode
- func (bn *BranchNode) Complete(input *command.Input, data *command.Data) (*command.Completion, error)
- func (bn *BranchNode) Execute(input *command.Input, output command.Output, data *command.Data, ...) error
- func (bn *BranchNode) IsBranch(s string) bool
- func (bn *BranchNode) Next(input *command.Input, data *command.Data) (command.Node, error)
- func (bn *BranchNode) Usage(input *command.Input, data *command.Data, u *command.Usage) error
- func (bn *BranchNode) UsageNext(input *command.Input, data *command.Data) (command.Node, error)
- type CachableCLI
- type CacheOption
- type Completer
- func AsCompleter[T any](c *command.Completion) Completer[T]
- func BoolCompleter() Completer[bool]
- func CompleterFromFunc[T any](f func(T, *command.Data) (*command.Completion, error)) Completer[T]
- func CompleterList[T any](c Completer[T]) Completer[[]T]
- func CompleterWithOpts[T any](cr Completer[T], cn *command.Completion) Completer[T]
- func DeferredCompleter[T any](graph command.Node, completer Completer[T]) Completer[T]
- func ShellCommandCompleter[T any](name string, args ...string) Completer[T]
- func ShellCommandCompleterWithOpts[T any](opts *command.Completion, name string, args ...string) Completer[T]
- func SimpleCompleter[T any](s ...string) Completer[T]
- func SimpleDistinctCompleter[T any](s ...string) Completer[T]
- type Complexecute
- type CustomSetter
- type EchoExecuteDataProcessor
- func (e *EchoExecuteDataProcessor) Complete(*command.Input, *command.Data) (*command.Completion, error)
- func (e *EchoExecuteDataProcessor) Execute(_ *command.Input, o command.Output, _ *command.Data, ed *command.ExecuteData) error
- func (e *EchoExecuteDataProcessor) Usage(i *command.Input, d *command.Data, u *command.Usage) error
- type EnvArg
- func (ea *EnvArg) Complete(i *command.Input, d *command.Data) (*command.Completion, error)
- func (ea *EnvArg) Execute(i *command.Input, o command.Output, d *command.Data, ed *command.ExecuteData) error
- func (ea *EnvArg) Get(d *command.Data) string
- func (ea *EnvArg) Provided(d *command.Data) bool
- func (ea *EnvArg) Usage(*command.Input, *command.Data, *command.Usage) error
- type ExecutorProcessor
- type FileCompleter
- type FlagInterface
- type FlagOptions
- type FlagWithType
- func BoolFlag(name string, shortName rune, desc string) FlagWithType[bool]
- func Flag[T any](name string, shortName rune, desc string, opts ...ArgumentOption[T]) FlagWithType[T]
- func ItemizedListFlag[T any](name string, shortName rune, desc string, opts ...ArgumentOption[[]T]) FlagWithType[[]T]
- func ListFlag[T any](name string, shortName rune, desc string, minN, optionalN int, ...) FlagWithType[[]T]
- func MenuFlag[T comparable](name string, shortName rune, desc string, choices ...T) FlagWithType[T]
- func OptionalFlag[T any](name string, shortName rune, desc string, defaultValue T, ...) FlagWithType[T]
- type GetProcessor
- type Lengthable
- type ListBreaker
- type MapFlargument
- func (man *MapFlargument[K, V]) AddOptions(opts ...ArgumentOption[V]) FlagWithType[V]
- func (man *MapFlargument[K, V]) FlagUsage(d *command.Data, u *command.Usage) error
- func (man *MapFlargument[K, V]) Get(d *command.Data) V
- func (man *MapFlargument[K, V]) GetKey() K
- func (man *MapFlargument[K, V]) GetOrDefault(d *command.Data, dflt V) V
- func (man *MapFlargument[K, V]) Hit() bool
- func (man *MapFlargument[K, V]) Options() *FlagOptions
- func (man *MapFlargument[K, V]) Processor() command.Processor
- func (man *MapFlargument[K, V]) Provided(d *command.Data) bool
- func (man *MapFlargument[K, V]) ShortName() rune
- type MutableProcessor
- func (rp *MutableProcessor[P]) Complete(i *command.Input, d *command.Data) (*command.Completion, error)
- func (rp *MutableProcessor[P]) Execute(i *command.Input, o command.Output, d *command.Data, ed *command.ExecuteData) error
- func (rp *MutableProcessor[P]) Usage(i *command.Input, d *command.Data, u *command.Usage) error
- type ShellCommand
- func (bn *ShellCommand[T]) Complete(input *command.Input, data *command.Data) (*command.Completion, error)
- func (bn *ShellCommand[T]) Execute(input *command.Input, output command.Output, data *command.Data, ...) error
- func (bn *ShellCommand[T]) Get(d *command.Data) T
- func (bn *ShellCommand[T]) Name() string
- func (bn *ShellCommand[T]) Run(output command.Output, data *command.Data) (T, error)
- func (bn *ShellCommand[T]) Usage(i *command.Input, d *command.Data, u *command.Usage) error
- type ShellCommandDataStringer
- type ShortcutCLI
- type SimpleEdge
- type SimpleNode
- func (sn *SimpleNode) Complete(input *command.Input, data *command.Data) (*command.Completion, error)
- func (sn *SimpleNode) Execute(input *command.Input, output command.Output, data *command.Data, ...) error
- func (sn *SimpleNode) Next(i *command.Input, d *command.Data) (command.Node, error)
- func (sn *SimpleNode) Usage(i *command.Input, d *command.Data, u *command.Usage) error
- func (sn *SimpleNode) UsageNext(input *command.Input, data *command.Data) (command.Node, error)
- type Transformer
- type ValidatorOption
- func Between[T constraints.Ordered](start, end T, inclusive bool) *ValidatorOption[T]
- func Contains(s string) *ValidatorOption[string]
- func EQ[T comparable](n T) *ValidatorOption[T]
- func FileDoesNotExist() *ValidatorOption[string]
- func FileExists() *ValidatorOption[string]
- func GT[T constraints.Ordered](n T) *ValidatorOption[T]
- func GTE[T constraints.Ordered](n T) *ValidatorOption[T]
- func InList[T comparable](choices ...T) *ValidatorOption[T]
- func IsDir() *ValidatorOption[string]
- func IsFile() *ValidatorOption[string]
- func IsRegex() *ValidatorOption[string]
- func LT[T constraints.Ordered](n T) *ValidatorOption[T]
- func LTE[T constraints.Ordered](n T) *ValidatorOption[T]
- func Length[K any, T Lengthable[K]](length int) *ValidatorOption[T]
- func ListifyValidatorOption[T any](vo *ValidatorOption[T]) *ValidatorOption[[]T]
- func MatchesRegex(pattern ...string) *ValidatorOption[string]
- func MaxLength[K any, T Lengthable[K]](length int) *ValidatorOption[T]
- func MinLength[K any, T Lengthable[K]](length int) *ValidatorOption[T]
- func NEQ[T comparable](n T) *ValidatorOption[T]
- func Negative[T constraints.Ordered]() *ValidatorOption[T]
- func NonNegative[T constraints.Ordered]() *ValidatorOption[T]
- func Not[T any](vo *ValidatorOption[T]) *ValidatorOption[T]
- func Positive[T constraints.Ordered]() *ValidatorOption[T]
Constants ¶
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 = "--" )
const (
DebugEnvVar = "COMMAND_CLI_DEBUG"
)
const (
// GetwdKey is the `command.Data` key used by `Getwd`.
GetwdKey = "GETWD"
)
const (
// RuntimeCallerKey is the `command.Data` key used by `RuntimeCaller`.
RuntimeCallerKey = "RUNTIME_CALLER"
)
Variables ¶
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]$") )
var (
CacheDefaultHistory = 100
)
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, } )
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]()) )
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 ¶
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 ¶
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 ClosureProcessor ¶
func ClosureProcessor(f func(i *command.Input, d *command.Data) command.Processor) command.Processor
ClosureProcessor returns a `command.Processor` that runs the processor returned by the provided function.
func CreateFile ¶
CreateFile creates a file from the provided string slice.
func DataTransformer ¶
DataTransformer transforms the value in command.Data under `key` using the provided function.
func Description ¶
Description creates a `command.Processor` that adds a command description to the usage text.
func Descriptionf ¶
Descriptionf is like `Description`, but with formatting options.
func EchoExecuteDataf ¶
EchoExecuteDataf returns a `command.Processor` that sends the `command.ExecuteData` contents to stdout with the provided format
func ExecutableProcessor ¶
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 ¶
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 ¶
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 ¶
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 ¶
IsBranchingError returns whether or not the provided error is a branching error.
func IsNotEnoughArgsError ¶
IsNotEnoughArgsError returns whether or not the provided error is a `NotEnoughArgs` error.
func IsUsageError ¶
IsUsageError returns whether or not the provided error is a usage-related error.
func IsValidationError ¶
IsValidationError returns whether or not the provided error is a validation error.
func NodeRepeater ¶
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 ¶
NotEnoughArgs returns a custom error for when not enough arguments are provided to the command.
func PrintlnProcessor ¶
PrintlnProcessor returns a `command.Processor` that runs `output.Stdoutln(v)`.
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 ¶
SerialNodes returns a graph that iterates serially over nodes with the provided `command.Processor` objects.
func SetEnvVarProcessor ¶
SetEnvVarProcessor returns a `command.Processor` that sets the environment variable to the provided value.
func SetupOutputContents ¶
SetupOutputString returns the file contents, as a string slice, of the setup file for the command.
func SetupOutputFile ¶
SetupOutputFile returns the name of the setup file for the command.
func SetupOutputString ¶
SetupOutputString returns the file contents, as a string, of the setup file for the command.
func ShortcutNode ¶
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 ¶
SimpleExecutableProcessor returns a `command.Processor` that adds to the command's `Executable`.
func SimpleProcessor ¶
func SimpleProcessor(e func(*command.Input, command.Output, *command.Data, *command.ExecuteData) error, c func(*command.Input, *command.Data) (*command.Completion, error)) command.Processor
SimpleProcessor creates a `command.Processor` from execution and completion functions.
func Stat ¶
Stat runs os.Stat on the provided file and returns (nil, nil) if the file does not exist.
func StaticCLIs ¶
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 SuperSimpleProcessor ¶
SuperSimpleProcessor returns a processor from a single function that is run in both the execution and completion contexts.
func UnsetEnvVarProcessor ¶
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 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 ¶
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]) 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]) GetOrDefault ¶
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]) Provided ¶
Provided returns whether or not the argument has been set in `command.Data`.
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 // DefaultCompletion is whether or not the Default `command.Node` completion is run or // if branch argument values are used for completion suggestions. // // Note: this is only relevant when the branching argument is the argument // being completed. If a later arg is being completed, then the Default completion // is always run. 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.
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 ¶
BoolCompleter is a completer for all boolean strings.
func CompleterFromFunc ¶
CompleterFromFunc returns a `Completer` object from the provided function.
func CompleterList ¶
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 ¶
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 ¶
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 ¶
SimpleCompleter returns a completer that suggests the provided strings for command autocompletion.
func SimpleDistinctCompleter ¶
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 ¶
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 (e *EchoExecuteDataProcessor) Complete(*command.Input, *command.Data) (*command.Completion, error)
type EnvArg ¶
type EnvArg struct { // Name is the name of the environment variable Name string // Optional indiciates whether a value is required to be set. An error will be // returned if this is false and no environment variable value exists. Optional bool // Validators are the validators to run on the on the environment variable's value. These are not // executed if `Optional` is true and the environment variable does not exist. // Note that these run after the `Transformers` Validators []*ValidatorOption[string] // Transformers are the transformations to run on the environment variable's value. These are not // executed if `Optional` is true and the environment variable does not exist. // Note that these run prior to the `Validators` Transformers []*Transformer[string] // DontRunOnComplete indicates whether or not this `command.Processor` will execute when running argument completion DontRunOnComplete bool }
EnvArg is a `command.Processor` that loads an environment variable's value into `command.Data`. The provided `name` is also used as the `command.Data` key. It results in an error if the environment variable is not set or if any of the validators fails.
type ExecutorProcessor ¶
ExecuteErrNode creates a simple execution node from the provided error-able function.
func (*ExecutorProcessor) Complete ¶
func (e *ExecutorProcessor) Complete(*command.Input, *command.Data) (*command.Completion, error)
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 ¶
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 ¶
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 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.
type Lengthable ¶
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]) DiscardBreak ¶
func (lb *ListBreaker[T]) DiscardBreak(s string, d *command.Data) bool
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]) 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 ¶
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)
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 // Env is the additional environment variables to include Env []string // 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`
type ShellCommandDataStringer ¶
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 ¶
SimpleEdge implements the `Edge` interface and points to the provided `command.Node`.
type SimpleNode ¶
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
type Transformer ¶
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 ¶
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
Source Files ¶
- arg.go
- autocomplete.go
- branch_node.go
- cache.go
- completer.go
- conditional.go
- data_transformer.go
- debug.go
- description.go
- echo.go
- error.go
- execute.go
- executor.go
- file_functions.go
- flag.go
- get_processor.go
- list_breaker.go
- map_arg.go
- menu.go
- mutable_processor.go
- node_repeater.go
- option.go
- osenv.go
- prompt.go
- runtime_caller.go
- serial_nodes.go
- setup.go
- shell_command_node.go
- shortcut.go
- simple_node.go
- simple_processor.go
- static_cli.go
- transformer.go
- validator.go
- working_directory.go