parser

package
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2025 License: MIT Imports: 9 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArgumentsParser

type ArgumentsParser struct {
	// Banner is a string that is printed before running the argument parsing.
	// This is typically used to display the program name or purpose.
	Banner string

	// Options holds various configuration options for the ArgumentsParser.
	Options ArgumentsParserOptions

	// ParsingState holds the state of the parsing process.
	ParsingState ParsingState

	// PositionalArguments is a slice of pointers to positional arguments
	// that the parser will manage.
	PositionalArguments []positionals.PositionalArgument

	// Groups is a map of named subgroups to organize related arguments
	// into logical categories for better structure and readability.
	Groups map[string]*argumentgroup.ArgumentGroup

	// SubParsers holds the subparsers for handling subcommands within the main parser.
	SubParsers SubParsers
	// contains filtered or unexported fields
}

ArgumentsParser is responsible for parsing command-line arguments for a program. It handles both positional and named arguments, supports argument groups, and provides usage information. The parser maintains a mapping of argument names to their corresponding values and manages required arguments.

func NewParser added in v1.2.0

func NewParser(banner string) *ArgumentsParser

func (*ArgumentsParser) AddSubParser added in v1.2.0

func (ap *ArgumentsParser) AddSubParser(name, banner string) *ArgumentsParser

AddSubParser adds a new subparser to the ArgumentsParser.

Parameters: - name: The name of the subparser.

Returns: - A pointer to the newly created ArgumentsParser instance for the subparser.

func (*ArgumentsParser) ArgumentIsPresent

func (ap *ArgumentsParser) ArgumentIsPresent(argumentName string) bool

ArgumentIsPresent checks if a given argument is present in the parsed arguments. It supports both short (e.g., -e) and long (e.g., --example) argument names.

Parameters:

  • argumentName: The name of the argument to check. It should start with a dash ('-') for short arguments or two dashes ('--') for long arguments.

Returns: - bool: true if the argument is present; false otherwise.

The function first verifies that the argument name has a valid length and starts with a dash. It then checks if the argument is in the `longNameToArgument` map for long arguments or `shortNameToArgument` map for short arguments, returning true if found and false if not.

func (*ArgumentsParser) Get

func (ap *ArgumentsParser) Get(argumentFlag string) (interface{}, error)

Get retrieves the value of the argument specified by its short or long name.

Parameters:

  • name: The name of the argument to retrieve. This can be either the short name (single character) or the long name (string) of the argument.

Returns: - The value of the argument as an interface{} if the argument is found. - An error if the argument maps are not initialized or if the argument with the specified name is not found.

The function first checks if the argument maps (shortNameToArgument and longNameToArgument) are initialized. If they are not, it returns an error indicating that the argument maps are not initialized. It then looks up the argument by its short name in the shortNameToArgument map. If the argument is not found, it looks up the argument by its long name in the longNameToArgument map. If the argument is still not found, it returns an error indicating that the argument with the specified name is not found. If the argument is found, it returns the value of the argument.

func (*ArgumentsParser) NewArgumentGroup

func (ap *ArgumentsParser) NewArgumentGroup(name string) (*argumentgroup.ArgumentGroup, error)

NewArgumentGroup creates a new argument group with the specified name and adds it to the list of child groups.

Parameters: - name: The name of the new argument group.

Returns: A pointer to the newly created ArgumentGroup struct, which can be used to add arguments to the group.

The function initializes a new ArgumentGroup with the provided name, appends it to the SubGroups slice, and returns a pointer to the newly added ArgumentGroup. This allows for further configuration and addition of arguments to the group.

func (*ArgumentsParser) NewBoolArgument

func (ap *ArgumentsParser) NewBoolArgument(ptr *bool, shortName, longName string, defaultValue bool, help string) error

NewBoolArgument initializes a new BoolArgument and registers it with the ArgumentsParser. It sets up the argument with the provided short and long names, default value, and help message.

Parameters: - ptr: A pointer to the boolean variable where the argument's value will be stored. - shortName: The short flag (e.g., "-b") used to specify the boolean argument. It can be empty if no short flag is defined. - longName: The long flag (e.g., "--bool") used to specify the boolean argument. It can be empty if no long flag is defined. - defaultValue: The boolean value to be used if the argument is not provided by the user. - help: A description of what this argument represents, displayed in help/usage information.

Returns: - An error if the argument registration fails, otherwise nil.

func (*ArgumentsParser) NewDependentArgumentGroup

func (ap *ArgumentsParser) NewDependentArgumentGroup(name string) (*argumentgroup.ArgumentGroup, error)

NewRequiredMutuallyExclusiveArgumentGroup creates a new argument group with the specified name and adds it to the list of child groups. This group enforces that exactly one of the arguments within it must be set; if none or more than one are provided, an error will be thrown.

Parameters: - name: The name of the new argument group.

Returns: A pointer to the newly created ArgumentGroup struct, which can be used to add arguments to the group, or an error if a group with the same name already exists.

The function initializes a new ArgumentGroup with the provided name and the type ARGUMENT_GROUP_TYPE_REQUIRED_MUTUALLY_EXCLUSIVE. It adds the group to the Groups map and returns a pointer to the newly added ArgumentGroup. This allows for further configuration and addition of arguments to the group, ensuring that only one of the arguments is set during parsing.

func (*ArgumentsParser) NewIntArgument

func (ap *ArgumentsParser) NewIntArgument(ptr *int, shortName, longName string, defaultValue int, required bool, help string) error

NewIntArgument initializes a new IntArgument and registers it with the ArgumentsParser. It sets up the argument with the provided short and long names, default value, requirement status, and help message.

Parameters: - ptr: A pointer to the integer variable where the argument's value will be stored. - shortName: The short flag (e.g., "-n") used to specify the integer argument. It can be empty if no short flag is defined. - longName: The long flag (e.g., "--number") used to specify the integer argument. It can be empty if no long flag is defined. - defaultValue: The integer value to be used if the argument is not provided by the user. - required: Indicates whether the argument must be specified by the user. - help: A description of what this argument represents, displayed in help/usage information.

Returns: - An error if the argument registration fails, otherwise nil.

func (*ArgumentsParser) NewIntPositionalArgument

func (ap *ArgumentsParser) NewIntPositionalArgument(ptr *int, name string, help string) error

NewIntArgument registers a new int argument with the argument parser.

Parameters: - ptr: A pointer to the int variable where the argument value will be stored. - shortName: The short name (single character) of the argument, prefixed with a dash (e.g., "-u"). - longName: The long name of the argument, prefixed with two dashes (e.g., "--username"). - defaultValue: The default value of the argument if it is not provided by the user. - help: A description of the argument, which will be displayed in the help message.

The function creates a new StringArgument with the provided parameters and adds it to the argument group.

func (*ArgumentsParser) NewIntRangeArgument

func (ap *ArgumentsParser) NewIntRangeArgument(ptr *int, shortName, longName string, defaultValue int, rangeStart int, rangeStop int, required bool, help string) error

NewIntRangeArgument initializes a new IntRangeArgument and registers it with the ArgumentsParser. It sets up the argument with the provided short and long names, default value, range boundaries, requirement status, and help message.

Parameters: - ptr: A pointer to the integer variable where the argument's value will be stored. - shortName: The short flag (e.g., "-r") used to specify the argument. It can be empty if no short flag is defined. - longName: The long flag (e.g., "--range") used to specify the argument. It can be empty if no long flag is defined. - defaultValue: The integer to be used if the argument is not provided by the user. - rangeStart: The minimum allowable value for the integer argument. - rangeStop: The maximum allowable value for the integer argument. - required: Indicates whether the argument must be specified by the user. - help: A description of what this argument represents, displayed in help/usage information.

Returns: - An error if the argument registration fails, otherwise nil.

func (*ArgumentsParser) NewListOfIntsArgument

func (ap *ArgumentsParser) NewListOfIntsArgument(ptr *[]int, shortName, longName string, defaultValue []int, required bool, help string) error

NewListOfIntsArgument registers a new list of integers argument with the argument parser.

Parameters: - ptr: A pointer to the slice of int variables where the argument values will be stored. - shortName: The short name (single character) of the argument, prefixed with a dash (e.g., "-n"). - longName: The long name of the argument, prefixed with two dashes (e.g., "--numbers"). - defaultValue: The default list of integers if the argument is not provided by the user. - required: A boolean indicating if the argument is mandatory. - help: A description of the argument, which will be displayed in the help message.

The function creates a new ListOfIntsArgument with the provided parameters and adds it to the argument group.

func (*ArgumentsParser) NewListOfStringsArgument

func (ap *ArgumentsParser) NewListOfStringsArgument(ptr *[]string, shortName, longName string, defaultValue []string, required bool, help string) error

NewListOfStringsArgument registers a new list of strings argument with the argument parser.

Parameters: - ptr: A pointer to the slice of string variables where the argument values will be stored. - shortName: The short name (single character) of the argument, prefixed with a dash (e.g., "-s"). - longName: The long name of the argument, prefixed with two dashes (e.g., "--strings"). - defaultValue: The default list of strings if the argument is not provided by the user. - required: A boolean indicating if the argument is mandatory. - help: A description of the argument, which will be displayed in the help message.

The function creates a new ListOfStringsArgument with the provided parameters and adds it to the argument group.

func (*ArgumentsParser) NewMapOfHttpHeadersArgument

func (ap *ArgumentsParser) NewMapOfHttpHeadersArgument(ptr *map[string]string, shortName, longName string, defaultValue map[string]string, required bool, help string) error

NewMapOfHttpHeadersArgument registers a new list of HTTP headers argument with the argument parser.

Parameters: - ptr: A pointer to the slice of string variables where the argument values will be stored. - shortName: The short name (single character) of the argument, prefixed with a dash (e.g., "-H"). - longName: The long name of the argument, prefixed with two dashes (e.g., "--header"). - required: A boolean indicating if the argument is mandatory. - help: A description of the argument, which will be displayed in the help message.

The function creates a new MapOfHttpHeadersArgument with the provided parameters and adds it to the argument group. Each header should be passed in the format "Key: Value".

func (*ArgumentsParser) NewNotRequiredMutuallyExclusiveArgumentGroup

func (ap *ArgumentsParser) NewNotRequiredMutuallyExclusiveArgumentGroup(name string) (*argumentgroup.ArgumentGroup, error)

NewNotRequiredMutuallyExclusiveArgumentGroup creates a new argument group with the specified name and adds it to the list of child groups. This group allows at most one of the arguments within it to be set, but it is not mandatory to provide any.

Parameters: - name: The name of the new argument group.

Returns: A pointer to the newly created ArgumentGroup struct, which can be used to add arguments to the group, or an error if a group with the same name already exists.

The function initializes a new ArgumentGroup with the provided name and the type ARGUMENT_GROUP_TYPE_NOT_REQUIRED_MUTUALLY_EXCLUSIVE. It appends the group to the Groups map and returns a pointer to the newly added ArgumentGroup. This allows for further configuration and addition of arguments to the group.

func (*ArgumentsParser) NewRequiredMutuallyExclusiveArgumentGroup

func (ap *ArgumentsParser) NewRequiredMutuallyExclusiveArgumentGroup(name string) (*argumentgroup.ArgumentGroup, error)

NewRequiredMutuallyExclusiveArgumentGroup creates a new argument group with the specified name and adds it to the list of child groups. This group enforces that exactly one of the arguments within it must be set; if none or more than one are provided, an error will be thrown.

Parameters: - name: The name of the new argument group.

Returns: A pointer to the newly created ArgumentGroup struct, which can be used to add arguments to the group, or an error if a group with the same name already exists.

The function initializes a new ArgumentGroup with the provided name and the type ARGUMENT_GROUP_TYPE_REQUIRED_MUTUALLY_EXCLUSIVE. It adds the group to the Groups map and returns a pointer to the newly added ArgumentGroup. This allows for further configuration and addition of arguments to the group, ensuring that only one of the arguments is set during parsing.

func (*ArgumentsParser) NewStringArgument

func (ap *ArgumentsParser) NewStringArgument(ptr *string, shortName, longName string, defaultValue string, required bool, help string) error

NewStringArgument initializes a new StringArgument and registers it with the ArgumentsParser. It sets up the argument with the provided short and long names, default value, requirement status, and help message.

Parameters: - ptr: A pointer to the string variable where the argument's value will be stored. - shortName: The short flag (e.g., "-s") used to specify the string argument. It can be empty if no short flag is defined. - longName: The long flag (e.g., "--string") used to specify the string argument. It can be empty if no long flag is defined. - defaultValue: The string value to be used if the argument is not provided by the user. - required: Indicates whether the argument must be specified by the user. - help: A description of what this argument represents, displayed in help/usage information.

Returns: - An error if the argument registration fails, otherwise nil.

func (*ArgumentsParser) NewStringPositionalArgument

func (ap *ArgumentsParser) NewStringPositionalArgument(ptr *string, name string, help string) error

NewStringArgument registers a new string argument with the argument parser.

Parameters: - ptr: A pointer to the string variable where the argument value will be stored. - shortName: The short name (single character) of the argument, prefixed with a dash (e.g., "-u"). - longName: The long name of the argument, prefixed with two dashes (e.g., "--username"). - defaultValue: The default value of the argument if it is not provided by the user. - help: A description of the argument, which will be displayed in the help message.

The function creates a new StringArgument with the provided parameters and adds it to the argument group.

func (*ArgumentsParser) NewTcpPortArgument

func (ap *ArgumentsParser) NewTcpPortArgument(ptr *int, shortName, longName string, defaultValue int, required bool, help string) error

NewTcpPortArgument initializes a new TcpPortArgument and registers it with the ArgumentsParser. It sets up the argument with the provided short and long names, default value, requirement status, and help message.

Parameters: - ptr: A pointer to the integer variable where the argument's value will be stored. - shortName: The short flag (e.g., "-p") used to specify the TCP port argument. It can be empty if no short flag is defined. - longName: The long flag (e.g., "--port") used to specify the TCP port argument. It can be empty if no long flag is defined. - defaultValue: The TCP port number to be used if the argument is not provided by the user. - required: Indicates whether the argument must be specified by the user. - help: A description of what this argument represents, displayed in help/usage information.

Returns: - An error if the argument registration fails, otherwise nil.

func (*ArgumentsParser) Parse

func (ap *ArgumentsParser) Parse()

Parse parses the arguments and returns the parsed arguments.

Returns: - A map of parsed arguments.

func (*ArgumentsParser) ParseFrom

func (ap *ArgumentsParser) ParseFrom(index int, parsingState *ParsingState)

Parse processes the command-line arguments and sets the values for the defined arguments. This method handles both positional and named arguments, supports flags with values specified using "=", and checks for missing or unexpected arguments. It also provides a usage message if the "-h" or "--help" flags are present.

Behavior:

  • Populates maps for quick lookup of arguments based on their short and long names.
  • Splits input arguments on "=" to allow for flags like "--key=value".
  • Detects the presence of help flags ("-h" or "--help") and displays usage information.
  • Separates positional arguments from named arguments based on the order of inputs.
  • Validates that all required positional and named arguments are provided and parses them.
  • Displays error messages for missing or extra arguments and exits if any errors are detected.

Note:

This method terminates the program if it encounters errors or if help is requested.

Example Usage:

  • `./program positional1 positional2 --name=example`

Errors:

If required arguments are missing or extra positional arguments are found, error messages
will be displayed, and the program will exit with a non-zero status.

func (*ArgumentsParser) PrintArgumentTree

func (ap *ArgumentsParser) PrintArgumentTree()

PrintArgumentTree prints the argument tree for the ArgumentsParser.

The function prints the banner, the list of arguments, and the subgroups in a tree-like structure. Each level of indentation is represented by " │ ". The output includes the banner, the names of the arguments, and the names of the subgroups within the ArgumentsParser.

func (*ArgumentsParser) Register

func (ap *ArgumentsParser) Register(arg arguments.Argument) error

Register adds a new argument to the ArgumentsParser's default group. It ensures that the short and long names for the argument are unique and prevents duplicate registrations.

Parameters: - arg: An instance of the arguments.Argument interface representing the argument to be registered.

Returns: - An error if the argument's short or long name conflicts with an existing argument, otherwise nil.

func (*ArgumentsParser) RegisterPositional

func (ap *ArgumentsParser) RegisterPositional(newPositionalArgument positionals.PositionalArgument) error

Register registers a new argument with the argument group if it does not already exist.

Parameters: - arg: The argument to be registered.

The function checks if the argument's short name and long name are already present in the ShortNameToArgument and LongNameToArgument maps. If not, it adds the argument to these maps and appends it to the Arguments slice.

func (*ArgumentsParser) SetOptShowBannerOnHelp added in v1.2.0

func (ap *ArgumentsParser) SetOptShowBannerOnHelp(showBannerOnHelp bool)

SetOptShowBannerOnHelp sets the option to show the banner on help.

Parameters: - showBannerOnHelp: A boolean indicating whether to show the banner on help.

func (*ArgumentsParser) SetOptShowBannerOnRun added in v1.2.0

func (ap *ArgumentsParser) SetOptShowBannerOnRun(showBannerOnRun bool)

SetOptShowBannerOnRun sets the option to show the banner on run.

Parameters: - showBannerOnRun: A boolean indicating whether to show the banner on run.

func (*ArgumentsParser) SetupSubParsing added in v1.2.0

func (ap *ArgumentsParser) SetupSubParsing(name string, value *string, caseInsensitive bool)

SetupSubParsing initializes a new subparser with the specified name, value, and case sensitivity.

Parameters: - name: The name of the subparser. - value: A pointer to a string where the subparser name will be stored. - caseInsensitive: A boolean indicating if the subparser name matching should be case insensitive.

Returns: - A pointer to the newly created ArgumentsParser instance for the subparser.

func (*ArgumentsParser) Usage

func (ap *ArgumentsParser) Usage()

Usage prints the usage information for the command-line arguments.

func (*ArgumentsParser) UsageFrom

func (ap *ArgumentsParser) UsageFrom(index int, parsingState *ParsingState)

Usage prints the usage information for the command-line arguments.

The function first prints the banner, followed by the usage string, which includes the name of the executable. It then iterates through all the arguments in the DefaultGroup and prints their short name, long name, and help description. The arguments are formatted using the padding format calculated by the computePaddingFormat function.

After printing the arguments in the DefaultGroup, the function iterates over the named subgroups in the Groups map. For each subgroup, it prints the group name and the arguments within that group, including their short name, long name, and help description. The subgroup arguments are also formatted using the padding format calculated by the computePaddingFormat function.

The function ensures that the usage information is displayed in a clear and organized manner, making it easy for users to understand the available command-line arguments and their descriptions.

type ArgumentsParserOptions added in v1.2.0

type ArgumentsParserOptions struct {
	ShowBannerOnHelp bool

	ShowBannerOnRun bool
}

type ParsedArguments added in v1.2.1

type ParsedArguments struct {
	PositionalArguments map[string]*positionals.PositionalArgument
	LongNameToArgument  map[string]*arguments.Argument
	ShortNameToArgument map[string]*arguments.Argument
}

func (*ParsedArguments) AddArgument added in v1.2.1

func (pa *ParsedArguments) AddArgument(argument *arguments.Argument)

AddArgument adds an argument to the parsing state.

Parameters: - argument: The argument to add.

func (*ParsedArguments) AddPositionalArgument added in v1.2.1

func (pa *ParsedArguments) AddPositionalArgument(argument *positionals.PositionalArgument)

AddPositionalArgument adds a positional argument to the parsing state.

Parameters: - argument: The positional argument to add.

type ParsingState added in v1.2.0

type ParsingState struct {
	RawArguments    []string
	ErrorMessages   []string
	ParsedArguments ParsedArguments
}

func (*ParsingState) AddErrorMessage added in v1.2.1

func (ps *ParsingState) AddErrorMessage(message string)

AddErrorMessage adds an error message to the parsing state.

Parameters: - message: The error message to add.

func (*ParsingState) ClearErrorMessages added in v1.2.1

func (ps *ParsingState) ClearErrorMessages()

ClearErrorMessages clears the error messages from the parsing state.

This method resets the error messages slice to an empty state, effectively clearing any previously added error messages.

func (*ParsingState) GetErrorMessages added in v1.2.1

func (ps *ParsingState) GetErrorMessages() []string

GetErrorMessages returns the error messages from the parsing state.

Returns: - A slice of error messages.

func (*ParsingState) SetRawArguments added in v1.2.1

func (ps *ParsingState) SetRawArguments(rawArguments []string)

SetRawArguments sets the raw arguments in the parsing state.

Parameters: - rawArguments: The raw arguments to set.

type SubParsers added in v1.2.0

type SubParsers struct {
	// Name is the name of the subparser.
	Name string
	// Value is the value of the subparser.
	Value *string
	// Enabled is a boolean that indicates whether the subparser is enabled.
	Enabled bool
	// CaseInsensitive is a boolean that indicates whether the subparser is case-insensitive.
	CaseInsensitive bool
	// Parsers is a map of subparsers.
	Parsers map[string]*ArgumentsParser
}

func (*SubParsers) AddSubParser added in v1.2.0

func (sp *SubParsers) AddSubParser(name, banner string) *ArgumentsParser

AddSubParser adds a new subparser to the SubParsers. It creates a new ArgumentsParser with the specified name and banner. If the subparser is case-insensitive, it adds the subparser to the SubParsers with the specified name in lowercase. Otherwise, it adds the subparser to the SubParsers with the specified name.

func (*SubParsers) GetSubParser added in v1.2.0

func (sp *SubParsers) GetSubParser(name string) *ArgumentsParser

GetSubParser returns the subparser with the specified name. If the subparser is case-insensitive, it returns the subparser with the specified name in lowercase. Otherwise, it returns the subparser with the specified name.

Jump to

Keyboard shortcuts

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