cmdgo

package module
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2023 License: MIT Imports: 20 Imported by: 0

README

cmdgo

A utility for creating command line interfaces that can run in interactive mode, from parameters, from the environment, and from files (json, xml, yaml). The command properties can be validated or populated dynamically.

Example Code

// myprogram
package main

import (
  "fmt"
  "github.com/ClickerMonkey/cmdgo"
)

type Echo struct {
  Message string `prompt:"Enter message" help:"The message to enter" default:"Hello World" min:"2" env:"ECHO_MESSAGE" arg:"msg"`
}

func (echo *Echo) Execute(opts cmdgo.Options) error {
  opts.Printf("ECHO: %s\n", echo.Message)
  return nil
}

func main() {
  cmdgo.Register(cmdgo.RegistryEntry{
    Name: "echo", 
    Command: Echo{},
  })

  opts := cmdgo.NewOptions().Program()
  err := cmdgo.Execute(opts)
  if err != nil {
    panic(err)
  }
}
Example Usage
# By default its interactive unless you specify arguments or files to import
> ./myprogram echo
Enter message (Hello World): Hi
ECHO: Hi

> ./myprogram echo --msg Ho
ECHO: Ho

> ./myprogram echo
Enter message (Hello World): help!
The message to enter
Enter message (Hello World): Lets go
ECHO: Lets go

> ECHO_MESSAGE=Hey ./myprogram echo --interactive no
ECHO: Hey

> ./myprogram echo --interactive no
ECHO: Hello World

> ./myprogram echo --msg A
*fails since message is too small*

> ./myprogram echo --json path/to/json/file
# {"Message":"From json!"}
ECHO: From json!

> ./myprogram echo --xml path/to/xml/file
# <Echo><Message>From xml!</Message></Echo>
ECHO: From xml!

> ./myprogram echo --yaml path/to/yaml/file
# message: From yaml!
ECHO: From yaml!
Struct tags

Various struct tags can be used to control how values are pulled from arguments, json, yaml, xml, and prompting the user.

  • json This tag is utilized normally
    • `json:"JSON property override,omitempty"`
  • xml This tag is utilized normally
    • `xml:"XML element override,omitempty"`
  • yaml This tag is utilized normally
    • `yaml:"YAML property override,omitempty"`
  • prompt The text to display to the user when prompting for a single value. The current/default may be added to this prompt in parenthesis along with ": ".
    • prompt:"Your name"
    • prompt:- (does not prompt the user for this field)
  • prompt-options Various options for controlling prompting. They are key:value pairs separated by commas, where value is optional.
    • start A message to display when starting a complex value and asking if they want to enter a value for it. If the value is not specified it doesn't prompt the user and just assumes it should start.
    • more A message to display when a value has been added to a map or slice and we want to know if more values should be added. The user must enter y to add more.
    • end A message to display when the complex value is done being prompted.
    • multi The property accepts multiple lines of input and will stop prompting when an empty line is given.
    • hidden The property input should be hidden from the user. (ex: passwords)
    • verify The user is prompted to re-enter the value to confirm it.
    • reprompt The user is repromproted for existing values in the property slice or map. Has no affect for other types.
    • tries A maximum number of times to try to get a valid value from the user. This overrides the Context's RepromptOnInvalid.
    • Example: prompt-options:"start:,end:Thank you for your feedback!,multi,more:Do you have any other questions?"
  • help The text to display if the user is prompted for a value and enters "help!" (help text can be changed or disabled on the Context). The prompt will display the help and prompt for a value one more time.
  • default-text The text to display in place of the current value for a field. If a field contains sensitive data, you can use this to mask it.
  • default The default value for the field. This is populated on capture assuming no environment variables are found.
  • default-mode If "hide" then if a field has a current value it won't be displayed when prompting the user.
  • options A comma delimited list of key:value pairs that are acceptable values. If no values are given the keys are the values. If values are given then the user input is matched to a key and the value is used. Options handle partial keys, so if an option is "hello" and they enter "he" and no other options start with "he" then the value will be the value paired with "hello" or "hello" if there is no value.
    • options:"a:1,b:2,c:3" The user can enter a, b, or c and it converts it to the number 1, 2, and 3 respectively.
  • min The minimum required slice length, map length, string length, or numeric value (inclusive). When prompting for a map or slice it will prompt for this many.
  • max The maximum allowed slice length, map length, string length, or numeric value (inclusive). When prompting for a map or slice and this length is met capturing will end for the value.
  • env The environment variables to look for to populate the field.
  • arg The override for the argument name. By default the argument is the normalized name of the field.
    • arg:"msg" (if opts.ArgPrefix is -- then the user can specify this field value with --msg).
    • arg:"-" (does not pull value from the arguments)

Documentation

Index

Constants

This section is empty.

Variables

View Source
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)
	},
}
View Source
var ErrDiscard = errors.New("DISCARD")

The error returned when the user requested to discard the current value being prompted for a complex type.

View Source
var ErrInvalidConversion = errors.New("invalid conversion")

An error returned when input is given to prompt choices and no choices could be determined.

View Source
var ErrInvalidFormat = errors.New("invalid format")

An error returned when we failed setting a value from a given string.

View Source
var ErrInvalidUnmarshalError = errors.New("non-pointer passed to Unmarshal")

An error returned from Unmarshal if nil or a non-pointer is passed to Unmarshal.

View Source
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.

View Source
var ErrNoPrompt = errors.New("NOPROMPT")

The error returned when no valid value could be gotten from prompt.

View Source
var ErrQuit = errors.New("QUIT")

The error returned when the user requested to quit prompting.

View Source
var ErrRegexFailed = errors.New("NOREGEX")

The error returned when the input did not match the specified regular expression.

View Source
var ErrUnsupportedType = errors.New("unsupported type")

An error returned when a type cannot be parsed from a string value.

View Source
var ErrVerifyFailed = errors.New("NOVERIFY")

The error returned when no valid value could be gotten from prompt.

View Source
var GlobalRegistry = NewRegistry()

Functions

func Capture

func Capture(opts *Options) (any, error)

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 DisplayEntryHelp(opts *Options, entry *Entry) error

func DisplayHelp added in v0.5.2

func DisplayHelp(opts *Options, registry Registry, help string) error

func DisplayRootHelp added in v0.5.2

func DisplayRootHelp(opts *Options, registry Registry)

func Execute

func Execute(opts *Options) error

Executes an executable command from the global registry based on the given options.

func Get

func Get(name string) any

Gets an instance of a command from the global registry with the given name, or nil if non could be found.

func GetArg

func GetArg(name string, defaultValue string, args *[]string, argPrefix string, flag bool) string

Finds the first argument in args that is named argPrefix+name and returns the value while removing the name & value from args.

func Normalize

func Normalize(x string) string

Normalizes the string which removes all non-letters and numbers and converts it to lowercase.

func ParseType

func ParseType(t reflect.Type, s string) (any, error)

Returns a value of the given type which is parsed from s, or returns an error.

func Peek added in v0.3.0

func Peek(opts *Options) any

Peeks a command from the options and global registry and returns it. See Registry.Peek.

func Register

func Register(entry Entry)

Adds a command to the global registry.

func SetString

func SetString(value reflect.Value, s string) error

Sets the value based on the given string or returns an error if it couldn't be parsed or set.

func Unmarshal

func Unmarshal(opts *Options, v any) error

Unmarshal parses the arguments and prompts in opts and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

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

type CaptureImporter func(data []byte, target any) error

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

type Executable interface {
	// Executes the command
	Execute(opts *Options) error
}

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.

func (*Flags[T]) Clear

func (f *Flags[T]) Clear()

Clears all flags from this set.

func (Flags[T]) Get

func (f Flags[T]) Get() T

Returns the current integer value in this set.

func (Flags[T]) Is

func (f Flags[T]) Is(match Match[T]) bool

Returns whether this set of flags matches the given Match function.

func (Flags[T]) IsEmpty

func (f Flags[T]) IsEmpty() bool

Returns whether this set is empty.

func (*Flags[T]) Only

func (f *Flags[T]) Only(flags T)

Changes this set to be only values that are shared between it and the flags.

func (*Flags[T]) Remove

func (f *Flags[T]) Remove(flags T)

Removes the flags from this set.

func (*Flags[T]) Set

func (f *Flags[T]) Set(flags T)

Adds the flags to this set.

func (*Flags[T]) Toggle

func (f *Flags[T]) Toggle(flags T)

Toggles the flags in this set.

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 GetInstance

func GetInstance(value any) Instance

Creates an instance given a value.

func GetSubInstance

func GetSubInstance(value any, prop Property) Instance

Creates an instance that is appropriate for the given property.

func (*Instance) AddProperty

func (inst *Instance) AddProperty(prop *Property)

Adds a property to the instance.

func (*Instance) Capture

func (inst *Instance) Capture(opts *Options) error

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.

func (Instance) IsDefault

func (inst Instance) IsDefault() bool

Returns if the value in this instance has all default values.

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.

func MatchOr

func MatchOr[T constraints.Integer](ors ...Match[T]) Match[T]

Creates a match which returns true if any given matches return true.

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) CanPrompt

func (opts *Options) CanPrompt() bool

Returns whether this options can prompt the user.

func (*Options) CaptureExitSignal

func (opts *Options) CaptureExitSignal()

Stops capturing user input if the exit signal is sent.

func (*Options) ClearArgs

func (opts *Options) ClearArgs() *Options

Clears all from the current options.

func (*Options) ClearFiles

func (opts *Options) ClearFiles() *Options

Clears all files used during prompting, effectively disabling prompting unless ForcePrompt is specified.

func (*Options) Cli

func (opts *Options) Cli() *Options

Enables argument parsing using the current running programs arguments.

func (*Options) Close

func (opts *Options) Close() error

Closes any input set on the options.

func (*Options) Context added in v0.3.0

func (opts *Options) Context() context.Context

Sets the context for the current options.

func (*Options) Printf

func (opts *Options) Printf(format string, args ...any) error

Prints text out to the configured output destination.

func (*Options) Program

func (opts *Options) Program() *Options

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

func (opts *Options) RestorArgs() *Options

Restores args to its original value

func (*Options) Std

func (opts *Options) Std() *Options

Enables prompting using standard in & out.

func (*Options) WithArgs

func (opts *Options) WithArgs(args []string) *Options

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

func (opts *Options) WithContext(ctx context.Context) *Options

Sets the context for the current options.

func (*Options) WithFiles

func (opts *Options) WithFiles(in *os.File, out *os.File) *Options

Sets the files used during prompting for the current options.

type PromptChoice

type PromptChoice struct {
	Text  string
	Value string
}

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

type PromptCustom interface {
	Prompt(opts *Options, prop *Property) error
}

A value which has custom prompt handling logic.

type PromptOnceOptions

type PromptOnceOptions struct {
	Multi     bool
	Hidden    bool
	MultiStop string
}

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

type PromptValue interface {
	FromPrompt(opts *Options, value string) error
}

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

func (prop Property) CanFromArgs() bool

Returns whether this property can have its state loaded from arguments.

func (Property) CanLoad

func (prop Property) CanLoad() bool

Returns whether this property can have its state loaded from environment variables or default tags.

func (Property) CanPrompt

func (prop Property) CanPrompt() bool

Returns whether this property can have its state loaded from prompting the user.

func (Property) ConcreteType

func (prop Property) ConcreteType() reflect.Type

func (Property) ConcreteValue

func (prop Property) ConcreteValue() any

func (*Property) FromArgs

func (prop *Property) FromArgs(opts *Options) error

Loads value of the property from args if it can and it exists.

func (*Property) GetPromptChoices

func (prop *Property) GetPromptChoices(opts *Options) PromptChoices

func (Property) HasCustomPromptText added in v0.5.3

func (prop Property) HasCustomPromptText() bool

func (Property) IsArray

func (prop Property) IsArray() bool

func (Property) IsBool

func (prop Property) IsBool() bool

func (Property) IsDefault

func (prop Property) IsDefault() bool

func (Property) IsIgnored

func (prop Property) IsIgnored() bool

func (Property) IsKind

func (prop Property) IsKind(kind reflect.Kind) bool

func (Property) IsKinds

func (prop Property) IsKinds(kinds map[reflect.Kind]struct{}) bool

func (Property) IsMap

func (prop Property) IsMap() bool

func (Property) IsNil

func (prop Property) IsNil() bool

func (Property) IsOptional

func (prop Property) IsOptional() bool

func (Property) IsSimple

func (prop Property) IsSimple() bool

func (Property) IsSlice

func (prop Property) IsSlice() bool

func (Property) IsStruct

func (prop Property) IsStruct() bool

func (*Property) Load

func (prop *Property) Load(opts *Options) error

Loads the initial value of the property from environment variables or default tags specified on the struct fields.

func (*Property) Prompt

func (prop *Property) Prompt(opts *Options) error

Prompts the user for the value of this property if configured to do so.

func (*Property) Set

func (prop *Property) Set(opts *Options, input string, addFlags PropertyFlags) error

func (Property) Size

func (prop Property) Size() float64

func (Property) Validate

func (prop Property) Validate(opts *Options) error

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

func CreateRegistry(entries []Entry) Registry

Creates a registry with the given initial entries.

func NewRegistry

func NewRegistry() Registry

Creates a new empty registry.

func (*Registry) Add

func (r *Registry) Add(entry Entry)

Adds a command to the registry.

func (Registry) Capture

func (r Registry) Capture(opts *Options) (any, error)

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) Entries

func (r Registry) Entries() []*Entry

Returns all commands registered to this registry.

func (Registry) EntriesAll added in v0.3.0

func (r Registry) EntriesAll() []Entry

Returns all commands registered to this registry and all sub registries.

func (Registry) EntryFor

func (r Registry) EntryFor(namePartial string) *Entry

Returns the entry which matches the name only if one entry does.

func (Registry) EntryForDeep added in v0.3.0

func (r Registry) EntryForDeep(namePartials []string) (*Entry, int)

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) Execute

func (r Registry) Execute(opts *Options) error

Executes an executable command based on the given options.

func (Registry) ExecuteReturn added in v0.3.0

func (r Registry) ExecuteReturn(opts *Options) (any, error)

Executes an executable command based on the given options and returns it.

func (Registry) Get

func (r Registry) Get(namePartial string) any

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

func (r Registry) GetDeep(namePartials []string) (any, int)

Gets an instance of a command with the given name, or nil if non could be found.

func (Registry) Has

func (r Registry) Has(namePartial string) bool

Returns whether the registry has a command with the given name.

func (Registry) HasDeep added in v0.3.0

func (r Registry) HasDeep(namePartials []string) bool

Returns whether the registry has a command with the given name.

func (Registry) IsEmpty added in v0.3.0

func (r Registry) IsEmpty() bool

Returns whether the registry is empty.

func (Registry) Matches

func (r Registry) Matches(namePartial string) []*Entry

Returns all commands that match the partial name.

func (Registry) Peek added in v0.2.1

func (r Registry) Peek(opts *Options) any

Returns an instance of the command that would be captured based on the given options. nil is returned if the options is missing a valid command or is requesting for help.

type Validator

type Validator interface {
	Validate(opts *Options) error
}

A command can be validated against the current options before it's executed. If an error is returned then execution never happens.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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