argo

package
v1.4.8 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// ArgErrInvalidDefault represents all cases where the
	// Default value passed to an ArgumentBuilder is the root
	// cause.
	ArgErrInvalidDefault ArgumentErrorType = 1 << iota

	// ArgErrInvalidBinding represents all cases where the
	// Binding value passed to an ArgumentBuilder is the root
	// cause.
	ArgErrInvalidBinding

	// ArgErrInvalidDefaultFn represents the case where the
	// default value provider function set on an
	// ArgumentBuilder is incompatible with the binding type
	// also set on that ArgumentBuilder.
	ArgErrInvalidDefaultFn = ArgErrInvalidDefault | 1<<iota

	// ArgErrInvalidDefaultFn represents the case where the
	// default value set on an ArgumentBuilder is incompatible
	// with the binding type also set on that ArgumentBuilder.
	ArgErrInvalidDefaultVal = ArgErrInvalidDefault | 1<<iota

	// ArgErrInvalidBindingBadType represents the case where
	// the value set as the ArgumentBuilder's binding is not
	// of a type that can be unmarshaled.
	ArgErrInvalidBindingBadType = ArgErrInvalidBinding | 1<<iota
)

Variables

This section is empty.

Functions

func ByteSliceParserBase64 added in v1.2.0

func ByteSliceParserBase64(s string) ([]byte, error)

ByteSliceParserBase64 is a ByteSliceParser function that decodes the given string as a base64 string.

func ByteSliceParserHex added in v1.2.0

func ByteSliceParserHex(s string) ([]byte, error)

ByteSliceParserHex is a ByteSliceParser function that decodes the given string as a hex string.

func ByteSliceParserRaw added in v1.2.0

func ByteSliceParserRaw(s string) ([]byte, error)

ByteSliceParserRaw is a ByteSliceParser function that casts the input string into a byte slice.

This function will never return an error.

func NoneOfPostParseArgumentValidator added in v1.1.0

func NoneOfPostParseArgumentValidator[T comparable](values []T, message string) any

NoneOfPostParseArgumentValidator builds an argument post-parse validator function that ensures the value parsed from the raw command line input does not match any of the values in the given values slice.

If the parsed value does match one of the values in the given values slice, the given message will be used to build a new error which will be returned.

func NoneOfPreParseArgumentValidator added in v1.1.0

func NoneOfPreParseArgumentValidator(values []string, message string) any

NoneOfPreParseArgumentValidator builds an argument pre-parse validator function that ensures the raw value passed on the command line call does not match any of the values in the given values slice.

If the parsed value does match one of the values in the given values slice, the given message will be used to build a new error which will be returned.

func NumericRangePostParseArgumentValidator added in v1.1.0

func NumericRangePostParseArgumentValidator[T NumericValue](minimum, maximum T, message string) any

NumericRangePostParseArgumentValidator builds an argument post-parse validator function that ensures the value parsed from the raw command line input falls within the given inclusive range.

If the value falls outside the given inclusive range, the given message will be used to build a new error which will be returned.

func OneOfPostParseArgumentValidator added in v1.1.0

func OneOfPostParseArgumentValidator[T comparable](values []T, message string) any

OneOfPostParseArgumentValidator builds an argument post-parse validator function that ensures the value parsed from the raw command line input matches at least one of the values in the given values slice.

If the parsed value does not match one of the values in the given values slice, the given message will be used to build a new error which will be returned.

func OneOfPreParseArgumentValidator added in v1.1.0

func OneOfPreParseArgumentValidator(values []string, message string) any

OneOfPreParseArgumentValidator builds an argument pre-parse validator function that ensures the raw value passed on the command line call matches at least one of the values in the given values slice.

If the incoming raw value does not match one of the values in the given values slice, the given message will be used to build a new error which will be returned.

Types

type Argument

type Argument interface {

	// Name returns the custom name assigned to this Argument.
	//
	// If no custom name was assigned to this Argument when it was built, this
	// method will return an empty string.
	Name() string

	// HasName tests whether this Argument has a custom name assigned.
	HasName() bool

	// Default returns the default value or value provider attached to this
	// Argument, if such a value exists.
	//
	// If this Argument does not have a default value or provider set, this method
	// will return nil.
	Default() any

	// HasDefault indicates whether a default value has been set on this
	// Argument.
	HasDefault() bool

	// DefaultType returns the reflect.Type value for the configured default
	// value.
	//
	// If no default value has been set on this Argument, this method will return
	// nil.
	DefaultType() reflect.Type

	// Description returns the description attached to this Argument.
	//
	// If no description was attached to this Argument when it was built, this
	// method will return an empty string.
	Description() string

	// HasDescription tests whether this Argument has a description attached.
	HasDescription() bool

	// WasHit tests whether this Argument was hit in a CLI call.
	//
	// This does not necessarily indicate that there is no value available for
	// this argument, just that it wasn't hit in the CLI call.  If the argument
	// had a default value provided, it will have been set in that case.
	WasHit() bool

	// RawValue returns the raw text value that was assigned to this Argument in
	// the CLI call.
	//
	// If this Argument was not hit during the CLI call, this method will return
	// an empty string.  This empty string IS NOT an indicator whether this
	// Argument was hit, as it may have been intentionally assigned an empty
	// value.  To test whether the Argument was hit, use WasHit.
	RawValue() string

	// IsRequired returns whether this Argument is required by its parent CLI
	// component.
	//
	// When parsing the CLI, if this argument is not found, an error will be
	// returned.
	IsRequired() bool

	// HasBinding indicates whether this Argument has a value binding.
	HasBinding() bool

	AppendWarning(warning string)

	// BindingType returns the reflect.Type value for the configured binding.
	//
	// If this argument has no binding, this method will return nil.
	BindingType() reflect.Type
	// contains filtered or unexported methods
}

Argument represents a positional or flag argument that may be attached directly to a Command or CommandLeaf, or may be attached to a Flag.

type ArgumentBuilder

type ArgumentBuilder interface {

	// WithName sets the name for this argument.
	//
	// The name value is used when rendering help information about this argument.
	WithName(name string) ArgumentBuilder

	// WithDescription sets the description of this argument to be shown in
	// rendered help text.
	WithDescription(desc string) ArgumentBuilder

	// Require marks the output Argument as being required.
	Require() ArgumentBuilder

	// WithBinding sets the bind value for the Argument.
	//
	// The bind value may be one of a value pointer, a consumer function, or an
	// Unmarshaler instance.  For demonstrations of each, see the examples below.
	//
	// If the bind value is a pointer, the Argument's value unmarshaler will be
	// called to unmarshal the raw string value into a value of the type passed
	// to this method.
	//
	// If the bind value is a consumer function, that function will be called with
	// the parsed value from the CLI.  The consumer function may optionally return
	// an error which, if not nil, will be passed up as a parsing error.
	//
	// If the bind value is an Unmarshaler instance, that instance's Unmarshal
	// method will be called with the raw input from the CLI.
	//
	// Setting this value to anything other than a pointer or an Unmarshaler
	// instance will result in an error being returned when building the argument
	// is attempted.
	//
	// Example 1 (a simple var binding):
	//     var myValue time.Duration
	//     cli.Argument.WithBinding(&myValue)
	//
	// Example 2 (an unmarshaler func):
	//     cli.Argument.WithBinding(UnmarshalerFunc(func(raw string) error {
	//         fmt.Println(raw)
	//         return nil
	//     }))
	//
	// Example 3 (lets get silly with it):
	//     var myValue map[bool]**string
	//     cli.Argument().WithBinding(&myValue)
	//
	// Example 4 (custom type)
	//     type Foo struct {
	//         // some fields
	//     }
	//
	//     func (f *Foo) Unmarshal(raw string) error {
	//         // parse the given string
	//         return nil
	//     }
	//
	//     func main() {
	//         var foo Foo
	//         cli.Argument().WithBinding(&foo)
	//     }
	//
	// Example 5 (plain consumer func which returns an error):
	//     cli.Argument().WithBinding(func(value int) error { do something })
	//
	// Example 6 (plain consumer func which returns nothing):
	//     cli.Argument().WithBinding(func(value int) { do something })
	//
	WithBinding(pointer any) ArgumentBuilder

	// WithDefault sets the default value for the argument to be used if the
	// argument is not provided on the command line.
	//
	// Setting this value without providing a binding value using `Bind()` will
	// mean that the given default will not be set to anything when the CLI input
	// is parsed.
	//
	// When used, the type of this value must meet one of the following criteria:
	//   1. `val` is compatible with the type of the value used with
	//      WithBinding.
	//   2. `val` is a string that may be parsed into a value of the type used
	//      with WithBinding.
	//   3. `val` is a function which returns a type that is compatible with the
	//      type of the value used with WithBinding
	//   4. `val` is a function which returns a type that is compatible with the
	//      type of the value used with WithBinding in addition to returning an
	//      error as the second return value.
	//
	// Examples:
	//     arg.WithBinding(&fooString).WithDefault(3)   // Type mismatch
	//
	//     arg.WithBinding(&fooInt).WithDefault(3)      // OK
	//
	//     arg.WithBinding(&fooInt).
	//       WithDefault(func() int {return 3})         // OK
	//
	//     arg.WithBinding(&fooInt).
	//       WithDefault(func() (int, error) {
	//         return 3, nil
	//       })                                         // OK
	//
	// If the value provided to this method is a pointer to the type of the bind
	// value it will be dereferenced to set the bind value.
	WithDefault(def any) ArgumentBuilder

	// WithUnmarshaler allows providing a custom ValueUnmarshaler instance that
	// will be used to unmarshal string values into the binding type.
	//
	// If no binding is set on this argument, the provided ValueUnmarshaler will
	// not be used.
	//
	// If a custom unmarshaler is not provided by way of this method, then the
	// internal magic unmarshaler will be used to parse raw argument values.
	WithUnmarshaler(fn ValueUnmarshaler) ArgumentBuilder

	// WithValidator appends the given validator function to the argument's
	// internal slice of validators.
	//
	// There are 2 types of validators that may be set here, each of which going
	// to a separate slice.  Type 1 is a pre-parse validator which will be called
	// when an argument is first hit, but before it is parsed.  Type 2 is a
	// post-parse validator which will be called immediately after an argument is
	// parsed to validate the parsed value.
	//
	// When appending a validator function, if it is of type 1 it will go to the
	// pre-parse validator slice, and if it is of type 2 it will go to the
	// post-parse validator slice.
	//
	// Pre-parse (type 1) validators must match the following function signature:
	//     func(string) error
	//
	// The value that is passed to the function will be the raw value that was
	// passed to the command on the CLI.  If an error is returned, CLI parsing
	// will halt, and the returned error will be passed up.
	//
	// Post-parse (type 2) validators must match the following function signature:
	//     func(T, string) error
	//
	// Two values are passed to the function, the parsed value, and the raw value
	// that was passed to the command ont he CLI.  If an error is returned, CLI
	// parsing will halt, and the returned error will be passed up.
	//
	// Validators will be executed in the order they are appended.
	WithValidator(validatorFn any) ArgumentBuilder

	// Build attempts to build an Argument instance out of the configuration given
	// to this ArgumentBuilder instance.
	//
	// This function shouldn't need to be called in normal use of this library.
	Build(ctx *WarningContext) (Argument, error)
	// contains filtered or unexported methods
}

An ArgumentBuilder instance is used to construct a CLI argument that may be attached to a Flag or CommandLeaf.

func NewArgumentBuilder

func NewArgumentBuilder() ArgumentBuilder

type ArgumentError

type ArgumentError interface {
	error

	// Type returns the specific type of this error.
	//
	// See ArgumentErrorType for more details.
	Type() ArgumentErrorType

	// Is returns whether this error is of the type given.
	Is(errorType ArgumentErrorType) bool

	// Builder returns the ArgumentBuilder in which this error was encountered.
	Builder() ArgumentBuilder
}

ArgumentError represents an error encountered when attempting to build or handle an Argument.

type ArgumentErrorType

type ArgumentErrorType uint8

ArgumentErrorType provides a flag indicating what kind of error was encountered while attempting to build or use an Argument.

func (ArgumentErrorType) String

func (a ArgumentErrorType) String() string

type ByteSliceParser added in v1.2.0

type ByteSliceParser = func(string) ([]byte, error)

ByteSliceParser defines a function that expects a string input and attempts to deserialize that input into a byte slice.

type Command

type Command interface {

	// Name returns the name of the command.
	Name() string

	// Description returns the custom description for the command.
	//
	// Description values are used internally for rendering held text.
	Description() string

	// HasDescription indicates whether this command has a description value set.
	HasDescription() bool

	// FlagGroups returns the flag groups attached to this command.
	//
	// Flag groups are named categories of flags defined when building the
	// command.
	FlagGroups() []FlagGroup

	// HasFlagGroups indicates whether this command has any flag groups attached
	// to it.
	HasFlagGroups() bool

	// FindShortFlag looks up a Flag instance by its short form.
	//
	// If no such flag could be found on this command, this method will return
	// nil.
	FindShortFlag(c byte) Flag

	// FindLongFlag looks up a Flag instance by its long form.
	//
	// If no such flag could be found on this command, this method will return
	// nil.
	FindLongFlag(name string) Flag

	// Arguments returns the positional Argument instances attached to this
	// Command.
	Arguments() []Argument

	// HasArguments indicates whether this Command has any positional arguments
	// attached.
	//
	// This method does not indicate whether those arguments were present on the
	// command line, it simply indicates whether Argument instances were attached
	// to the Command by the CommandBuilder.
	//
	// To determine whether an argument was present on the command line, test the
	// argument itself by using the Argument.WasHit method.
	HasArguments() bool

	// UnmappedInputs returns a collection of inputs that were passed to this
	// command that do not match any registered flag or argument.
	//
	// Unmapped inputs may be used to collect slices of positional arguments when
	// singular arguments can't be used.  For these situations, consider using
	// CommandBuilder.WithUnmappedLabel to set a help-text label indicating that
	// the command expects an arbitrary number of positional arguments.
	//
	// Defined positional arguments will always be hit before a value is added to
	// a command's unmapped inputs.
	UnmappedInputs() []string

	// HasUnmappedInputs indicates whether the command has collected any inputs
	// that were not mapped to any registered flag or argument.
	HasUnmappedInputs() bool

	// PassthroughInputs are command line values that were passed after an
	// end-of-arguments boundary, "--".
	PassthroughInputs() []string

	// HasPassthroughInputs indicates whether this command has collected any
	// passthrough input values.
	HasPassthroughInputs() bool

	// GetUnmappedLabel returns the label used when generating help text to
	// indicate the shape or purpose of unmapped inputs.
	GetUnmappedLabel() string

	// HasUnmappedLabel indicates whether an unmapped label has been set on this
	// command instance.
	HasUnmappedLabel() bool

	Warnings() []string

	AppendWarning(warning string)
	// contains filtered or unexported methods
}

Command represents a singular, non-nested command which accepts flags and arguments.

type CommandBranch

type CommandBranch interface {
	CommandNode
	CommandParent
	CommandChild
	// contains filtered or unexported methods
}

CommandBranch represents a subcommand under a CommandTree that is an intermediate node between the tree root and an executable CommandLeaf.

CommandBranches enable the organization of subcommands into categories.

Example command tree:

docker
 |- compose
 |   |- build
 |   |- down
 |   |- ...
 |- container
 |   |- exec
 |   |- ls
 |   |- ...
 |- ...

type CommandBranchBuilder

type CommandBranchBuilder interface {

	// WithAliases appends the given alias strings to this CommandBranchBuilder's
	// alias list.
	//
	// Aliases must be unique and must not conflict with any other command branch
	// or leaf names or aliases at a given command tree level.
	//
	// Example:
	//     cli.CommandBranch("service").
	//         WithAliases("svc")
	WithAliases(aliases ...string) CommandBranchBuilder

	// WithDescription sets a description value for the CommandBranch being built.
	//
	// Descriptions are used when rendering help text.
	WithDescription(desc string) CommandBranchBuilder

	// WithHelpDisabled disables the automatic '-h | --help' flag that is enabled
	// by default.
	WithHelpDisabled() CommandBranchBuilder

	// WithBranch appends a child branch to the default CommandGroup for this
	// CommandBranchBuilder.
	WithBranch(branch CommandBranchBuilder) CommandBranchBuilder

	// WithLeaf appends a child leaf to the default CommandGroup for this
	// CommandBranchBuilder.
	WithLeaf(leaf CommandLeafBuilder) CommandBranchBuilder

	// WithCommandGroup appends a custom CommandGroup to this
	// CommandBranchBuilder.
	//
	// CommandGroups are used to organize subcommands into named categories that
	// are primarily used for rendering help text.
	WithCommandGroup(group CommandGroupBuilder) CommandBranchBuilder

	// WithFlag appends the given FlagBuilder to the default FlagGroup attached to
	// this CommandBranchBuilder.
	WithFlag(flag FlagBuilder) CommandBranchBuilder

	// WithFlagGroup appends the given custom FlagGroupBuilder to this
	// CommandBranchBuilder instance.
	//
	// Custom flag groups are primarily used for categorizing flags in the
	// rendered help text.
	WithFlagGroup(flagGroup FlagGroupBuilder) CommandBranchBuilder

	WithCallback(cb CommandBranchCallback) CommandBranchBuilder

	// OnIncomplete sets the incomplete command handler.
	//
	// The incomplete command handler is called when a command tree is called, but
	// a leaf node is not reached.
	//
	// If this is unset, the default behavior is to print the help text for the
	// furthest command node reached and exit with code 1.
	OnIncomplete(handler OnIncompleteHandler) CommandBranchBuilder

	Build(warnings *WarningContext) (CommandBranch, error)
	// contains filtered or unexported methods
}

A CommandBranchBuilder instance may be used to configure a new CommandBranch instance to be built.

CommandBranches are intermediate steps between the root of the CommandTree and the CommandLeaf instances.

For example, given the following command example, the tree is "foo", the branch is "bar", and the leaf is "fizz":

./foo bar fizz

func NewCommandBranchBuilder

func NewCommandBranchBuilder(name string) CommandBranchBuilder

type CommandBranchCallback

type CommandBranchCallback = func(branch CommandBranch)

type CommandBuilder

type CommandBuilder interface {

	// WithDescription sets the description value that will be used for the built
	// Command instance.
	//
	// Command descriptions are used when rendering help text.
	WithDescription(desc string) CommandBuilder

	WithHelpDisabled() CommandBuilder

	// WithFlagGroup appends the given FlagGroupBuilder to this CommandBuilder
	// instance.
	WithFlagGroup(group FlagGroupBuilder) CommandBuilder

	// WithFlag attaches the given FlagBuilder to the default FlagGroupBuilder
	// instance attached to this CommandBuilder.
	WithFlag(flag FlagBuilder) CommandBuilder

	// WithArgument appends the given ArgumentBuilder to this CommandBuilder's
	// list of positional arguments.
	WithArgument(arg ArgumentBuilder) CommandBuilder

	// WithUnmappedLabel sets the help-text label for unmapped arguments.
	//
	// This is useful when your command takes an arbitrary number of argument
	// inputs, and you would like the help text to indicate as such.
	//
	// Example Config:
	//     cli.Command().
	//         WithUnmappedLabel("[FILE...]")
	//
	// Example Result:
	//     Usage:
	//       my-command [FILE...]
	WithUnmappedLabel(label string) CommandBuilder

	// WithCallback sets a callback function that will be executed immediately
	// after CLI parsing has completed successfully.
	WithCallback(cb CommandCallback) CommandBuilder

	Build(ctx *WarningContext) (Command, error)

	// Parse reads the given arguments and attempts to populate the built Command
	// instance based on the values parsed from the given inputs.
	Parse(args []string) (Command, error)

	// MustParse is the same as Parse, however if an error is encountered while
	// building the Command or parsing the input arguments, this method will
	// panic.
	MustParse(args []string) Command
}

A CommandBuilder provides an API to configure the construction of a new Command instance.

Example Usage:

cli.Command().
    WithDescription("This is my command that does something.").
    WithFlag(cli.Flag().
        WithShortForm('v').
        WithLongForm("verbose").
        WithDescription("Enable verbose logging.")
        WithBinding(&config.verbose)).
    WithArgument(cli.Argument().
        WithName("file").
        WithDescription("File path.").
        WithBinding(&config.file)).
    Build()

func NewCommandBuilder

func NewCommandBuilder() CommandBuilder

type CommandCallback added in v1.1.0

type CommandCallback = func(command Command)

type CommandChild

type CommandChild interface {
	CommandNode

	// HasAliases indicates whether this CommandChild has alias strings that may
	// be used to reference this CommandChild instead of the CommandChild's
	// assigned name.
	HasAliases() bool

	// Aliases returns the aliases attached to this CommandChild.
	Aliases() []string

	// Matches tests whether the branch name or any of its aliases match the given
	// string.
	Matches(name string) bool
}

A CommandChild is a CommandNode that is the child of another CommandNode.

type CommandGroup

type CommandGroup interface {

	// Name returns the custom name for the CommandGroup.
	Name() string

	// Description returns the description value set on this CommandGroup.
	//
	// If no description was set on this CommandGroup, this method will return an
	// empty string.
	Description() string

	// HasDescription indicates whether a description value was set on this
	// CommandGroup.
	HasDescription() bool

	// Branches returns the CommandBranch nodes attached to this CommandGroup.
	Branches() []CommandBranch

	// HasBranches indicates whether this CommandGroup contains any branch nodes.
	HasBranches() bool

	// Leaves returns the CommandLeaf nodes attached to this CommandGroup.
	Leaves() []CommandLeaf

	// HasLeaves indicates whether this CommandGroup contains any leaf nodes.
	HasLeaves() bool

	// FindChild searches this CommandGroup instance for a CommandBranch or
	// CommandLeaf node that matches the given string.
	//
	// Commands may match on either their name or one of their aliases.
	FindChild(name string) CommandChild
}

A CommandGroup is an organizational category containing one or more commands.

type CommandGroupBuilder

type CommandGroupBuilder interface {

	// WithDescription sets a description value for this CommandGroupBuilder.
	//
	// Descriptions are used when rendering help text.
	WithDescription(desc string) CommandGroupBuilder

	// WithBranch appends the given branch builder to this command group builder.
	WithBranch(branch CommandBranchBuilder) CommandGroupBuilder

	// WithLeaf appends the given leaf builder to this command group builder.
	WithLeaf(leaf CommandLeafBuilder) CommandGroupBuilder

	// Build attempts to build a new CommandGroup instance from the set
	// configuration.
	Build(warnings *WarningContext) (CommandGroup, error)
	// contains filtered or unexported methods
}

A CommandGroupBuilder is used to construct a CommandGroup instance.

func NewCommandGroupBuilder

func NewCommandGroupBuilder(name string) CommandGroupBuilder

type CommandLeaf

type CommandLeaf interface {
	CommandNode
	CommandChild
	Command
	// contains filtered or unexported methods
}

A CommandLeaf is the final node in a CommandTree branch.

Command leaves may be children of either a CommandTree directly, or of a CommandBranch.

type CommandLeafBuilder

type CommandLeafBuilder interface {

	// WithAliases attaches the given aliases to this CommandLeafBuilder.
	//
	// Command aliases must be unique per level in a command tree.  This means
	// that for a given step in the tree, no alias may conflict with another
	// CommandNode's name or aliases.
	//
	// If a conflict is found, an error will be returned when attempting to build
	// the CommandLeaf.
	WithAliases(aliases ...string) CommandLeafBuilder

	// WithDescription sets a description for the CommandLeaf to be built.
	//
	// Descriptions are used when rendering help text.
	WithDescription(desc string) CommandLeafBuilder

	WithHelpDisabled() CommandLeafBuilder

	// WithUnmappedLabel provides a label for unmapped inputs.
	//
	// The unmapped label value is used when rendering the command usage line of
	// the auto-generated help text.  If a command expects an unknown number of
	// positional argument values, it is best to capture them as unmapped inputs
	// with a label.
	//
	// Example configuration:
	//     cli.CommandLeaf("my-leaf").
	//         WithUnmappedLabel("ITEMS...")
	//
	// Example usage line:
	//     Usage:
	//       my-leaf [ITEMS...]
	WithUnmappedLabel(label string) CommandLeafBuilder

	// WithCallback sets a callback on the CommandLeaf to be built that will be
	// executed when the command leaf is used, after any tree or branch callbacks
	// that were set on parent nodes.
	WithCallback(cb CommandLeafCallback) CommandLeafBuilder

	// WithArgument adds a positional argument to the CommandLeaf being built.
	WithArgument(argument ArgumentBuilder) CommandLeafBuilder

	// WithFlagGroup adds a new FlagGroup to this CommandLeaf being built.
	WithFlagGroup(flagGroup FlagGroupBuilder) CommandLeafBuilder

	// WithFlag adds the given flag to the default FlagGroup for the CommandLeaf
	// being built.
	WithFlag(flag FlagBuilder) CommandLeafBuilder

	Build(warnings *WarningContext) (CommandLeaf, error)
	// contains filtered or unexported methods
}

CommandLeafBuilder defines a builder type that is used to construct CommandLeaf instances.

func NewCommandLeafBuilder

func NewCommandLeafBuilder(name string) CommandLeafBuilder

type CommandLeafCallback

type CommandLeafCallback = func(leaf CommandLeaf)

CommandLeafCallback defines the function type for a callback function that may be attached to a CommandLeaf.

A CommandLeaf's callback function will be called once if and when a CommandLeaf is used in a CLI call.

type CommandNode

type CommandNode interface {

	// Parent returns the parent CommandNode for the current CommandNode.
	//
	// If the current CommandNode does not have a parent (meaning it is the
	// CommandTree instance) this method will return nil.
	Parent() CommandNode

	// HasParent indicates whether this CommandNode has a parent node.
	//
	// This means that the current CommandNode instance is either a branch or a
	// leaf node.
	HasParent() bool

	// Name returns the name of the command or subcommand.
	//
	// For the CommandTree node, this method will return the name of the CLI
	// command that was called.
	//
	// For branch and leaf nodes, it will return the assigned name of that node.
	Name() string

	// Description returns the description value assigned to this node.
	//
	// Description values are used when rendering help text.
	Description() string

	// HasDescription indicates whether this CommandNode has a description value
	// set.
	HasDescription() bool

	// FlagGroups returns the flag groups assigned to this CommandNode.
	//
	// This method will only return flag groups that had flags assigned to them,
	// the rest of the flag groups will have been filtered out when the node was
	// built.
	FlagGroups() []FlagGroup

	// HasFlagGroups indicates whether this CommandNode has at least one populated
	// flag group.
	HasFlagGroups() bool

	// FindShortFlag looks up a target Flag instance by its short-form character.
	//
	// If no such flag exists on this CommandNode or any of its parents, this
	// method will return nil.
	FindShortFlag(c byte) Flag

	// FindLongFlag looks up a target Flag instance by its long-form name.
	//
	// If no such flag exists on this CommandNode or any of its parents, this
	// method will return nil.
	FindLongFlag(name string) Flag

	Warnings() []string

	AppendWarning(warning string)
}

A CommandNode is a base type common to all elements in a CommandTree.

type CommandParent

type CommandParent interface {
	CommandNode

	// CommandGroups returns the CommandGroup instances attached to this
	// CommandParent node.
	CommandGroups() []CommandGroup

	// FindChild searches this CommandParent's CommandGroup instances for a
	// subcommand that matches the given string.
	//
	// A subcommand may match on either its name or one of its aliases.
	FindChild(name string) CommandChild
	// contains filtered or unexported methods
}

A CommandParent is a CommandNode instance that may contain child CommandNode instances.

type CommandTree

type CommandTree interface {
	CommandNode
	CommandParent

	// SelectedCommand returns the leaf command that was selected in the CLI call.
	SelectedCommand() CommandLeaf
	// contains filtered or unexported methods
}

CommandTree represents the root of a tree of subcommands.

The command tree consists of branch and leaf nodes. The branch nodes can be thought of as categories for containing sub-branches and/or leaves. Leaf nodes are the actual callable command implementations.

All levels of the command tree accept flags, with sub-node flags taking priority over parent node flags on flag collision. Leaf nodes, however, are the only nodes that accept positional arguments, or passthroughs.

Example command tree:

docker
 |- compose
 |   |- build
 |   |- down
 |   |- ...
 |- container
 |   |- exec
 |   |- ls
 |   |- ...
 |- ...

type CommandTreeBuilder

type CommandTreeBuilder interface {

	// WithDescription sets a description value for the root of this command tree.
	//
	// Descriptions are used when rendering help text.
	WithDescription(desc string) CommandTreeBuilder

	// WithCallback sets a callback for the CommandTree being built.
	//
	// If set, this callback will be executed on parsing success.  Each level of
	// a command tree may have a callback.  The callbacks are called in the order
	// the command segments appear in the CLI call.
	WithCallback(cb CommandTreeCallback) CommandTreeBuilder

	// WithHelpDisabled disables the automatic `-h` and `--help` flags for
	// rendering help text.
	WithHelpDisabled() CommandTreeBuilder

	// WithBranch appends the given branch builder to be built with this command
	// tree.
	//
	// The built branch will be available as a subcommand directly under the root
	// command call.
	WithBranch(branch CommandBranchBuilder) CommandTreeBuilder

	// WithLeaf appends the given leaf builder to be built with this command tree.
	//
	// The built leaf will be available as a subcommand directly under the root
	// command call.
	WithLeaf(leaf CommandLeafBuilder) CommandTreeBuilder

	// WithCommandGroup appends the given command group builder to be built with
	// this command tree.
	//
	// Command groups are used for organizing subcommands into named groups that
	// are primarily used for rendering help text.
	WithCommandGroup(group CommandGroupBuilder) CommandTreeBuilder

	// WithFlag appends the given flag builder to the default flag group attached
	// to this command tree builder.  The default flag group is an automatically
	// created group for containing otherwise ungrouped flags.
	WithFlag(flag FlagBuilder) CommandTreeBuilder

	// WithFlagGroup appends the given flag group builder to this command tree
	// builder.  Flag groups are for organizing flags into named categories that
	// are primarily used for rendering help text.
	WithFlagGroup(flagGroup FlagGroupBuilder) CommandTreeBuilder

	// OnIncomplete sets the incomplete command handler.
	//
	// The incomplete command handler is called when a command tree is called, but
	// a leaf node is not reached.
	//
	// If this is unset, the default behavior is to print the help text for the
	// furthest command node reached and exit with code 1.
	//
	// Child nodes will inherit this handler if they do not have their own custom
	// handler set.
	OnIncomplete(handler OnIncompleteHandler) CommandTreeBuilder

	Build(warnings *WarningContext) (CommandTree, error)

	// Parse builds the command tree and attempts to parse the given CLI arguments
	// into that command tree's components.
	Parse(args []string) (CommandTree, error)

	// MustParse calls Parse and panics if an error is returned.
	MustParse(args []string) CommandTree
	// contains filtered or unexported methods
}

A CommandTreeBuilder is a builder type used to construct a CommandTree instance.

A CommandTree is a command that consists of branching subcommands. Examples of such commands include the `go` command, `docker`, or `kubectl`.

To use the Docker command example we have a command tree that includes the following:

docker
 |- compose
 |   |- build
 |   |- down
 |   |- ...
 |- container
 |   |- exec
 |   |- ls
 |   |- ...
 |- ...

func NewCommandTreeBuilder

func NewCommandTreeBuilder() CommandTreeBuilder

type CommandTreeCallback

type CommandTreeCallback = func(com CommandTree)

type Flag

type Flag interface {

	// ShortForm returns the short-form character representing this Flag.
	ShortForm() byte

	// HasShortForm indicates whether this Flag has a short-form character.
	HasShortForm() bool

	// LongForm returns the long-form string representing this Flag.
	LongForm() string

	// HasLongForm indicates whether this Flag has a long-form string.
	HasLongForm() bool

	// Description returns the help-text description of this flag.
	Description() string

	// HasDescription indicates whether this Flag has a help-text description.
	HasDescription() bool

	// Argument returns the argument value attached to this Flag.
	//
	// If this Flag does not have an Argument attached, this method will return
	// nil.
	Argument() Argument

	// HasArgument indicates whether this Flag accepts an argument.
	HasArgument() bool

	// IsRequired indicates whether this Flag is required.
	//
	// Required flags must be present in the CLI call.
	IsRequired() bool

	// RequiresArgument indicates whether this flag has an argument that is
	// required.
	RequiresArgument() bool

	// WasHit indicates whether this flag was used in the CLI call.
	WasHit() bool

	// HitCount returns the number of times that this flag was used in the CLI
	// call.
	HitCount() int

	AppendWarning(warning string)
	// contains filtered or unexported methods
}

Flag represents a single CLI flag which may have an argument.

type FlagBuilder

type FlagBuilder interface {

	// WithShortForm sets the short-form flag character that the flag may be
	// referenced by on the CLI.
	//
	// Short-form flags consist of a single character preceded by either a
	// prefix/leader character, or by one or more other short-form flags.
	//
	// Short-form flags must be alphanumeric.
	//
	// Examples:
	//     # Single, unchained short flags.
	//     -f
	//     -f bar
	//     -f=bar
	//     # Multiple short flags chained.  In these examples, the short flag '-c'
	//     # takes an optional string argument, which will be "def" in the last
	//     # two examples.
	//     -abc
	//     -abc def
	//     -abc=def
	WithShortForm(char byte) FlagBuilder

	// WithLongForm sets the long-form flag name that the flag may be referenced
	// by on the CLI.
	//
	// Long-form flags consist of one or more characters preceded immediately by
	// two prefix/leader characters (typically dashes).
	//
	// Long-form flags must start with an alphanumeric character and may only
	// consist of alphanumeric characters, dashes, and/or underscores.
	//
	// Example long-form flags:
	//     # The '--foo' flag takes an optional string argument
	//     --foo
	//     --foo bar
	//     --foo=bar
	WithLongForm(form string) FlagBuilder

	// WithDescription sets an optional description value for the Flag being
	// built.
	//
	// The description value is used for rendering help text.
	WithDescription(desc string) FlagBuilder

	// WithCallback provides a function that will be called when a Flag is hit
	// while parsing the CLI inputs.
	//
	// The given function will be called after parsing has completed, regardless
	// of whether there were parsing errors.
	//
	// Flag on-hit callbacks will be executed in priority order with the higher
	// priority values executing before lower priority values.  For flags that
	// have the same priority, the callbacks will be called in the order the flags
	// appeared in the CLI call.
	WithCallback(fn FlagCallback) FlagBuilder

	// WithArgument attaches the given argument to the Flag being built.
	//
	// Only one argument may be set on a Flag at a time.
	WithArgument(arg ArgumentBuilder) FlagBuilder

	// WithBinding is a shortcut method for attaching an argument and binding it
	// to the given pointer.
	//
	// Bind is equivalent to calling one of the following:
	//    WithArgument(cli.Argument().Bind(ptr))
	//    // or
	//    WithArgument(cli.Argument().Bind(ptr).Require())
	WithBinding(pointer any, required bool) FlagBuilder

	// WithBindingAndDefault is a shortcut method for attaching an argument,
	// binding it to the given pointer, and setting a default on that argument.
	//
	// BindWithDefault is equivalent to calling one of the following:
	//     WithArgument(cli.Argument().WithBinding(ptr).WithDefault(something))
	//     // or
	//     WithArgument(cli.Argument().WithBinding(ptr).WithDefault(something).Require())
	WithBindingAndDefault(pointer, def any, required bool) FlagBuilder

	// Require marks this Flag as being required.
	//
	// If this flag is not present in the CLI call, an error will be returned when
	// parsing the CLI input.
	Require() FlagBuilder

	// Build builds a new Flag instance constructed from the components set on
	// this FlagBuilder.
	Build(warnings *WarningContext) (Flag, error)
	// contains filtered or unexported methods
}

A FlagBuilder is used to construct a Flag instance which represents the input from the CLI call.

func NewFlagBuilder

func NewFlagBuilder() FlagBuilder

NewFlagBuilder returns a new FlagBuilder instance.

type FlagCallback

type FlagCallback = func(flag Flag)

A FlagCallback is a function that, if set on a flag, will be called by the CLI parsing process if that flag is used in the CLI call.

The flag callback will be called after CLI parsing has completed.

type FlagGroup

type FlagGroup interface {

	// Name of the FlagGroup.
	//
	// This value will be used when rendering help text.
	Name() string

	// Description for this FlagGroup.
	//
	// This optional value will be used when rendering help text.
	Description() string

	// HasDescription indicates whether this FlagGroup has a description attached.
	HasDescription() bool

	// Flags returns the Flag instances contained by this FlagGroup.
	Flags() []Flag

	// FindShortFlag checks this FlagGroup's contents for a flag with the given
	// short flag character.  If one could not be found, this method returns nil.
	FindShortFlag(c byte) Flag

	// FindLongFlag checks this FlagGroup's contents for a flag with the given
	// long flag name.  If one could not be found, this method returns nil.
	FindLongFlag(name string) Flag
	// contains filtered or unexported methods
}

A FlagGroup is a named group or category for a collection of one or more Flag instances.

Flag groups are primarily used to categorize CLI flags when rendering help text.

Flag groups that do not contain any flags will be filtered out at build time.

type FlagGroupBuilder

type FlagGroupBuilder interface {

	// WithDescription sets a description value on this FlagGroupBuilder.
	WithDescription(desc string) FlagGroupBuilder

	// WithFlag appends the given FlagBuilder instance to this FlagGroupBuilder.
	WithFlag(flag FlagBuilder) FlagGroupBuilder

	Build(warnings *WarningContext) (FlagGroup, error)
	// contains filtered or unexported methods
}

A FlagGroupBuilder is used to build a group or category of flags that go together. This is primarily used for rendering help text.

FlagGroups are not required but allow for organizing the help text when there are many flags attached to a command.

func NewFlagGroupBuilder

func NewFlagGroupBuilder(name string) FlagGroupBuilder

type FormatError

type FormatError interface {
	UnmarshallingError

	Argument() string

	Kind() reflect.Kind

	Root() error
}

type HelpRenderer

type HelpRenderer[T any] interface {

	// RenderHelp renders help text for the given command and writes it to the
	// given io.Writer instance.
	RenderHelp(command T, writer io.Writer) error
}

A HelpRenderer is a type that renders help text for the given type to the given io.Writer instance.

This interface may be implemented to provide custom help rendering for your command.

func CommandBranchHelpRenderer

func CommandBranchHelpRenderer() HelpRenderer[CommandBranch]

CommandBranchHelpRenderer returns a HelpRenderer instance that is suited to rendering help text for CommandBranch instances.

func CommandHelpRenderer

func CommandHelpRenderer() HelpRenderer[Command]

CommandHelpRenderer returns a HelpRenderer instance that is suited to rendering help text for Command instances.

func CommandLeafHelpRenderer

func CommandLeafHelpRenderer() HelpRenderer[CommandLeaf]

CommandLeafHelpRenderer returns a HelpRenderer instance that is suited to rendering help text for CommandLeaf instances.

func CommandTreeHelpRenderer

func CommandTreeHelpRenderer() HelpRenderer[CommandTree]

CommandTreeHelpRenderer returns a HelpRenderer instance that is suited to rendering help text for CommandTree instances.

type Hex

type Hex int

Hex represents an untyped signed int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*Hex) Unmarshal

func (h *Hex) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Hex type.

type Hex16

type Hex16 int16

Hex16 represents a signed 16 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*Hex16) Unmarshal

func (h *Hex16) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Hex16 type.

type Hex32

type Hex32 int32

Hex32 represents a signed 32 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*Hex32) Unmarshal

func (h *Hex32) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Hex32 type.

type Hex64

type Hex64 int64

Hex64 represents a signed 64 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*Hex64) Unmarshal

func (h *Hex64) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the Hex64 type.

type Hex8

type Hex8 int8

Hex8 represents a signed 8 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*Hex8) Unmarshal

func (h *Hex8) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Hex8 type.

type InvalidArgError

type InvalidArgError struct {
	// contains filtered or unexported fields
}

func (*InvalidArgError) Builder

func (i *InvalidArgError) Builder() ArgumentBuilder

func (*InvalidArgError) Error

func (i *InvalidArgError) Error() string

func (*InvalidArgError) Is

func (*InvalidArgError) Type

type MissingFlagError

type MissingFlagError interface {
	error
	Flag() Flag
}

A MissingFlagError is returned on CLI parse when a flag that has been marked as being required was not found to be present in the CLI call.

MissingFlagError is a hard error that will be returned regardless of whether the parser is operating in strict mode.

type MissingRequiredArgumentError

type MissingRequiredArgumentError interface {
	error
	Argument() Argument
	Flag() Flag
	HasFlag() bool
}

type MultiError

type MultiError interface {
	error

	// Errors returns a slice of all the errors collected into this MultiError
	// instance.
	Errors() []error

	// AppendError appends the given error to this MultiError.  If the given error
	// is itself a MultiError, it will be unpacked into this MultiError instance.
	AppendError(err error)
}

A MultiError is an error instance that contains a collection of sub-errors of any type except MultiError.

type NumericValue added in v1.1.0

type NumericValue interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
}

NumericValue defines the numeric types that Argonaut can parse.

type Octal

type Octal int

Octal represents an untyped signed int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*Octal) Unmarshal

func (o *Octal) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Octal type.

type Octal16

type Octal16 int16

Octal16 represents a signed 16 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*Octal16) Unmarshal

func (o *Octal16) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Octal16 type.

type Octal32

type Octal32 int32

Octal32 represents a signed 32 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*Octal32) Unmarshal

func (o *Octal32) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Octal32 type.

type Octal64

type Octal64 int64

Octal64 represents a signed 64 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*Octal64) Unmarshal

func (o *Octal64) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Octal64 type.

type Octal8

type Octal8 int8

Octal8 represents a signed 8 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*Octal8) Unmarshal

func (o *Octal8) Unmarshal(value string) error

Unmarshal implements the Unmarshaler.Unmarshal method for the Octal8 type.

type OnIncompleteHandler added in v1.1.0

type OnIncompleteHandler = func(command CommandParent)

OnIncompleteHandler defines a function type that may be used as a callback for when a command leaf is not reached when parsing a command tree structure.

type Scanner added in v1.2.0

type Scanner[T any] interface {
	// HasNext indicates whether there is at least one more segment available.
	HasNext() bool

	// Next returns the next segment.
	Next() T
}

Scanner defines an iterator over a given input that breaks the input into segments through some internal mechanism.

For example, a scanner may break an input reader into lines of text, or split a string on a specific delimiter.

func DelimitedSliceScanner added in v1.2.0

func DelimitedSliceScanner(input, delimiters string) Scanner[string]

DelimitedSliceScanner returns a new scanner over the given string, breaking it into substrings on every delimiter character.

Examples:

// Comma separated values:
DelimitedSliceScanner("hello,world", ",")
// Comma or semicolon separated values.
DelimitedSliceScanner("goodbye,cruel;world", ",;")

Parameters:

  1. input = Input string that will be scanned.
  2. delimiters = Set of delimiter characters. If this string is empty, the scanner will return the whole input string on the first call to Next.
Example (CommaSeparatedValues)
package main

import (
	"fmt"

	"github.com/Foxcapades/Argonaut/pkg/argo"
)

func main() {
	scanner := argo.DelimitedSliceScanner("goodbye,cruel,world", ",")
	values := make([]string, 0, 3)

	for scanner.HasNext() {
		values = append(values, scanner.Next())
	}

	fmt.Println(values)

}
Output:

[goodbye cruel world]

type StringScannerFactory added in v1.2.0

type StringScannerFactory = func(input string) Scanner[string]

type UHex

type UHex uint

UHex represents an untyped unsigned int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*UHex) Unmarshal

func (h *UHex) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UHex type.

type UHex16

type UHex16 uint16

UHex16 represents an unsigned 16 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*UHex16) Unmarshal

func (h *UHex16) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UHex16 type.

type UHex32

type UHex32 uint32

UHex32 represents an unsigned 32 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*UHex32) Unmarshal

func (h *UHex32) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UHex32 type.

type UHex64

type UHex64 uint64

UHex64 represents an unsigned 64 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*UHex64) Unmarshal

func (h *UHex64) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UHex64 type.

type UHex8

type UHex8 uint8

UHex8 represents an unsigned 8 bit int value that is expected to be input in hexadecimal notation and will be parsed from string in base 16.

func (*UHex8) Unmarshal

func (h *UHex8) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UHex8 type.

type UOctal

type UOctal uint

UOctal represents an untyped unsigned int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*UOctal) Unmarshal

func (o *UOctal) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UOctal type.

type UOctal16

type UOctal16 uint16

UOctal16 represents an unsigned 16 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*UOctal16) Unmarshal

func (o *UOctal16) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UOctal16 type.

type UOctal32

type UOctal32 uint32

UOctal32 represents an unsigned 32 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*UOctal32) Unmarshal

func (o *UOctal32) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UOctal32 type.

type UOctal64

type UOctal64 uint64

UOctal64 represents an unsigned 64 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*UOctal64) Unmarshal

func (o *UOctal64) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UOctal64 type.

type UOctal8

type UOctal8 uint8

UOctal8 represents an unsigned 8 bit int value that is expected to be input in octal notation and will be parsed from string in base 8.

func (*UOctal8) Unmarshal

func (o *UOctal8) Unmarshal(value string) (err error)

Unmarshal implements the Unmarshaler.Unmarshal method for the UOctal8 type.

type UnmarshalIntegerProps

type UnmarshalIntegerProps struct {

	// OctalLeaders defines the prefixes used to signify that a value should be
	// parsed as octal.
	//
	// An empty slice will disable octal value parsing.
	//
	// Default: ["0o", "0O", "o", "O", "0"]
	//
	// Example octal values using the default prefixes:
	//
	//     o666    O666
	//     o0666   O0666
	//     0o666   0O666
	//     0o0666  0O0666
	//     0666
	OctalLeaders []string `json:"octalLeaderChars"`

	// HexLeaders defines the prefixes used to signify that a value should be
	// parsed as hexadecimal.
	//
	// An empty slice will disable hex value parsing.
	//
	// Default: ["0x", "0X", "x", "X"]
	//
	// Example hex values using the default prefixes:
	//
	//     xFA9    XFA9
	//     xfa9    Xfa9
	//     0xFA9   0XFA9
	//     0xfa9   0Xfa9
	HexLeaders []string `json:"hexLeaderChars"`

	// The integer base to use when no prefix is present.
	//
	// Default: base 10
	DefaultBase int `json:"defaultBase"`
}

UnmarshalIntegerProps defines int parsing specific options for the "magic" unmarshaler.

type UnmarshalMapProps

type UnmarshalMapProps struct {

	// KeyValSeparatorChars defines characters used to separate a key from a value
	// in an individual mapping entry.
	//
	// This character can be escaped with a '\' (backslash) character.
	//
	// The first unescaped instance of one of the defined characters in the
	// individual entry will be used as the divider, and any subsequent
	// appearances in the entry will be included in the value.
	//
	// Default: "=:" (equals, colon)
	//
	// Example key/value pairs using the default divider characters.  The second
	// column is a JSON representation of the parsed map
	//
	//     key:value            {"key": "value"}
	//     key=value            {"key": "value"}
	//     key\\:foo:value      {"key:foo": "value"}
	//     key\\=bar=value      {"key=bar": "value"}
	//     key\\:baz=value:a=b  {"key:baz": "value:a=b"}
	//     key:value=c:d        {"key": "value=c:d"}
	KeyValSeparatorChars string

	// Default: ",; " (comma, semicolon, space)
	EntrySeparatorChars string
}

UnmarshalMapProps defines map specific unmarshalling options for the "magic" unmarshaler.

type UnmarshalProps

type UnmarshalProps struct {

	// Integers defines settings for parsing integral types (int, int*, uint,
	// uint*).
	Integers UnmarshalIntegerProps `json:"integers"`

	// Maps defines settings to use when parsing mappings from the command line
	Maps UnmarshalMapProps `json:"maps"`

	Slices UnmarshalSliceProps `json:"slices"`

	Time UnmarshalTimeProps `json:"time"`
}

UnmarshalProps defines configuration options for the included "magic" Unmarshaler implementation.

This configuration may be used to customize how the unmarshaler behaves or parses input values.

func DefaultUnmarshalProps

func DefaultUnmarshalProps() UnmarshalProps

DefaultUnmarshalProps returns an UnmarshalProps instance with the default values configured.

type UnmarshalSliceProps

type UnmarshalSliceProps struct {
	// Scanner is a function that provides a text scanner that will be used to
	// break an argument string into individual slice elements.
	//
	// The values split by the scanner will then be parsed into the type expected
	// by the argument binding slice.
	//
	// The default scanner breaks strings on comma characters.
	//
	// For example, given the input string "foo,bar,fizz,buzz" use of the default
	// scanner would result in a slice containing the values:
	// [ foo, bar, fizz, buzz ]
	Scanner StringScannerFactory

	// The ByteSliceParser property controls the parser that will be used to
	// deserialize a raw argument string into a byte slice.
	//
	// This function will be called with the raw CLI input and will be expected to
	// return either the parsed byte slice or an error.  If the function returns
	// an error it will be passed up like any other parsing error.
	//
	// The default ByteSliceParser implementation takes the raw string and
	// directly casts it to a byte slice.
	//
	// WARNING: In v2 the default behavior will be changed to expect base64 input.
	ByteSliceParser ByteSliceParser
}

UnmarshalSliceProps defines options for slice unmarshalling in the "magic" unmarshaler.

type UnmarshalTimeProps added in v1.1.0

type UnmarshalTimeProps struct {
	// DateFormats configures the date-time formats that the unmarshaler will use
	// when attempting to parse a date value.
	//
	// By default, the RFC3339 and RFC3339 nano patterns are used.
	DateFormats []string
}

type Unmarshaler

type Unmarshaler interface {

	// Unmarshal is handed the raw string for its obviously nefarious purposes and
	// may return an error.
	Unmarshal(raw string) error
}

Unmarshaler defines a type that may be used as an Argument binding value to unmarshal the given raw string into a custom type.

Example 1:

cli.Argument()
    WithBinding(UnmarshalerFunc(func(raw string) error {
        // Do something with the raw string
        return nil
    })

Example 2:

type MyCustomType struct {
    Value string
}
func (t *MyCustomType) Unmarshal(raw string) error {
    t.Value = raw
    return nil
}

var value MyCustomType

cli.Argument().
    WithBinding(&value)

type UnmarshalerFunc

type UnmarshalerFunc func(raw string) error

UnmarshalerFunc defines a function that implements the Unmarshaler interface.

func (UnmarshalerFunc) Unmarshal

func (u UnmarshalerFunc) Unmarshal(raw string) error

type UnmarshallingError

type UnmarshallingError interface {
	error

	Value() reflect.Value
}

type ValueUnmarshaler

type ValueUnmarshaler interface {

	// Unmarshal accepts a raw value and a pointer to an arbitrary type and is
	// expected to fill the pointer value by parsing the raw string, returning an
	// error if parsing fails.
	Unmarshal(raw string, val any) error
}

ValueUnmarshaler is the internal unmarshaler type that is used to parse input string values into the given pointer (val).

For arguments with a specific type, this may be implemented and passed to the argument builder to use instead of the default "magic" unmarshaler instance.

An example ValueUnmarshaler that is used for a single Argument may safely make assumptions about the type of the provided pointer, however reflection or unsafe pointers will still be required to fill the given pointer value.

If you were reasonable, you could do something like this:

ValueUnmarshalerFunc(func(raw string, val any) error {
    if parsed, err := strconv.Atoi(raw); err != nil {
        return err
    } else {
        rVal := reflect.ValueOf(val)
        if rVal.Kind() != reflect.Pointer {
            return errors.New("value must be a pointer")
        } else {
            rVal.Elem().Set(reflect.ValueOf(parsed))
            return nil
        }
    }
})

And if you are half-baked, you could try this:

ValueUnmarshalerFunc(func(raw string, val any) error {
    if parsed, err := strconv.Atoi(raw); err != nil {
        return err
    } else {
        **(**int)(unsafe.Add(unsafe.Pointer(&val), bits.UintSize/8)) = parsed
        return nil
    }
})

func NewDefaultMagicUnmarshaler

func NewDefaultMagicUnmarshaler() ValueUnmarshaler

NewDefaultMagicUnmarshaler creates a new "magic" ValueUnmarshaler instance using default UnmarshalProps.

This is the default ValueUnmarshaler used by all arguments if not otherwise specified.

func NewMagicUnmarshaler

func NewMagicUnmarshaler(props UnmarshalProps) ValueUnmarshaler

NewMagicUnmarshaler creates a new "magic" ValueUnmarshaler instance using the given UnmarshalProps.

type ValueUnmarshalerFunc

type ValueUnmarshalerFunc func(raw string, val any) error

ValueUnmarshalerFunc defines a function that implements the ValueUnmarshaler interface.

func (ValueUnmarshalerFunc) Unmarshal

func (v ValueUnmarshalerFunc) Unmarshal(raw string, val any) error

type WarningContext

type WarningContext struct {
	// contains filtered or unexported fields
}

func (WarningContext) GetWarnings

func (w WarningContext) GetWarnings() []string

Jump to

Keyboard shortcuts

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