argparse

package module
v0.0.0-...-26aeb1e Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: MIT Imports: 10 Imported by: 7

README

argparse

Argument parsing library that tries to provide a similar API and functionality as Python's argparse package.

Documentation

Index

Constants

View Source
const (
	// OneOrMore means that one or more argument values are accepted by
	// the argument.
	OneOrMore int = -1 - iota

	// ZeroOrMore indicates that zero or more arguments are accepted.
	ZeroOrMore

	// ZeroOrOne indicates that zero or one argument is allowed
	ZeroOrOne
)
View Source
const (
	// Debug indicates whether or not argparse was compiled with debugging
	// enabled.  There are extremely few places where assertions are needed
	// but this is how we handle it.
	Debug = true
)

Variables

This section is empty.

Functions

func Bool

func Bool(v string) (interface{}, error)

Bool converts the given string into a boolean value. It implements the ValueParser interface.

func Float32

func Float32(v string) (interface{}, error)

Float32 converts the given string into a float32 value. It implements the ValueParser interface.

func Float64

func Float64(v string) (interface{}, error)

Float64 converts the given string into a float64 value. It implements the ValueParser interface.

func Int

func Int(v string) (interface{}, error)

Int converts the given string into a int value. It implements the ValueParser interface.

func Int16

func Int16(v string) (interface{}, error)

Int16 converts the given string into a int16 value. It implements the ValueParser interface.

func Int32

func Int32(v string) (interface{}, error)

Int32 converts the given string into a int32 value. It implements the ValueParser interface.

func Int64

func Int64(v string) (interface{}, error)

Int64 converts the given string into a int value. It implements the ValueParser interface.

func Int8

func Int8(v string) (interface{}, error)

Int8 converts the given string into a int8 value. It implements the ValueParser interface.

func Required

func Required(a *Argument) error

Required flags the Argument as required.

func String

func String(v string) (interface{}, error)

String is a "dummy" ValueParser filled in automatically by AddArgument if no other ValueParser is used.

func Uint

func Uint(v string) (interface{}, error)

Uint converts the given string into a uint value. It implements the ValueParser interface.

func Uint16

func Uint16(v string) (interface{}, error)

Uint16 converts the given string into a uint16 value. It implements the ValueParser interface.

func Uint32

func Uint32(v string) (interface{}, error)

Uint32 converts the given string into a uint32 value. It implements the ValueParser interface.

func Uint64

func Uint64(v string) (interface{}, error)

Uint64 converts the given string into a uint64 value. It implements the ValueParser interface.

func Uint8

func Uint8(v string) (interface{}, error)

Uint8 converts the given string into a uint8 value. It implements the ValueParser interface.

Types

type Argument

type Argument struct {

	// Action holds the action to perform after successful parsing of
	// values associated with the given argument.
	Action ArgumentAction

	// Const holds the value associated with this argument when the
	// argument is present.
	Const interface{}

	// Default is the value associated with the argument when a specific
	// value is not otherwise provided.
	Default interface{}

	// Dest is the string key that the argument can be retrieved by.
	Dest string

	// Help is the help text associated with the argument.
	Help string

	// MetaVar is the variable that the argument is represented with when
	// displaying its usage.  It is a slice in case Nargs is non-zero.
	MetaVar []string

	// Nargs is the number of values that this argument can accept.  It
	// should be a positive int unless it is one of the sentinel values:
	// ZeroOrOne, ZeroOrMore, or OneOrMore.
	Nargs int

	// OptionStrings are the possible string values that the argument can
	// be matched against.
	OptionStrings []string

	// Required determines if the argument is required or not.
	Required bool

	// Type holds a function that can be used to parse a string value into
	// the type desired by this argument.
	Type ValueParser

	// Choices holds an optional collection of allowed choices for this
	// Argument.  Choices is nil if no set of allowed values was provided.
	Choices *ArgumentChoices
	// contains filtered or unexported fields
}

Argument holds the definition of an argument.

func (*Argument) Bind

func (a *Argument) Bind(target interface{}) error

Bind the argument's parsed value into the given pointer.

func (*Argument) MustBind

func (a *Argument) MustBind(target interface{})

MustBind panics if Binding an argument fails.

func (*Argument) Optional

func (a *Argument) Optional() bool

Optional returns whether or not this is an optional (flag) argument. If it is not, then it is a positional argument.

type ArgumentAction

type ArgumentAction interface {
	Name() string
	UpdateNamespace(a *Argument, ns Namespace, vs []interface{}) error
}

ArgumentAction is called when an argument's values are parsed from the command line.

var (

	// Append is an ArgumentAction that appends an encountered argument to
	Append ArgumentAction = newArgumentActionStruct(
		"append",
		func(a *Argument, ns Namespace, args []interface{}) error {
			vs, err := a.defaultCreateValues(args)
			if err != nil {
				return err
			}
			ns.Append(a, getArgValueForNS(a, vs))
			return nil
		},
	)

	// Store is an ArgumentAction that sets the value associated with the
	// given argument.  If that argument already has a value in the given
	// namespace, an error is returned.
	Store ArgumentAction = newArgumentActionStruct(
		"store",
		func(a *Argument, ns Namespace, args []interface{}) error {
			if v, ok := ns.Get(a); ok {
				return errors.Errorf(
					"argument %q already defined with value %v.",
					a.Dest, v)
			}
			vs, err := a.defaultCreateValues(args)
			if err != nil {
				return err
			}
			ns.Set(a, getArgValueForNS(a, vs))
			return nil
		},
	)

	// StoreTrue is an ArgumentAction that stores the true value in the
	// given namespace for the given argument.
	StoreTrue ArgumentAction = newArgumentActionStruct(
		"store_true",
		func(a *Argument, ns Namespace, args []interface{}) error {
			if len(args) != 1 {
				return errors.Errorf(
					"one value expected for argument %q but got %d: %#v",
					a.Dest, len(args), args)
			}
			ns.Set(a, args[0])
			return nil
		},
	)

	// StoreFalse is an ArgumentAction that stores the false value in the given
	// namespace for the given argument.
	StoreFalse ArgumentAction = newArgumentActionStruct(
		"store_false",
		func(a *Argument, ns Namespace, args []interface{}) error {
			if len(args) != 1 {
				return errors.Errorf(
					"one value expected for argument %q but got %d: %#v",
					a.Dest, len(args), args)
			}
			ns.Set(a, args[0])
			return nil
		},
	)
)

type ArgumentChoices

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

ArgumentChoices keeps track of a collection of argument choices.

func NewChoiceValues

func NewChoiceValues(values ...interface{}) *ArgumentChoices

NewChoiceValues creates a Choices collection from the given values. The string representation of each value becomes that value's key in the collection.

func NewChoices

func NewChoices(choices ...Choice) *ArgumentChoices

NewChoices creates a Choices collection from the given slice.

func (*ArgumentChoices) At

func (cs *ArgumentChoices) At(index int) *Choice

At returns a pointer to the Choice at the given index. Do not mutate this Choice's key.

func (*ArgumentChoices) Len

func (cs *ArgumentChoices) Len() int

Len gets the number of choices within the collection.

func (*ArgumentChoices) Load

func (cs *ArgumentChoices) Load(key string) (value interface{}, ok bool)

Load a value from the collection by its key.

type ArgumentOption

type ArgumentOption func(a *Argument) error

ArgumentOption configures an Argument.

func Action

func Action(v string) ArgumentOption

Action takes the name of an action instead of the action function. it works similarly to Python's argparse.ArgumentParser.add_argument's action parameter when set to a string value.

func ActionFunc

func ActionFunc(f ArgumentAction) ArgumentOption

ActionFunc lets you specify an action function value instead of just a string key of an action function.

func ChoiceValues

func ChoiceValues(values ...interface{}) ArgumentOption

ChoiceValues sets the argument's choices.

func Choices

func Choices(choices ...Choice) ArgumentOption

Choices sets the argument's choices.

func Const

func Const(v interface{}) ArgumentOption

Const sets the Const value for the given string

func Default

func Default(v interface{}) ArgumentOption

Default sets the default value of an argument.

func Dest

func Dest(v string) ArgumentOption

Dest sets the destination name in the parsed argument namespace.

func Help

func Help(format string, args ...interface{}) ArgumentOption

Help sets the help string of an argument.

func MetaVar

func MetaVar(v ...string) ArgumentOption

MetaVar sets the help string of an argument.

func Nargs

func Nargs(v int) ArgumentOption

Nargs sets the number of values the argument can accept.

func OptionStrings

func OptionStrings(ops ...string) ArgumentOption

OptionStrings sets the arg strings.

func Type

Type sets the Type (actually a ValueParser function) of the argument.

type ArgumentParser

type ArgumentParser struct {
	// Optionals is a mapping from any of the option strings to the
	// arguments defined through AddArgument.
	Optionals map[string]*Argument

	// Positionals holds the arguments deduced by their positions in the
	// command line.  They must follow all Optional arguments.
	Positionals []*Argument

	// Prog is the name of the program
	Prog string

	// Usage describes the program's usage.  Is usually generated from the
	// arguments added to the parser.
	Usage string

	// Description is the brief description under the usage showing what
	// the command is for.
	Description string

	// Epilog is trailing text added after the argument help.
	Epilog string

	// Subparsers holds a slice of sub-parsers when your top-level parser
	// has different sub-commands.
	Subparsers []*ArgumentParser

	// NoHelp is false when the ArgumentParser should add the -h/--help
	// arguments to generate help output.  It is analogous to the add_help
	// attribute on the ArgumentParser class in Python.
	NoHelp bool
	// contains filtered or unexported fields
}

ArgumentParser collects allowed program arguments and parses them into a collection.

func MustNewArgumentParser

func MustNewArgumentParser(options ...ArgumentParserOption) *ArgumentParser

MustNewArgumentParser creates an argument parser and panics if creation fails.

func NewArgumentParser

func NewArgumentParser(options ...ArgumentParserOption) (*ArgumentParser, error)

NewArgumentParser constructs a new argument parser.

func (*ArgumentParser) AddArgument

func (p *ArgumentParser) AddArgument(options ...ArgumentOption) (*Argument, error)

AddArgument adds an argument to the argument parser.

func (*ArgumentParser) FormatHelp

func (p *ArgumentParser) FormatHelp() (string, error)

FormatHelp builds the help output into a string and returns it.

func (*ArgumentParser) MustAddArgument

func (p *ArgumentParser) MustAddArgument(options ...ArgumentOption) *Argument

MustAddArgument adds an argument or panics if argument creation fails.

func (*ArgumentParser) MustParseArgs

func (p *ArgumentParser) MustParseArgs(args ...string) Namespace

MustParseArgs must parse its arguments or it will panic.

func (*ArgumentParser) ParseArgs

func (p *ArgumentParser) ParseArgs(args ...string) (Namespace, error)

ParseArgs parses the given args (or os.Args[1:], if none specified) to create a namespace from those args. If any arguments were bound from an Argument, those targets are assigned to.

type ArgumentParserOption

type ArgumentParserOption func(p *ArgumentParser) error

ArgumentParserOption is a function that applies changes to the ArgumentParser during construction.

func Description

func Description(v string) ArgumentParserOption

Description sets the argument parser's description string.

func Epilog

func Epilog(v string) ArgumentParserOption

Epilog sets the argument parser's description string.

func Prog

Prog sets the Program name of the ArgumentParser during its construction.

func Usage

Usage sets the argument parser's usage string.

type Choice

type Choice struct {
	Key   string
	Value interface{}
	Help  string
}

Choice keeps track of choices by tracking the string representation of the choice and the actual value.

type Namespace

type Namespace map[string]interface{}

Namespace maps argument destination names with their values. Values are of the type the Argument's Type function converts them to (string, by default). If an argument's Nargs are >1, then the value is a slice of interface{} with the elements being the type set by the argument's Type function.

func (Namespace) Append

func (ns Namespace) Append(a *Argument, vs ...interface{})

Append a set of values to the namespace.

func (Namespace) Get

func (ns Namespace) Get(a *Argument) (v interface{}, ok bool)

Get the value from the Namespace associated with the given argument's Dest.

func (Namespace) GetStrings

func (ns Namespace) GetStrings(a *Argument) ([]string, error)

GetStrings is a helper function to get an argument's associated values as a slice of strings.

func (Namespace) MustGet

func (ns Namespace) MustGet(a *Argument) interface{}

MustGet retrieves an argument from the given namespace. It panics if the argument wasn't found in the namespace.

func (Namespace) MustGetStrings

func (ns Namespace) MustGetStrings(a *Argument) []string

MustGetStrings gets the arguments associated with a as a slice of strings. This function panics if a's values are not a slice of strings.

func (Namespace) Set

func (ns Namespace) Set(a *Argument, v interface{})

Set a value in the namespace for the given Arg.

type ValueParser

type ValueParser func(v string) (interface{}, error)

ValueParser can parse a string value into a Go value.

Jump to

Keyboard shortcuts

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