Documentation ¶
Index ¶
- Variables
- func Capture(opts *Options) (any, error)
- func CaptureExitSignal(f func())
- func DisplayEntryHelp(opts *Options, entry *Entry) error
- func DisplayHelp(opts *Options, registry Registry, help string) error
- func DisplayRootHelp(opts *Options, registry Registry)
- func Execute(opts *Options) error
- func Get(name string) any
- func GetArg(name string, defaultValue string, args *[]string, argPrefix string, flag bool) string
- func Normalize(x string) string
- func ParseType(t reflect.Type, s string) (any, error)
- func Peek(opts *Options) any
- func Register(entry Entry)
- func SetString(value reflect.Value, s string) error
- func Unmarshal(opts *Options, v any) error
- type ArgValue
- type CaptureImporter
- type Dynamic
- type Entry
- type Executable
- type Flags
- type HasChoices
- type Instance
- type Match
- func MatchAll[T constraints.Integer](test T) Match[T]
- func MatchAnd[T constraints.Integer](ands ...Match[T]) Match[T]
- func MatchAny[T constraints.Integer](test T) Match[T]
- func MatchEmpty[T constraints.Integer]() Match[T]
- func MatchExact[T constraints.Integer](test T) Match[T]
- func MatchNone[T constraints.Integer](test T) Match[T]
- func MatchNot[T constraints.Integer](not Match[T]) Match[T]
- func MatchOnly[T constraints.Integer](test T) Match[T]
- func MatchOr[T constraints.Integer](ors ...Match[T]) Match[T]
- type Options
- func (opts *Options) CanPrompt() bool
- func (opts *Options) CaptureExitSignal()
- func (opts *Options) ClearArgs() *Options
- func (opts *Options) ClearFiles() *Options
- func (opts *Options) Cli() *Options
- func (opts *Options) Close() error
- func (opts *Options) Context() context.Context
- func (opts *Options) Printf(format string, args ...any) error
- func (opts *Options) Program() *Options
- func (opts *Options) Prompt(options PromptOptions) (any, error)
- func (opts *Options) RestorArgs() *Options
- func (opts *Options) Std() *Options
- func (opts *Options) WithArgs(args []string) *Options
- func (opts *Options) WithContext(ctx context.Context) *Options
- func (opts *Options) WithFiles(in *os.File, out *os.File) *Options
- type PromptChoice
- type PromptChoices
- type PromptContext
- type PromptCustom
- type PromptOnceOptions
- type PromptOptions
- type PromptStatus
- type PromptValue
- type Property
- func (prop Property) CanFromArgs() bool
- func (prop Property) CanLoad() bool
- func (prop Property) CanPrompt() bool
- func (prop Property) ConcreteType() reflect.Type
- func (prop Property) ConcreteValue() any
- func (prop *Property) FromArgs(opts *Options) error
- func (prop *Property) GetPromptChoices(opts *Options) PromptChoices
- func (prop Property) HasCustomPromptText() bool
- func (prop Property) IsArray() bool
- func (prop Property) IsBool() bool
- func (prop Property) IsDefault() bool
- func (prop Property) IsIgnored() bool
- func (prop Property) IsKind(kind reflect.Kind) bool
- func (prop Property) IsKinds(kinds map[reflect.Kind]struct{}) bool
- func (prop Property) IsMap() bool
- func (prop Property) IsNil() bool
- func (prop Property) IsOptional() bool
- func (prop Property) IsSimple() bool
- func (prop Property) IsSlice() bool
- func (prop Property) IsStruct() bool
- func (prop *Property) Load(opts *Options) error
- func (prop *Property) Prompt(opts *Options) error
- func (prop *Property) Set(opts *Options, input string, addFlags PropertyFlags) error
- func (prop Property) Size() float64
- func (prop Property) Validate(opts *Options) error
- type PropertyFlags
- type Registry
- func (r *Registry) Add(entry Entry)
- func (r Registry) Capture(opts *Options) (any, error)
- func (r Registry) Entries() []*Entry
- func (r Registry) EntriesAll() []Entry
- func (r Registry) EntryFor(namePartial string) *Entry
- func (r Registry) EntryForDeep(namePartials []string) (*Entry, int)
- func (r Registry) Execute(opts *Options) error
- func (r Registry) ExecuteReturn(opts *Options) (any, error)
- func (r Registry) Get(namePartial string) any
- func (r Registry) GetDeep(namePartials []string) (any, int)
- func (r Registry) Has(namePartial string) bool
- func (r Registry) HasDeep(namePartials []string) bool
- func (r Registry) IsEmpty() bool
- func (r Registry) Matches(namePartial string) []*Entry
- func (r Registry) Peek(opts *Options) any
- type Validator
Constants ¶
This section is empty.
Variables ¶
var CaptureImports = map[string]CaptureImporter{ "json": func(data []byte, target any) error { return json.Unmarshal(data, target) }, "yaml": func(data []byte, target any) error { return yaml.Unmarshal(data, target) }, "xml": func(data []byte, target any) error { return xml.Unmarshal(data, target) }, }
var ErrDiscard = errors.New("DISCARD")
The error returned when the user requested to discard the current value being prompted for a complex type.
var ErrInvalidConversion = errors.New("invalid conversion")
An error returned when input is given to prompt choices and no choices could be determined.
var ErrInvalidFormat = errors.New("invalid format")
An error returned when we failed setting a value from a given string.
var ErrInvalidUnmarshalError = errors.New("non-pointer passed to Unmarshal")
An error returned from Unmarshal if nil or a non-pointer is passed to Unmarshal.
var ErrNoCommand = errors.New("no command given, try running with --help")
An error returned when no command to capture/execute is given in the arguments.
var ErrNoPrompt = errors.New("NOPROMPT")
The error returned when no valid value could be gotten from prompt.
var ErrQuit = errors.New("QUIT")
The error returned when the user requested to quit prompting.
var ErrRegexFailed = errors.New("NOREGEX")
The error returned when the input did not match the specified regular expression.
var ErrUnsupportedType = errors.New("unsupported type")
An error returned when a type cannot be parsed from a string value.
var ErrVerifyFailed = errors.New("NOVERIFY")
The error returned when no valid value could be gotten from prompt.
var GlobalRegistry = NewRegistry()
Functions ¶
func Capture ¶
Captures a command from the options and global registry and returns it. See Registry.Capture.
func CaptureExitSignal ¶
func CaptureExitSignal(f func())
Notifies the function when the exit signal is sent.
func DisplayEntryHelp ¶ added in v0.5.2
func DisplayHelp ¶ added in v0.5.2
func DisplayRootHelp ¶ added in v0.5.2
func Get ¶
Gets an instance of a command from the global registry with the given name, or nil if non could be found.
func GetArg ¶
Finds the first argument in args that is named argPrefix+name and returns the value while removing the name & value from args.
func Normalize ¶
Normalizes the string which removes all non-letters and numbers and converts it to lowercase.
func Peek ¶ added in v0.3.0
Peeks a command from the options and global registry and returns it. See Registry.Peek.
Types ¶
type ArgValue ¶
type ArgValue interface {
FromArgs(opts *Options, prop *Property, getArg func(arg string, defaultValue string) string) error
}
A value which has custom arg handling logic. If this is present, this value and any sub values are not handled with arg or prompt logic.
type CaptureImporter ¶
An importer that can apply data to a target before Capture is executed.
type Dynamic ¶
type Dynamic interface { // The property just updated (or nil if this is the first call) and the map // of command properties that can be dynamically updated Update(opts *Options, updated *Property, instance *Instance) error }
A dynamic command will have UpdateDynamic invoked before and after every property has been gotten from the user/system. This allows the CommandProperties to be dynamically changed during data capture OR it allows the state of the command to change. For example if a command has two properties and the default of one is based on
type Entry ¶ added in v0.4.0
type Entry struct { // The user friendly name of the command. Name string // Aliases of the command. Aliases []string // A short description of the command (one line). HelpShort string // A long description of the command. HelpLong string // An instance of the command. Either this or Registry should be given. Command any // A registry of sub commands. Either this or Command should be given. Sub Registry }
An entry for a registered command.
type Executable ¶
A command that can be executed after it's data is captured.
type Flags ¶
type Flags[T constraints.Integer] struct { // contains filtered or unexported fields }
Utility struct for typed bitwise operations.
type HasChoices ¶
type HasChoices interface {
GetChoices(opts *Options, prop *Property) PromptChoices
}
A value which has user defined options.
type Instance ¶
type Instance struct { Value reflect.Value PropertyMap map[string]*Property PropertyList []*Property }
An instance of a struct and all the properties on it.
func GetSubInstance ¶
Creates an instance that is appropriate for the given property.
func (*Instance) AddProperty ¶
Adds a property to the instance.
func (*Instance) Capture ¶
Capture populates the properties of the instance from arguments and prompting the options.
func (Instance) Count ¶
func (inst Instance) Count(match Match[PropertyFlags]) int
Counts how many properties in this instance match.
func (Instance) Flags ¶
func (inst Instance) Flags() Flags[PropertyFlags]
Builds a set of all flags in all properties in this instance.
type Match ¶
type Match[T constraints.Integer] func(value T) bool
A match is a function which is given a single integer and returns whether it matches some criteria.
func MatchAll ¶
func MatchAll[T constraints.Integer](test T) Match[T]
Creates a match which returns true if all bits in test are on in a given value.
func MatchAnd ¶
func MatchAnd[T constraints.Integer](ands ...Match[T]) Match[T]
Creates a match which returns true if all given matches return true.
func MatchAny ¶
func MatchAny[T constraints.Integer](test T) Match[T]
Creates a match which returns true if any bits in test are in a given value.
func MatchEmpty ¶
func MatchEmpty[T constraints.Integer]() Match[T]
Creates a match which returns true when a given value is zero.
func MatchExact ¶
func MatchExact[T constraints.Integer](test T) Match[T]
Creates a match which returns true if a given value and test are equal.
func MatchNone ¶
func MatchNone[T constraints.Integer](test T) Match[T]
Creates a match which returns true if there are no bits in common with a given value.
func MatchNot ¶
func MatchNot[T constraints.Integer](not Match[T]) Match[T]
Creaes a match which returns the negation of given match.
func MatchOnly ¶
func MatchOnly[T constraints.Integer](test T) Match[T]
Creates a match which returns true if all bits in a given value are on in test.
type Options ¶
type Options struct { // A general map of values that can be passed and shared between values being parsed, validated, and updated. Values map[string]any // The arguments to parse out Args []string // The arguments to parse out (before values were pulled out of it) ArgsOriginal []string // The prefix all argument names have, to differentiate argument names to values. ArgPrefix string // The number arrays and maps should start for argument parsing. The number will be in the argument name for arrays or for slices with complex values. ArgStartIndex int // The template used to generate the argument name/prefix for a struct property. ArgStructTemplate *template.Template // The template used to generate the argument name/prefix for a slice property. ArgSliceTemplate *template.Template // The template used to generate the argument name/prefix for an array property. ArgArrayTemplate *template.Template // The template used to generate the argument name/prefix for map keys ArgMapKeyTemplate *template.Template // The template used to generate the argument name/prefix for map values ArgMapValueTemplate *template.Template // The text that should trigger display help for the current prompt. HelpPrompt string // The template to use for displaying help about a prop. HelpTemplate *template.Template // Displays the requested help to the user. DisplayHelp func(help string, prop *Property) // The number of characters before we wrap the help. HelpWrapWidth int // The number of spaces to indent for properties, sub properties, etc. HelpIndentWidth int // The text that should trigger prompting to stop immediately and return a Quit error. QuitPrompt string // The text that should discard the current slice element or map key/value being prompted. DiscardPrompt string // If prompting should be disabled. DisablePrompt bool // If prompting should be done even if no input file was given. ForcePrompt bool // Prompts for a single value. Potentially multiple lines & hidden. If quit or discard prompts are given, the appropriate error is returned. PromptOnce func(prompt string, options PromptOnceOptions) (string, error) // Prompts the user to start a complex type (struct, slice, array, map) that they can avoid populating. PromptStart func(prop Property) (bool, error) // The valid options the user can enter which decides if they start prompting for a complex type. The input must match one of the keys (normalized) or prompting will be done repeatedly. PromptStartOptions map[string]bool // The text to add to the end of the prompt that displays the valid true/false options for the user. PromptStartSuffix string // Prompts the user to continue populating a complex type (slice, map) that they can avoid adding to. PromptMore func(prop Property) (bool, error) // The valid options the user can enter which decides if they prompt another value for a complex type. The input must match one of the keys (normalized) or prompting will be done repeatedly. PromptMoreOptions map[string]bool // The text to add to the end of the prompt that displays the valid true/false options for the user. PromptMoreSuffix string // A function called at the end of PromptStart and possible PromptMore calls. Can be used to notify user. PromptEnd func(prop Property) error // A template which converts the current prompt state into a string to send the user. PromptTemplate *template.Template // The current context of prompts. This metadata is accessible in the PromptTemplate as .Context. PromptContext PromptContext // If a slice that is prepopulated (via import or developer) should reprompt the values to allow the user to change them. RepromptSliceElements bool // If a map that is prepopulated (via import or developer) should repomrpt the values to allow the user to change them. RepromptMapValues bool // How many times the user should be prompted for a valid value. RepromptOnInvalid int // contains filtered or unexported fields }
A dynamic set of variables that commands can have access to during unmarshal, capture, and execution.
func NewOptions ¶
func NewOptions() *Options
A new options which by default has no arguments and does not support prompting.
func (*Options) CaptureExitSignal ¶
func (opts *Options) CaptureExitSignal()
Stops capturing user input if the exit signal is sent.
func (*Options) ClearFiles ¶
Clears all files used during prompting, effectively disabling prompting unless ForcePrompt is specified.
func (*Options) Program ¶
Enables prompting and arguments from the programs stdin, stdout, and args.
func (*Options) Prompt ¶
func (opts *Options) Prompt(options PromptOptions) (any, error)
Prompts the options for a value given PromptOptions.
func (*Options) RestorArgs ¶ added in v0.3.0
Restores args to its original value
func (*Options) WithArgs ¶
Sets the args for the current options. The given slice is unchanged, a copy is retained and updated on the Context during argument parsing.
func (*Options) WithContext ¶ added in v0.3.0
Sets the context for the current options.
type PromptChoice ¶
A choice when prompting/parsing arg text values.
type PromptChoices ¶
type PromptChoices map[string]PromptChoice
A map of inputs to translated values. Matching is done ignoring punctuation and will do partial matching if only one choice is a partial match.
func (PromptChoices) Add ¶
func (pc PromptChoices) Add(input string, value string)
Adds an input and translated value to choices.
func (PromptChoices) Convert ¶
func (pc PromptChoices) Convert(input string) (string, error)
Converts the input to a translated value OR returns an InvalidConversion error. If choices is empty then the input given is returned. If input partially matches exactly one choice (normalized) then its assumed to be that value.
func (PromptChoices) FromTag ¶
func (pc PromptChoices) FromTag(tag string, pairDelimiter string, keyValueDelimiter string)
Parses choices from a tag string. choices.FromTag("a:1,b:2,c:3", ",", ":") is parsed to {"a":1,"b":2,"c":3}
func (PromptChoices) HasChoices ¶
func (pc PromptChoices) HasChoices() bool
Returns whether there are any choices defined.
type PromptContext ¶
type PromptContext struct { // If the user is currently being prompted for a map key. IsMapKey bool // If the user is currently being prompted for a map value. IsMapValue bool // The string representation of the key of the value being prompted when IsMapValue = true. MapKey string // If the user is currently being prompted for a slice element. IsSlice bool // The index of the element when being prompted for a slice element. SliceIndex int // If the current value is part of a slice or map reprompting. Reprompt bool }
Context that is changed during the prompt process.
type PromptCustom ¶
A value which has custom prompt handling logic.
type PromptOnceOptions ¶
Options that can be passed when prompting for a single input.
type PromptOptions ¶
type PromptOptions struct { // If specified this function is called to compute the text that is displayed to the user during prompting. GetPrompt func(status PromptStatus) (string, error) // The prompt text to use if GetPrompt is nil. Prompt string // If the user's input should be hidden (ex: passwords). Hidden bool // The type that the input should be converted to. If the user provides an invalid format they may be reprompted. // By default the type returned is string. If the type implements PromptValue then the FromPrompt function will be called. Type reflect.Type // If the input value should be verified (prompts again and ensures they match). Verification is only done after we know the value is valid for the type, choices, etc. Verify bool // If the input collects multiple lines of text and stops on MultiStop (an empty line by default). Multi bool // The text which stops collection of multiple lines of text. MultiStop string // How many times we should try to get valid input from the user. Tries int // Help text to display if they request it. Help string // A regular expression to run a first validation pass over the input. Regex string // If the value is optional, allowing the user to enter nothing. nil is returned in this scenario. Optional bool // The property being prompted, if any. This is sent to DisplayHelp. Prop *Property // The valid inputs and automatic translations. The matching and translation is done before converting it to the desired type. Choices PromptChoices // A custom validation function for the text, before its parsed. ValidateText func(text string) error // A custom validation function for the text, before its parsed. Validate func(value any, text string) error }
Options used to prompt a user for a value.
type PromptStatus ¶
type PromptStatus struct { // If the user is being asked for a value again directly after they asked for help. AfterHelp bool // The number of times we've prompted for a value and it was not successful. PromptCount int // How many times input was given for a prompt with choices and it didn't match. InvalidChoice int // How many times input was given in an improper format. InvalidFormat int // If this prompt is to verify the user's inut. Verify bool // How many times an invalid verification happened. InvalidVerify int }
The current status of the prompt, so useful prompt text can be generated.
type PromptValue ¶
A value which has custom prompt parsing logic.
type Property ¶
type Property struct { // The current value of the property Value reflect.Value // The property type Type reflect.Type // The name of the property Name string // If a prompt should be hidden for this property. ex: `prompt:"-"` HidePrompt bool // Text to display when prompting the user. ex: `prompt:"Enter value"` PromptText string // If the prompt can contain multiple lines and we only stop prompting on an empty line.ex: `prompt-options:"multi"` PromptMulti bool // If the prompt should ask before it starts to populate a complex type (default true). ex: `prompt-options:"start:"` or `prompt-options:"start:Do you have any favorite numbers (y/n)?"` PromptStart string // If the prompt should ask before it starts to populate a complex type (default true). ex: `prompt-options:"end:"` or `prompt-options:"end:Thank you for your favorite numbers."` PromptEnd string // The text to display when questioning for more. ex: `prompt-options:"more:More?"` PromptMore string // If we should prompt only when the current value is an empty value (not loaded by env, flags, or prompt). ex: `prompt-options:"empty"` PromptEmpty bool // If the user input should be hidden for this property. ex: `prompt-options:"hidden"` InputHidden bool // How many tries to get the input. Overrides Context settings. ex: `prompt-options:"tries:4"` PromptTries int // If we should verify the input by reprompting. ex: `prompt-options:"verify"` PromptVerify bool // If the property should reprompt given slice and map values. ex `prompt-options="reprompt"` Reprompt bool // Help text to display for this property if requested by the user. ex: `help:"your help text here"` Help string // If the default value should be shown to the user. ex: `default-mode:"hide"` HideDefault bool // Default text to display to override the text version of the current value. ex: `default-text:"***"` DefaultText string // The default value in string form. ex: `default` Default string // A regular expression to match. Regex string // A comma delimited map of acceptable values or a map of key/value pairs. ex: `options:"a,b,c"` or `options:"a:1,b:2,c:3"` Choices PromptChoices // Used by strings for min length, numbers for min value (inclusive), or by slices for min length. ex `min:"1"` Min *float64 // Used by strings for max length, numbers for max value (inclusive), or by slices for max length. ex `max:"10.3"` Max *float64 // Specified with the tag `env:"a,b"` Env []string // Arg name for this property. Defaults to the field name. ex: `arg:"my-flag"` Arg string // Flags that represent how Flags Flags[PropertyFlags] }
A command property parsed from a command struct.
func (Property) CanFromArgs ¶
Returns whether this property can have its state loaded from arguments.
func (Property) CanLoad ¶
Returns whether this property can have its state loaded from environment variables or default tags.
func (Property) CanPrompt ¶
Returns whether this property can have its state loaded from prompting the user.
func (Property) ConcreteType ¶
func (Property) ConcreteValue ¶
func (*Property) GetPromptChoices ¶
func (prop *Property) GetPromptChoices(opts *Options) PromptChoices
func (Property) HasCustomPromptText ¶ added in v0.5.3
func (Property) IsOptional ¶
func (*Property) Load ¶
Loads the initial value of the property from environment variables or default tags specified on the struct fields.
type PropertyFlags ¶
type PropertyFlags uint
Flags which are set on a property during capture.
const ( // The property has not been changed. PropertyFlagNone PropertyFlags = (1 << iota) >> 1 // The property has had a value populated from arguments. PropertyFlagArgs // The property has had a value populated from prompting. PropertyFlagPrompt // The property has had a value populated from environment variables. PropertyFlagEnv // The property has had a value populated from the `default:""` struct tag. PropertyFlagDefault )
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
A map of "commands" by name.
func CreateRegistry ¶ added in v0.3.0
Creates a registry with the given initial entries.
func (Registry) Capture ¶
Captures a command from the options and returns it. The first argument in the options is expected to be the name of the command. If no arguments are given the default "" command is used. The remaining arguments are used to populate the value. If no arguments are specified beyond the name then interactive mode is enabled by default. Interactive (prompt) can be disabled entirely with "--interactive false". Importers are also evaluted, like --json, --xml, and --yaml. The value following is the path to the file to import.
func (Registry) EntriesAll ¶ added in v0.3.0
Returns all commands registered to this registry and all sub registries.
func (Registry) EntryForDeep ¶ added in v0.3.0
Returns the entry & depth which matches the names if only one entry does - going deep into the entry inner registries until we reach max depth.
func (Registry) ExecuteReturn ¶ added in v0.3.0
Executes an executable command based on the given options and returns it.
func (Registry) Get ¶
Gets an instance of a command with the given name, or nil if non could be found.
func (Registry) GetDeep ¶ added in v0.3.0
Gets an instance of a command with the given name, or nil if non could be found.
func (Registry) HasDeep ¶ added in v0.3.0
Returns whether the registry has a command with the given name.