goopt

package module
v1.9.8 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2025 License: MIT Imports: 18 Imported by: 0

README

goopt: a flexible and powerful command-line parser

GoDoc Go Report Card Coverage

goopt is a flexible and powerful command-line option parser for Go applications. It provides a way to define commands, subcommands, flags, and their relationships declaratively or programmatically, offering both ease of use and extensibility.

📚 View Documentation (wip)

Key Features

  • Declarative and Programmatic Definition: Supports both declarative struct tag parsing and programmatic definition of commands and flags.
  • Command and Flag Grouping: Organize commands and flags hierarchically, supporting global, command-specific, and shared flags.
  • Flag Dependencies: Enforce flag dependencies based on the presence or specific values of other flags.
  • POSIX Compatibility: Offers POSIX-compliant flag parsing, including support for short flags.
  • Secure Flags: Enable secure, hidden input for sensitive information like passwords.
  • Automatic Usage Generation: Automatically generates usage documentation based on defined flags and commands.
  • Positional Arguments: Support for positional arguments with flexible position and index constraints.

Installation

Install goopt via go get:

go get github.com/napalu/goopt

Quick Start

Struct-based Definition
package main

import (
    "os"
    "fmt"
    "github.com/napalu/goopt"
)

type Config struct {
    // Global flags
    Verbose bool   `goopt:"short:v;desc:Enable verbose output"`
    Output  string `goopt:"short:o;desc:Output file;required:true"`
    // Command with subcommands
    Create struct {
        Force bool `goopt:"short:f;desc:Force creation"`
        User struct {
            Username string `goopt:"short:u;desc:Username;required:true"`
            Password string `goopt:"short:p;desc:Password;secure:true"`
        } `goopt:"kind:command;name:user;desc:Create user"`
    } `goopt:"kind:command;name:create;desc:Create resources"`
}

func main() {
    cfg := &Config{}
    parser, _:= goopt.NewParserFromStruct(cfg)
    if !parser.Parse(os.Args) {
        parser.PrintUsage(os.Stdout)
        return
    }
}
Programmatic Definition
package main

import (
    "os"
    "fmt"
    "github.com/napalu/goopt"
)   

func main() {
    parser := goopt.NewParser()
    parser.AddCommand(goopt.NewCommand(
        goopt.WithName("create"),
        goopt.WithDescription("Create resources"),
    ))
    parser.AddFlag("verbose", goopt.NewArg(
        goopt.WithShort("v"),
        goopt.WithDescription("Enable verbose output"),
    ))

    if !parser.Parse(os.Args) {
        parser.PrintUsage(os.Stdout)
        return
    }
}

For more examples and detailed documentation, visit the documentation site.


License

goopt is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Contributions should be based on open issues (feel free to open one).

Documentation

Overview

Package goopt provides support for command-line processing.

It supports 4 types of flags:

Single - a flag which expects a value
Chained - flag which expects a delimited value representing elements in a list (and is evaluated as a list)
Standalone - a boolean flag which by default takes no value (defaults to true) but may accept a value which evaluates to true or false
File - a flag which expects a file path

Additionally, commands and sub-commands (Command) are supported. Commands can be nested to represent sub-commands. Unlike the official go.Flag package commands and sub-commands may be placed before, after or mixed in with flags.

Index

Constants

View Source
const DefaultMaxDependencyDepth = 10

DefaultMaxDependencyDepth is the default maximum depth for flag dependencies

View Source
const (
	ExecDir = "${EXEC_DIR}"
)
View Source
const (
	FmtErrorWithString = "%w: %s"
)

Variables

View Source
var (
	// ToKebabCase converts a string to kebab case "my-command-name"
	ToKebabCase = func(s string) string {
		return strcase.ToKebab(s)
	}

	// ToSnakeCase converts a string to snake case "my_command_name"
	ToSnakeCase = func(s string) string {
		return strcase.ToSnake(s)
	}

	// ToScreamingSnake converts a string to screaming snake case "MY_COMMAND_NAME"
	ToScreamingSnake = func(s string) string {
		return strcase.ToScreamingSnake(s)
	}

	// ToLowerCamel converts a string to lower camel case "myCommandName"
	ToLowerCamel = func(s string) string {
		return strcase.ToLowerCamel(s)
	}

	// ToLowerCase converts a string to lower case "mycommandname"
	ToLowerCase = func(s string) string {
		return strings.ToLower(s)
	}

	DefaultCommandNameConverter = ToLowerCase
	DefaultFlagNameConverter    = ToLowerCamel
)

Built-in conversion strategies

Functions

func BindFlagToCmdLine deprecated added in v0.5.3

func BindFlagToCmdLine[T Bindable](s *Parser, data *T, flag string, argument *Argument, commandPath ...string) error

BindFlagToCmdLine is an alias for BindFlagToParser.

Deprecated: Use BindFlagToParser instead. This function will be removed in v2.0.0.

func BindFlagToParser added in v1.7.0

func BindFlagToParser[T Bindable](s *Parser, data *T, flag string, argument *Argument, commandPath ...string) error

BindFlagToParser is a helper function to allow passing generics to the Parser.BindFlag method

func CustomBindFlagToCmdLine deprecated added in v0.5.3

func CustomBindFlagToCmdLine[T any](s *Parser, data *T, proc ValueSetFunc, flag string, argument *Argument, commandPath ...string) error

CustomBindFlagToCmdLine is an alias for CustomBindFlagToParser.

Deprecated: Use CustomBindFlagToParser instead. This function will be removed in v2.0.0.

func CustomBindFlagToParser added in v1.7.0

func CustomBindFlagToParser[T any](s *Parser, data *T, proc ValueSetFunc, flag string, argument *Argument, commandPath ...string) error

CustomBindFlagToParser is a helper function to allow passing generics to the Parser.CustomBindFlag method

Types

type Argument

type Argument struct {
	Description    string
	TypeOf         types.OptionType
	Required       bool
	RequiredIf     RequiredIfFunc
	PreFilter      FilterFunc
	PostFilter     FilterFunc
	AcceptedValues []types.PatternValue
	DependsOn      []string // Deprecated: use DependencyMap instead - will be removed in v2.0.0
	OfValue        []string // Deprecated: use DependencyMap instead - will be removed in v2.0.0
	DependencyMap  map[string][]string
	Secure         types.Secure
	Short          string
	DefaultValue   string
	Capacity       int // For slices, the capacity of the slice, ignored for other types
	Position       *int
}

Argument defines a command-line Flag

func NewArg

func NewArg(configs ...ConfigureArgumentFunc) *Argument

NewArg convenience initialization method to configure flags

func NewArgument

func NewArgument(shortFlag string, description string, typeOf types.OptionType, required bool, secure types.Secure, defaultValue string) *Argument

NewArgument convenience initialization method to describe Flags. Alternatively, Use NewArg to configure Argument using option functions.

func (*Argument) Set added in v1.4.1

func (a *Argument) Set(configs ...ConfigureArgumentFunc) error

Set configures the Argument instance with the provided ConfigureArgumentFunc(s), and returns an error if a configuration results in an error.

Usage example:

arg := &Argument{}
err := arg.Set(
    WithDescription("example argument"),
    WithType(Standalone),
    SetRequired(true),
)
if err != nil {
    // handle error
}

func (*Argument) String added in v1.9.8

func (a *Argument) String() string

String returns a string representation of the Argument instance

type Bindable added in v0.5.3

type Bindable interface {
	~string | int8 | int16 | int32 | int64 | ~int | uint8 | uint16 | uint32 | uint64 | ~uint | float32 | float64 |
		bool | time.Time | time.Duration | []string | []int8 | []int16 | []int32 | []int64 | ~[]int | []uint8 | []uint16 | []uint32 |
		[]uint64 | ~[]uint | []float32 | []float64 | []bool | []time.Time | []time.Duration
}

type ClearConfig

type ClearConfig struct {
	// KeepOptions: keep key/value options seen on command line
	KeepOptions bool
	// KeepErrors: keep errors generated during previous Parse
	KeepErrors bool
	// KeepAcceptedValues: keep value guards
	KeepAcceptedValues bool
	// KeepFilters: Keep filters set during previous configuration
	KeepFilters bool
	// KeepCommands: keep key/value commands seen on command line
	KeepCommands bool
	// KeepPositional: keep positional arguments seen on command line
	// a positional argument is defined as anything passed on the command-line
	// which was not processed as either a flag, a flag value, a command
	// or a command value
	KeepPositional bool
}

ClearConfig allows to selectively clear a set of CmdLineOption configuration data

type CmdLineOption deprecated

type CmdLineOption = Parser

CmdLineOption is an alias for Parser.

Deprecated: Use Parser instead. This type will be removed in v2.0.0.

type Command

type Command struct {
	Name        string
	Subcommands []Command
	Callback    CommandFunc
	Description string
	// contains filtered or unexported fields
}

Command defines commands and sub-commands

func NewCommand

func NewCommand(configs ...ConfigureCommandFunc) *Command

NewCommand creates and returns a new Command object. This function takes variadic `ConfigureCommandFunc` functions to customize the created command.

func (*Command) IsTopLevel added in v1.8.8

func (c *Command) IsTopLevel() bool

IsTopLevel returns whether this is a top-level command

func (*Command) Path added in v1.5.0

func (c *Command) Path() string

Path returns the full path of the command

func (*Command) Set added in v1.5.2

func (c *Command) Set(configs ...ConfigureCommandFunc)

Set is a helper config function that allows setting multiple configuration functions on a command.

func (*Command) Visit

func (c *Command) Visit(visitor func(cmd *Command, level int) bool, level int)

Visit traverse a command and its subcommands from top to bottom

type CommandFunc

type CommandFunc func(cmdLine *Parser, command *Command) error

CommandFunc callback - optionally specified as part of the Command structure gets called when matched on Parse()

type CompletionData added in v1.8.0

type CompletionData struct {
	Commands            []string                    // Available commands
	Flags               []string                    // Global flags
	CommandFlags        map[string][]string         // Flags per command
	Descriptions        map[string]string           // Descriptions for commands/flags
	FlagValues          map[string][]CompletionData // Values for flags
	CommandDescriptions map[string]string           // Descriptions specific to commands
}

CompletionData is used to store information for command line completion

type ConfigureArgumentFunc

type ConfigureArgumentFunc func(argument *Argument, err *error)

ConfigureArgumentFunc is used when defining Flag arguments

func SetRequired

func SetRequired(required bool) ConfigureArgumentFunc

SetRequired when true, the flag must be supplied on the command-line

func SetRequiredIf added in v0.0.3

func SetRequiredIf(requiredIf RequiredIfFunc) ConfigureArgumentFunc

SetRequiredIf allows to set a function to evaluate if a flag is required

func SetSecure

func SetSecure(secure bool) ConfigureArgumentFunc

SetSecure sets the secure flag to true or false

func SetSecurePrompt

func SetSecurePrompt(prompt string) ConfigureArgumentFunc

SetSecurePrompt sets the prompt for the secure flag

func WithAcceptedValues added in v0.0.8

func WithAcceptedValues(values []types.PatternValue) ConfigureArgumentFunc

WithAcceptedValues sets the accepted values for the argument. The values can be either literal strings or regular expressions. Each value can optionally have a description that will be shown in help text.

func WithDefaultValue

func WithDefaultValue(defaultValue string) ConfigureArgumentFunc

WithDefaultValue sets the default value for the argument

func WithDependencyMap added in v1.8.3

func WithDependencyMap(dependencies map[string][]string) ConfigureArgumentFunc

WithDependencyMap specifies flag dependencies using a map of flag names to accepted values

func WithDependentFlags

func WithDependentFlags(dependencies []string) ConfigureArgumentFunc

WithDependentFlags accepts an array of string denoting flags on which an argument depends. Results in a warning being emitted in GetWarnings() when the dependent flags are not specified.

func WithDependentValueFlags deprecated

func WithDependentValueFlags(dependencies, values []string) ConfigureArgumentFunc

WithDependentValueFlags specifies flag dependencies with their accepted values

Deprecated: Use WithDependencyMap instead

func WithDescription

func WithDescription(description string) ConfigureArgumentFunc

WithDescription the description will be used in usage output presented to the user

func WithPosition added in v1.9.0

func WithPosition(idx int) ConfigureArgumentFunc

WithPosition sets a position requirement for the argument

func WithPostValidationFilter added in v0.0.7

func WithPostValidationFilter(filter FilterFunc) ConfigureArgumentFunc

WithPostValidationFilter sets the post-validation filter for the argument

func WithPreValidationFilter added in v0.0.7

func WithPreValidationFilter(filter FilterFunc) ConfigureArgumentFunc

WithPreValidationFilter sets the pre-validation filter for the argument

func WithShortFlag

func WithShortFlag(shortFlag string) ConfigureArgumentFunc

WithShortFlag represents the short form of a flag. Since by default and design, no max length is enforced, the "short" flag can be looked at as an alternative to using the long name. I use it as a moniker. The short flag can be used in all methods which take a flag argument. By default, there is no support for "POSIX/GNU-like" chaining of boolean flags such as :

-vvvv

Instead of specifying a flag 4 times, the "goopt" way would be specifying `-v 4`.

If POSIX/GNU compatibility is desired use the SetPosix or WithPosix functions on CmdLineOption (not implemented yet).

func WithType

func WithType(typeof types.OptionType) ConfigureArgumentFunc

WithType - one of three types:

  1. Single - a flag which expects a value
  2. Chained - a flag which expects a delimited value representing elements in a list (and is evaluated as a list)
  3. Standalone - a boolean flag which by default takes no value (defaults to true) but may accept a value which evaluates to true or false
  4. File - a flag which expects a valid file path whose content is the value

type ConfigureCmdLineFunc

type ConfigureCmdLineFunc func(cmdLine *Parser, err *error)

ConfigureCmdLineFunc is used when defining CommandLineOption options

func WithArgumentPrefixes

func WithArgumentPrefixes(prefixes []rune) ConfigureCmdLineFunc

WithArgumentPrefixes allows providing custom flag prefixes (defaults to '-', '---', and '/').

func WithBindFlag

func WithBindFlag[T Bindable](flag string, bindVar *T, argument *Argument, commandPath ...string) ConfigureCmdLineFunc

WithBindFlag is a wrapper to BindFlag which is used to bind a pointer to a variable with a flag. If `bindVar` is not a pointer, an error is returned The following variable types are supported:

  • *string
  • *int, *int8, *int16, *int32, *int64
  • *uint, *uint8, *uint16, *uint32, *uint64
  • *float32, *float64
  • *time.Time
  • *bool For other types use WithCustomBindFlag (wrapper around CustomBindFlag) or CustomBindFlag

func WithCommand

func WithCommand(command *Command) ConfigureCmdLineFunc

WithCommand is a wrapper for AddCommand. A Command represents a verb followed by optional sub-commands. A sub-command is a Command which is stored in a Command's []Subcommands field. A command which has no children is a terminating command which can receive values supplied by the user on the command line. Like flags, commands are evaluated on Parse. See the Command struct for more details.

func WithCommandNameConverter added in v1.8.4

func WithCommandNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc

WithCommandNameConverter allows setting a custom name converter for command names

func WithCustomBindFlag

func WithCustomBindFlag[T any](flag string, bindVar *T, proc ValueSetFunc, argument *Argument, commandPath ...string) ConfigureCmdLineFunc

WithCustomBindFlag is a wrapper for CustomBindFlag which receives parsed value via the ValueSetFunc callback On Parse the callback is called with the following arguments:

  • the bound flag name as string
  • the command-line value as string
  • the custom struct or variable which was bound. The bound structure is passed as reflect.Value

func WithEnvNameConverter added in v1.8.4

func WithEnvNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc

WithEnvNameConverter allows setting a custom name converter for environment variable names

func WithExecOnParse added in v1.5.7

func WithExecOnParse(value bool) ConfigureCmdLineFunc

WithExecOnParse specifies whether Command callbacks should be executed during Parse as they are encountered.

func WithFlag

func WithFlag(flag string, argument *Argument) ConfigureCmdLineFunc

WithFlag is a wrapper for AddFlag which is used to define a flag. A flag represents a command line option as a "long" and optional "short" form which is prefixed by '-', '--' or '/'.

func WithFlagNameConverter added in v1.8.4

func WithFlagNameConverter(converter NameConversionFunc) ConfigureCmdLineFunc

WithFlagNameConverter allows setting a custom name converter for flag names

func WithListDelimiterFunc

func WithListDelimiterFunc(delimiterFunc types.ListDelimiterFunc) ConfigureCmdLineFunc

WithListDelimiterFunc allows providing a custom function for splitting Chained command-line argument values into lists.

func WithPosix

func WithPosix(usePosix bool) ConfigureCmdLineFunc

WithPosix for switching on Posix/GNU-like flag compatibility

type ConfigureCommandFunc

type ConfigureCommandFunc func(command *Command)

ConfigureCommandFunc is used when defining Command options

func WithCallback

func WithCallback(callback CommandFunc) ConfigureCommandFunc

WithCallback sets the callback function for the command. This function is run when the command gets executed.

func WithCommandDescription

func WithCommandDescription(description string) ConfigureCommandFunc

WithCommandDescription sets the description for the command. This description helps users to understand what the command does.

func WithName

func WithName(name string) ConfigureCommandFunc

WithName sets the name for the command. The name is used to identify the command and invoke it from the command line.

func WithOverwriteSubcommands added in v1.5.2

func WithOverwriteSubcommands(subcommands ...*Command) ConfigureCommandFunc

WithOverwriteSubcommands allows replacing a Command's subcommands.

func WithSubcommands

func WithSubcommands(subcommands ...*Command) ConfigureCommandFunc

WithSubcommands function takes a list of subcommands and associates them with a command.

type FilterFunc added in v0.0.6

type FilterFunc func(string) string

FilterFunc used to "filter" (change/evaluate) flag values - see AddFilter/GetPreValidationFilter/HasPreValidationFilter

type FlagInfo added in v1.5.0

type FlagInfo struct {
	Argument    *Argument
	CommandPath string // The path of the command that owns this flag
}

FlagInfo is used to store information about a flag

type NameConversionFunc added in v1.8.4

type NameConversionFunc func(string) string

NameConversionFunc converts a field name to a command/flag name

type Parser added in v1.7.0

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

Parser opaque struct used in all Flag/Command manipulation

func NewCmdLine deprecated

func NewCmdLine(configs ...ConfigureCmdLineFunc) (*Parser, error)

NewCmdLine creates a new parser with functional configuration.

Deprecated: Use NewParserWith instead. This function will be removed in v2.0.0.

func NewCmdLineFromStruct deprecated added in v1.4.0

func NewCmdLineFromStruct[T any](structWithTags *T, config ...ConfigureCmdLineFunc) (*Parser, error)

NewCmdLineFromStruct is an alias for NewParserFromStruct.

Deprecated: Use NewParserFromStruct instead. This function will be removed in v2.0.0.

func NewCmdLineFromStructWithLevel deprecated added in v1.4.0

func NewCmdLineFromStructWithLevel[T any](structWithTags *T, maxDepth int, config ...ConfigureCmdLineFunc) (*Parser, error)

NewCmdLineFromStructWithLevel is an alias for NewParserFromStructWithLevel.

Deprecated: Use NewParserFromStructWithLevel instead. This function will be removed in v2.0.0.

func NewCmdLineOption deprecated

func NewCmdLineOption() *Parser

NewCmdLineOption creates a new parser with default initialization.

Deprecated: Use NewParser instead. This function will be removed in v2.0.0.

func NewParser added in v1.7.0

func NewParser() *Parser

NewParser convenience initialization method. Use NewCmdLine to configure CmdLineOption using option functions.

func NewParserFromInterface added in v1.9.2

func NewParserFromInterface(i interface{}, config ...ConfigureCmdLineFunc) (*Parser, error)

NewParserFromInterface creates a new parser from an interface{} that should be a struct or a pointer to a struct

func NewParserFromStruct added in v1.7.0

func NewParserFromStruct[T any](structWithTags *T, config ...ConfigureCmdLineFunc) (*Parser, error)

NewParserFromStruct creates a new Parser from a struct. By default, all fields are treated as flags unless:

  • They are tagged with `ignore`
  • They are unexported
  • They are nested structs or slices of structs

Default field behavior:

  • Type: Single
  • Name: derived from field name
  • Flag: true

Use tags to override defaults:

`goopt:"name:custom;type:chained"`

func NewParserFromStructWithLevel added in v1.7.0

func NewParserFromStructWithLevel[T any](structWithTags *T, maxDepth int, config ...ConfigureCmdLineFunc) (*Parser, error)

NewParserFromStructWithLevel parses a struct and binds its fields to command-line flags up to maxDepth levels

func NewParserWith added in v1.7.0

func NewParserWith(configs ...ConfigureCmdLineFunc) (*Parser, error)

NewParserWith allows initialization of Parser using option functions. The caller should always test for error on return because Parser will be nil when an error occurs during initialization.

Configuration example:

 parser, err := NewParserWith(
		WithFlag("flagWithValue",
			NewArg(
				WithShortFlag("fw"),
				WithType(Single),
				WithDescription("this flag requires a value"),
				WithDependentFlags([]string{"flagA", "flagB"}),
				SetRequired(true))),
		WithFlag("flagA",
			NewArg(
				WithShortFlag("fa"),
				WithType(Standalone))),
		WithFlag("flagB",
			NewArg(
				WithShortFlag("fb"),
				WithDescription("This is flag B - flagWithValue depends on it"),
				WithDefaultValue("db"),
				WithType(Single))),
		WithFlag("flagC",
			NewArg(
				WithShortFlag("fc"),
				WithDescription("this is flag C - it's a chained flag which can return a list"),
				WithType(Chained))))

func (*Parser) AcceptPattern added in v1.7.0

func (p *Parser) AcceptPattern(flag string, val types.PatternValue, commandPath ...string) error

AcceptPattern is used to define an acceptable value for a Flag. The 'pattern' argument is compiled to a regular expression and the description argument is used to provide a human-readable description of the pattern. Returns an error if the regular expression cannot be compiled or if the Flag does not support values (Standalone). Example:

	a Flag which accepts only whole numbers could be defined as:
 	AcceptPattern("times", PatternValue{Pattern: `^[\d]+`, Description: "Please supply a whole number"}).

func (*Parser) AcceptPatterns added in v1.7.0

func (p *Parser) AcceptPatterns(flag string, acceptVal []types.PatternValue, commandPath ...string) error

AcceptPatterns same as PatternValue but acts on a list of patterns and descriptions. When specified, the patterns defined in AcceptPatterns represent a set of values, of which one must be supplied on the command-line. The patterns are evaluated on Parse, if no command-line options match one of the PatternValue, Parse returns false.

func (*Parser) AddCommand added in v1.7.0

func (p *Parser) AddCommand(cmd *Command) error

AddCommand used to define a Command/sub-command chain Unlike a flag which starts with a '-' or '/' a Command represents a verb or action

func (*Parser) AddDependency added in v1.8.3

func (p *Parser) AddDependency(flag, dependsOn string, commandPath ...string) error

AddDependency adds a dependency without value constraints

func (*Parser) AddDependencyValue added in v1.8.3

func (p *Parser) AddDependencyValue(flag, dependsOn string, allowedValues []string, commandPath ...string) error

AddDependencyValue adds or updates a dependency with specific allowed values

func (*Parser) AddFlag added in v1.7.0

func (p *Parser) AddFlag(flag string, argument *Argument, commandPath ...string) error

AddFlag is used to define a Flag. A Flag represents a command line option with a "long" name and an optional "short" form prefixed by '-', '--' or '/'. This version supports both global flags and command-specific flags using the optional commandPath argument.

func (*Parser) AddFlagPostValidationFilter added in v1.7.0

func (p *Parser) AddFlagPostValidationFilter(flag string, proc FilterFunc, commandPath ...string) error

AddFlagPostValidationFilter adds a filter (user-defined transform/evaluate function) which is called on the Flag value during Parse *after* AcceptedValues are checked

func (*Parser) AddFlagPreValidationFilter added in v1.7.0

func (p *Parser) AddFlagPreValidationFilter(flag string, proc FilterFunc, commandPath ...string) error

AddFlagPreValidationFilter adds a filter (user-defined transform/evaluate function) which is called on the Flag value during Parse *before* AcceptedValues are checked

func (*Parser) BindFlag added in v1.7.0

func (p *Parser) BindFlag(bindPtr interface{}, flag string, argument *Argument, commandPath ...string) error

BindFlag is used to bind a *pointer* to string, int, uint, bool, float or time.Time scalar or slice variable with a Flag which is set when Parse is invoked. An error is returned if data cannot be bound - for compile-time safety use BindFlagToParser instead

func (*Parser) Clear added in v1.7.0

func (p *Parser) Clear(config ClearConfig)

Clear can be used to selectively clear sensitive options or when re-defining options on the fly.

func (*Parser) ClearAll added in v1.7.0

func (p *Parser) ClearAll()

ClearAll clears all parsed options and commands as well as filters and acceptedValues (guards). Configured flags and registered commands are not cleared. Use this when parsing a command line repetitively.

func (*Parser) CustomBindFlag added in v1.7.0

func (p *Parser) CustomBindFlag(data any, proc ValueSetFunc, flag string, argument *Argument, commandPath ...string) error

CustomBindFlag works like BindFlag but expects a ValueSetFunc callback which is called when a Flag is evaluated on Parse. When the Flag is seen on the command like the ValueSetFunc is called with the user-supplied value. Allows binding complex structures not supported by BindFlag

func (*Parser) DependsOnFlag added in v1.7.0

func (p *Parser) DependsOnFlag(flag, dependsOn string, commandPath ...string) error

DependsOnFlag adds a dependency without value constraints

func (*Parser) DependsOnFlagValue added in v1.7.0

func (p *Parser) DependsOnFlagValue(flag, dependsOn, ofValue string, commandPath ...string) error

DependsOnFlagValue adds a dependency with specific value constraints

func (*Parser) DescribeFlag added in v1.7.0

func (p *Parser) DescribeFlag(flag, description string, commandPath ...string) error

DescribeFlag is used to provide a description of a Flag

func (*Parser) ExecuteCommand added in v1.7.0

func (p *Parser) ExecuteCommand() error

ExecuteCommand command callbacks are placed on a FIFO queue during parsing until ExecuteCommands is called. Returns the error which occurred during execution of a command callback.

func (*Parser) ExecuteCommands added in v1.7.0

func (p *Parser) ExecuteCommands() int

ExecuteCommands command callbacks are placed on a FIFO queue during parsing until ExecuteCommands is called. Returns the count of errors encountered during execution.

func (*Parser) GenerateCompletion added in v1.8.0

func (p *Parser) GenerateCompletion(shell, programName string) string

GenerateCompletion generates completion scripts for the given shell and program name

func (*Parser) Get added in v1.7.0

func (p *Parser) Get(flag string, commandPath ...string) (string, bool)

Get returns a combination of a Flag's value as string and true if found. If a flag is not set but has a configured default value the default value is registered and is returned. Returns an empty string and false otherwise

func (*Parser) GetAcceptPatterns added in v1.7.0

func (p *Parser) GetAcceptPatterns(flag string, commandPath ...string) ([]types.PatternValue, error)

GetAcceptPatterns takes a flag string and returns an error if the flag does not exist, a slice of LiterateRegex otherwise

func (*Parser) GetArgument added in v1.7.0

func (p *Parser) GetArgument(flag string, commandPath ...string) (*Argument, error)

GetArgument returns the Argument corresponding to the long or short flag or an error when not found

func (*Parser) GetBool added in v1.7.0

func (p *Parser) GetBool(flag string, commandPath ...string) (bool, error)

GetBool attempts to convert the string value of a Flag to boolean.

func (*Parser) GetCommandExecutionError added in v1.7.0

func (p *Parser) GetCommandExecutionError(commandName string) error

GetCommandExecutionError returns the error which occurred during execution of a command callback after ExecuteCommands has been called. Returns nil on no error. Returns a CommandNotFound error when no callback is associated with commandName

func (*Parser) GetCommandExecutionErrors added in v1.8.6

func (p *Parser) GetCommandExecutionErrors() []types.KeyValue[string, error]

GetCommandExecutionErrors returns the errors which occurred during execution of command callbacks after ExecuteCommands has been called. Returns a KeyValue list of command name and error

func (*Parser) GetCommands added in v1.7.0

func (p *Parser) GetCommands() []string

GetCommands returns the list of all commands seen on command-line

func (*Parser) GetCompletionData added in v1.8.0

func (p *Parser) GetCompletionData() completion.CompletionData

GetCompletionData populates a CompletionData struct containing information for command line completion

func (*Parser) GetConsistencyWarnings deprecated added in v1.7.0

func (p *Parser) GetConsistencyWarnings() []string

GetConsistencyWarnings is a helper function which provides information about eventual option consistency warnings. It is intended for users of the library rather than for end-users

Deprecated: Use GetWarnings instead. This function will be removed in v2.0.0.

func (*Parser) GetDescription added in v1.7.0

func (p *Parser) GetDescription(flag string, commandPath ...string) string

GetDescription retrieves a Flag's description as set by DescribeFlag

func (*Parser) GetErrorCount added in v1.7.0

func (p *Parser) GetErrorCount() int

GetErrorCount is greater than zero when errors were encountered during Parse.

func (*Parser) GetErrors added in v1.7.0

func (p *Parser) GetErrors() []error

GetErrors returns a list of the errors encountered during Parse

func (*Parser) GetFloat added in v1.7.0

func (p *Parser) GetFloat(flag string, bitSize int, commandPath ...string) (float64, error)

GetFloat attempts to convert the string value of a Flag to a float64

func (*Parser) GetInt added in v1.7.0

func (p *Parser) GetInt(flag string, bitSize int, commandPath ...string) (int64, error)

GetInt attempts to convert the string value of a Flag to an int64.

func (*Parser) GetList added in v1.7.0

func (p *Parser) GetList(flag string, commandPath ...string) ([]string, error)

GetList attempts to split the string value of a Chained Flag to a string slice by default the value is split on '|', ',' or ' ' delimiters

func (*Parser) GetMaxDependencyDepth added in v1.8.8

func (p *Parser) GetMaxDependencyDepth() int

GetMaxDependencyDepth returns the current maximum allowed depth for flag dependencies. If not explicitly set, returns DefaultMaxDependencyDepth.

func (*Parser) GetOptions added in v1.7.0

func (p *Parser) GetOptions() []types.KeyValue[string, string]

GetOptions returns a slice of KeyValue pairs which have been supplied on the command-line. Note: Short flags are always resolved to their long form in the returned options. For example, if "-d" is specified on the command line and maps to "--debug", the returned option will use "debug" as the key.

func (*Parser) GetOrDefault added in v1.7.0

func (p *Parser) GetOrDefault(flag string, defaultValue string, commandPath ...string) string

GetOrDefault returns the value of a defined Flag or defaultValue if no value is set

func (*Parser) GetPositionalArgCount added in v1.7.0

func (p *Parser) GetPositionalArgCount() int

GetPositionalArgCount returns the number of positional arguments

func (*Parser) GetPositionalArgs added in v1.7.0

func (p *Parser) GetPositionalArgs() []PositionalArgument

GetPositionalArgs returns the list of positional arguments - a positional argument is a command line argument that is neither a flag, a flag value, nor a command

func (*Parser) GetPostValidationFilter added in v1.7.0

func (p *Parser) GetPostValidationFilter(flag string, commandPath ...string) (FilterFunc, error)

GetPostValidationFilter retrieve Flag transform/evaluate function which is called on Parse after checking for acceptable values

func (*Parser) GetPreValidationFilter added in v1.7.0

func (p *Parser) GetPreValidationFilter(flag string, commandPath ...string) (FilterFunc, error)

GetPreValidationFilter retrieve Flag transform/evaluate function which is called on Parse before checking for acceptable values

func (*Parser) GetShortFlag added in v1.7.0

func (p *Parser) GetShortFlag(flag string, commandPath ...string) (string, error)

GetShortFlag maps a long flag to its equivalent short flag. Short flags are concise alternatives to their verbose counterparts.

The function returns the corresponding short flag if it exists. If not, it returns an error indicating that no short flag is defined for the provided long flag.

Params: flag (string): The long flag for which the function should retrieve the corresponding short flag.

Returns: string: The short flag variant if it exists. error: An error if no short flag is defined for the provided long flag, or if any other error occurs.

func (*Parser) GetStderr added in v1.8.3

func (p *Parser) GetStderr() io.Writer

GetStderr returns the current stderr writer this is a low-level function and should not be used by most users - by default stderr is os.Stderr

func (*Parser) GetStdout added in v1.8.3

func (p *Parser) GetStdout() io.Writer

GetStdout returns the current stdout writer this is a low-level function and should not be used by most users - by default stdout is os.Stdout

func (*Parser) GetTerminalReader added in v1.8.3

func (p *Parser) GetTerminalReader() util.TerminalReader

GetTerminalReader returns the current terminal reader this is a low-level function and should not be used by most users - by default terminal reader is nil and the real terminal is used

func (*Parser) GetWarnings added in v1.7.0

func (p *Parser) GetWarnings() []string

GetWarnings returns a string slice of all warnings (non-fatal errors) - a warning is set when optional dependencies are not met - for instance, specifying the value of a Flag which relies on a missing argument

func (*Parser) HasAcceptedValues added in v1.7.0

func (p *Parser) HasAcceptedValues(flag string, commandPath ...string) bool

HasAcceptedValues returns true when a Flag defines a set of valid values it will accept

func (*Parser) HasCommand added in v1.7.0

func (p *Parser) HasCommand(path string) bool

HasCommand return true when the name has been seen on the command line.

func (*Parser) HasFlag added in v1.7.0

func (p *Parser) HasFlag(flag string, commandPath ...string) bool

HasFlag returns true when the Flag has been seen on the command line.

func (*Parser) HasPositionalArgs added in v1.7.0

func (p *Parser) HasPositionalArgs() bool

HasPositionalArgs returns true if there are positional arguments

func (*Parser) HasPostValidationFilter added in v1.7.0

func (p *Parser) HasPostValidationFilter(flag string, commandPath ...string) bool

HasPostValidationFilter returns true when an option has a transform/evaluate function which is called on Parse after checking for acceptable values

func (*Parser) HasPreValidationFilter added in v1.7.0

func (p *Parser) HasPreValidationFilter(flag string, commandPath ...string) bool

HasPreValidationFilter returns true when an option has a transform/evaluate function which is called on Parse before checking for acceptable values

func (*Parser) HasRawFlag added in v1.7.0

func (p *Parser) HasRawFlag(flag string) bool

HasRawFlag returns true when the Flag has been seen on the command line - can be used to check if a flag was specified on the command line irrespective of the command context.

func (*Parser) Parse added in v1.7.0

func (p *Parser) Parse(args []string) bool

Parse this function should be called on os.Args (or a user-defined array of arguments). Returns true when user command line arguments match the defined Flag and Command rules Parse processes user command line arguments matching the defined Flag and Command rules.

func (*Parser) ParseString added in v1.7.0

func (p *Parser) ParseString(argString string) bool

ParseString calls Parse

func (*Parser) ParseStringWithDefaults added in v1.7.0

func (p *Parser) ParseStringWithDefaults(defaults map[string]string, argString string) bool

ParseStringWithDefaults calls Parse supplementing missing arguments in argString with default values from defaults

func (*Parser) ParseWithDefaults added in v1.7.0

func (p *Parser) ParseWithDefaults(defaults map[string]string, args []string) bool

ParseWithDefaults calls Parse supplementing missing arguments in args array with default values from defaults

func (*Parser) PrintCommandSpecificFlags added in v1.7.0

func (p *Parser) PrintCommandSpecificFlags(writer io.Writer, commandPath string, level int, config *PrettyPrintConfig)

PrintCommandSpecificFlags print flags for a specific command with the appropriate indentation

func (*Parser) PrintCommands added in v1.7.0

func (p *Parser) PrintCommands(writer io.Writer)

PrintCommands writes the list of accepted Command structs to io.Writer.

func (*Parser) PrintCommandsUsing added in v1.7.0

func (p *Parser) PrintCommandsUsing(writer io.Writer, config *PrettyPrintConfig)

PrintCommandsUsing writes the list of accepted Command structs to io.Writer using PrettyPrintConfig. PrettyPrintConfig.NewCommandPrefix precedes the start of a new command PrettyPrintConfig.DefaultPrefix precedes sub-commands by default PrettyPrintConfig.TerminalPrefix precedes terminal, i.e. Command structs which don't have sub-commands PrettyPrintConfig.OuterLevelBindPrefix is used for indentation. The indentation is repeated for each Level under the command root. The Command root is at Level 0.

func (*Parser) PrintCommandsWithFlags added in v1.7.0

func (p *Parser) PrintCommandsWithFlags(writer io.Writer, config *PrettyPrintConfig)

PrintCommandsWithFlags prints commands with their respective flags

func (*Parser) PrintFlags added in v1.7.0

func (p *Parser) PrintFlags(writer io.Writer)

PrintFlags pretty prints accepted command-line switches to io.Writer

func (*Parser) PrintGlobalFlags added in v1.7.0

func (p *Parser) PrintGlobalFlags(writer io.Writer)

PrintGlobalFlags prints global (non-command-specific) flags

func (*Parser) PrintPositionalArgs added in v1.9.8

func (p *Parser) PrintPositionalArgs(writer io.Writer)

PrintPositionalArgs prints all positional arguments in order

func (*Parser) PrintUsage added in v1.7.0

func (p *Parser) PrintUsage(writer io.Writer)

PrintUsage pretty prints accepted Flags and Commands to io.Writer.

func (*Parser) PrintUsageWithGroups added in v1.7.0

func (p *Parser) PrintUsageWithGroups(writer io.Writer)

PrintUsageWithGroups pretty prints accepted Flags and show command-specific Flags grouped by Commands to io.Writer.

func (*Parser) Remove added in v1.7.0

func (p *Parser) Remove(flag string, commandPath ...string) bool

Remove used to remove a defined-flag at runtime - returns false if the Flag was not found and true on removal.

func (*Parser) RemoveDependency added in v1.8.3

func (p *Parser) RemoveDependency(flag, dependsOn string, commandPath ...string) error

RemoveDependency removes a dependency

func (*Parser) SetArgument added in v1.7.0

func (p *Parser) SetArgument(flag string, paths []string, configs ...ConfigureArgumentFunc) error

SetArgument sets an Argument configuration. Returns an error if the Argument is not found or the configuration results in an error

func (*Parser) SetArgumentPrefixes added in v1.7.0

func (p *Parser) SetArgumentPrefixes(prefixes []rune) error

SetArgumentPrefixes sets the flag argument prefixes

func (*Parser) SetCommand added in v1.7.0

func (p *Parser) SetCommand(commandPath string, configs ...ConfigureCommandFunc) error

SetCommand allows for setting of Command fields via option functions Example:

 s.Set("user create",
	WithCommandDescription("create user),
	WithCommandCallback(callbackFunc),
)

func (*Parser) SetCommandNameConverter added in v1.8.4

func (p *Parser) SetCommandNameConverter(converter NameConversionFunc) NameConversionFunc

SetCommandNameConverter allows setting a custom name converter for command names

func (*Parser) SetEnvNameConverter added in v1.8.4

func (p *Parser) SetEnvNameConverter(converter NameConversionFunc) NameConversionFunc

SetEnvNameConverter allows setting a custom name converter for environment variable names If set and the environment variable exists, it will be prepended to the args array

func (*Parser) SetExecOnParse added in v1.7.0

func (p *Parser) SetExecOnParse(value bool)

func (*Parser) SetFlag added in v1.7.0

func (p *Parser) SetFlag(flag, value string, commandPath ...string) error

SetFlag is used to re-define a Flag or define a new Flag at runtime. This can be sometimes useful for dynamic evaluation of combinations of options and values which can't be expressed statically. For instance, when the user should supply these during a program's execution but after command-line options have been parsed. If the Flag is of type File the value is stored in the file.

func (*Parser) SetFlagNameConverter added in v1.8.4

func (p *Parser) SetFlagNameConverter(converter NameConversionFunc) NameConversionFunc

SetFlagNameConverter allows setting a custom name converter for flag names

func (*Parser) SetListDelimiterFunc added in v1.7.0

func (p *Parser) SetListDelimiterFunc(delimiterFunc types.ListDelimiterFunc) error

SetListDelimiterFunc sets the value delimiter function for Chained flags

func (*Parser) SetMaxDependencyDepth added in v1.8.8

func (p *Parser) SetMaxDependencyDepth(depth int)

SetMaxDependencyDepth sets the maximum allowed depth for flag dependencies. If depth is less than 1, it will be set to DefaultMaxDependencyDepth.

func (*Parser) SetPosix added in v1.7.0

func (p *Parser) SetPosix(posixCompatible bool) bool

SetPosix sets the posixCompatible flag.

func (*Parser) SetStderr added in v1.8.3

func (p *Parser) SetStderr(w io.Writer) io.Writer

SetStderr sets the stderr writer and returns the old writer this is a low-level function and should not be used by most users - by default stderr is os.Stderr

func (*Parser) SetStdout added in v1.8.3

func (p *Parser) SetStdout(w io.Writer) io.Writer

SetStdout sets the stdout writer and returns the old writer this is a low-level function and should not be used by most users - by default stdout is os.Stdout

func (*Parser) SetTerminalReader added in v1.8.3

func (p *Parser) SetTerminalReader(t util.TerminalReader) util.TerminalReader

SetTerminalReader sets the terminal reader for secure input (by default, the terminal reader is the real terminal) this is useful for testing or mocking the terminal reader or for setting a custom terminal reader the returned value is the old terminal reader, so it can be restored later this is a low-level function and should not be used by most users - by default terminal reader is nil and the real terminal is used

type PositionalArgument

type PositionalArgument struct {
	Position int       // Position in the command line
	Value    string    // The actual value
	Argument *Argument // Reference to the argument definition, if this was bound
}

PositionalArgument describes command-line arguments which were not matched as flags, flag values, command or command values.

type PrettyPrintConfig

type PrettyPrintConfig struct {
	// NewCommandPrefix precedes the start of a new command
	NewCommandPrefix string
	// DefaultPrefix precedes sub-commands by default
	DefaultPrefix string
	// TerminalPrefix precedes terminal, i.e. Command structs which don't have sub-commands
	TerminalPrefix string
	// InnerLevelBindPrefix is used for indentation. The indentation is repeated for each Level under the
	//  command root. The Command root is at Level 0. Each sub-command increases root Level by 1.
	InnerLevelBindPrefix string
	// OuterLevelBindPrefix is used for indentation after InnerLevelBindPrefix has been rendered. The indentation is repeated for each Level under the
	//  command root. The Command root is at Level 0. Each sub-command increases root Level by 1.
	OuterLevelBindPrefix string
}

PrettyPrintConfig is used to print the list of accepted commands as a tree in PrintCommandsUsing and PrintCommands

type RequiredIfFunc added in v0.0.3

type RequiredIfFunc func(cmdLine *Parser, optionName string) (bool, string)

RequiredIfFunc used to specify if an option is required when a particular Command or Flag is specified

type ValueSetFunc

type ValueSetFunc func(flag, value string, customStruct interface{})

ValueSetFunc callback - optionally specified as part of the Argument structure to 'bind' variables to a Flag Used to set the value of a Flag to a custom structure.

Directories

Path Synopsis
cmd
completion/data.go
completion/data.go

Jump to

Keyboard shortcuts

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