structarg

package module
v0.0.0-...-2789fc6 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2023 License: Apache-2.0 Imports: 17 Imported by: 27

README

structarg

Argument parser for go that defines and parses command line arguements into a struct type variable. The attributes of arguments are defined in the comment tags of the struct. after parsing command-line argument or configuration files, the values are stored in this struct.

please refer to examples/example.go for example usages.

An example of a struct definition is shown as follows:

type Options struct {
    Help bool       `help:"Show help messages" short-token:"h"`
    Debug bool      `help:"Show extra debug information"`
    Timeout int     `default:"600" help:"Number of seconds to wait for a response"`
    SUBCOMMAND string `help:"subcommand" subcommand:"true"`
}

Argument name

Each member variable of the struct represents an argument. The variable name is the argument name.

Positional and optional arguments

If the variable name is all uppercased, the argument is a positional argument, otherwise, it is an optional argument. Additionally, boolean tag "optional" explicitly defines whether the argument is optional or positional.

Tags

The attributes of an argument are defined in the comment tags of the member variable of the struct. The following tags are supported:

	/*
	   help text of the argument
	   the argument is optional.
	*/
	TAG_HELP = "help"
	/*
	   command-line token for the optional argument, e.g. token:"url"
	   the command-line argument will be "--url http://127.0.0.1:3306"
	   the tag is optional.
	   if the tag is missing, the variable name will be used as token.
	   If the variable name is CamelCase, the token will be transformed
	   into kebab-case, e.g. if the variable is "AuthURL", the token will
	   be "--auth-url"
	*/
	TAG_TOKEN = "token"
	/*
	   short form of command-line token, e.g. short-token:"u"
	   the command-line argument will be "-u http://127.0.0.1:3306"
	   the tag is optional
	*/
	TAG_SHORT_TOKEN = "short-token"
	/*
	   Metavar of the argument
	   the tag is optional
	*/
	TAG_METAVAR = "metavar"
	/*
	   The default value of the argument.
	   the tag is optional
	*/
	TAG_DEFAULT = "default"
	/*
	   The possible values of an arguments. All choices are are concatenatd by "|".
	   e.g. `choices:"1|2|3"`
	   the tag is optional
	*/
	TAG_CHOICES = "choices"
	/*
	   A boolean value explicitly declare whether the argument is optional,
	   the tag is optional
	*/
	TAG_OPTIONAL = "optional"
	/*
	   A boolean value explicitly decalre whther the argument is an subcommand
	   A subcommand argument must be the last positional argument.
	   the tag is optional, the default value is false
	*/
	TAG_SUBCOMMAND = "subcommand"
	/*
	   The attribute defines the possible number of argument. Possible values
	   are:
	       * positive integers, e.g. "1", "2"
	       * "*" any number of arguments
	       * "+" at lease one argument
	       * "?" at most one argument
	   the tag is optional, the default value is "1"
	*/
	TAG_NARGS = "nargs"
	/*
		Alias name of argument
	*/
	TAG_ALIAS = "alias"

Example usage

use ParseArgs which set default value automatically


parser, e := structarg.NewArgumentParser(&Options{},
                                        "programname",
                                        `description text`,
                                        `epilog of the program`)

e = parser.ParseArgs(os.Args[1:], false)
if e != nil {
    panic(e)
}

options := parser.Options().(*Options)

// then access argument values via options
// ...

use ParseArgs2 which set default value according to parameter

call SetDefault() to set options default value


parser, e := structarg.NewArgumentParser(&Options{},
                                        "programname",
                                        `description text`,
                                        `epilog of the program`)

// do not set default value after parse
e = parser.ParseArgs2(os.Args[1:], false, false)
if e != nil {
    panic(e)
}

options := parser.Options().(*Options)

if len(options.Config) > 0 {
    e = parser.ParseFile(options.Config)
    if e != nil {
        panic(e)
    }
}

parser.SetDefault() // set option default here

// then access argument values via options
// ...

Documentation

Index

Constants

View Source
const (
	/*
	   help text of the argument
	   the argument is optional.
	*/
	TAG_HELP = "help"
	/*
	   command-line token for the optional argument, e.g. token:"url"
	   the command-line argument will be "--url http://127.0.0.1:3306"
	   the tag is optional.
	   if the tag is missing, the variable name will be used as token.
	   If the variable name is CamelCase, the token will be transformed
	   into kebab-case, e.g. if the variable is "AuthURL", the token will
	   be "--auth-url"
	*/
	TAG_TOKEN = "token"
	/*
	   short form of command-line token, e.g. short-token:"u"
	   the command-line argument will be "-u http://127.0.0.1:3306"
	   the tag is optional
	*/
	TAG_SHORT_TOKEN = "short-token"
	/*
	   Metavar of the argument
	   the tag is optional
	*/
	TAG_METAVAR = "metavar"
	/*
	   The default value of the argument.
	   the tag is optional
	*/
	TAG_DEFAULT = "default"
	/*
	   The possible values of an arguments. All choices are are concatenatd by "|".
	   e.g. `choices:"1|2|3"`
	   the tag is optional
	*/
	TAG_CHOICES = "choices"
	/*
	   A boolean value explicitly declare whether the argument is optional,
	   the tag is optional
	*/
	TAG_POSITIONAL = "positional"
	/*
	   A boolean value explicitly declare whether the argument is required.
	   The tag is optional.  This is for optional arguments.  Positional
	   arguments must be "required"
	*/
	TAG_REQUIRED = "required"
	/*
	   A boolean value explicitly decalre whther the argument is an subcommand
	   A subcommand argument must be the last positional argument.
	   the tag is optional, the default value is false
	*/
	TAG_SUBCOMMAND = "subcommand"
	/*
	   The attribute defines the possible number of argument. Possible values
	   are:
	       * positive integers, e.g. "1", "2"
	       * "*" any number of arguments
	       * "+" at lease one argument
	       * "?" at most one argument
	   the tag is optional, the default value is "1"
	*/
	TAG_NARGS = "nargs"
	/*
		Alias name of argument
	*/
	TAG_ALIAS = "alias"
	/*
		Token for negative value, applicable to boolean values
	*/
	TAG_NEGATIVE_TOKEN = "negative"
	/*
	   Token for ignore
	*/
	TAG_IGNORE = "ignore"
)

Variables

This section is empty.

Functions

func ChoicesString

func ChoicesString(choices []string) string

func FindSimilar

func FindSimilar(niddle string, stack []string, maxDist int, minRate float64) []string

*

*
* minRate: minimal similarity ratio, between 0.0~1.0, 0.0: totally different, 1.0: exactly identitical

Types

type Argument

type Argument interface {
	NeedData() bool
	Token() string
	AliasToken() string
	ShortToken() string
	NegativeToken() string
	MetaVar() string
	IsPositional() bool
	IsRequired() bool
	IsMulti() bool
	IsSubcommand() bool
	HelpString(indent string) string
	String() string
	SetValue(val string) error
	Reset()
	DoAction(nega bool) error
	Validate() error
	SetDefault()
	IsSet() bool
}

type ArgumentParser

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

func NewArgumentParser

func NewArgumentParser(target interface{}, prog, desc, epilog string) (*ArgumentParser, error)

func NewArgumentParserWithHelp

func NewArgumentParserWithHelp(target interface{}, prog, desc, epilog string) (*ArgumentParser, error)

func (*ArgumentParser) AddArgument

func (this *ArgumentParser) AddArgument(arg Argument) error

func (*ArgumentParser) GetOptArgs

func (this *ArgumentParser) GetOptArgs() []Argument

func (*ArgumentParser) GetPosArgs

func (this *ArgumentParser) GetPosArgs() []Argument

func (*ArgumentParser) GetSubcommand

func (this *ArgumentParser) GetSubcommand() *SubcommandArgument

func (*ArgumentParser) HelpString

func (this *ArgumentParser) HelpString() string

func (*ArgumentParser) IsHelpSet

func (this *ArgumentParser) IsHelpSet() bool

func (*ArgumentParser) Options

func (this *ArgumentParser) Options() interface{}

func (*ArgumentParser) ParseArgs

func (this *ArgumentParser) ParseArgs(args []string, ignore_unknown bool) error

func (*ArgumentParser) ParseArgs2

func (this *ArgumentParser) ParseArgs2(args []string, ignore_unknown bool, setDefaults bool) error

func (*ArgumentParser) ParseFile

func (this *ArgumentParser) ParseFile(filepath string) error

func (*ArgumentParser) ParseKnownArgs

func (this *ArgumentParser) ParseKnownArgs(args []string) error

func (*ArgumentParser) ParseTornadoFile

func (this *ArgumentParser) ParseTornadoFile(filepath string) error

func (*ArgumentParser) ParseYAMLFile

func (this *ArgumentParser) ParseYAMLFile(filepath string) error

func (*ArgumentParser) SetDefault

func (this *ArgumentParser) SetDefault()

func (*ArgumentParser) ShortDescription

func (this *ArgumentParser) ShortDescription() string

func (*ArgumentParser) Usage

func (this *ArgumentParser) Usage() string

func (*ArgumentParser) Validate

func (this *ArgumentParser) Validate() error

type BaseOptions

type BaseOptions struct {
	PidFile string `help:"Pid file path"`
	Config  string `help:"Configuration file"`
	Help    bool   `help:"Show help and exit"`
	Version bool   `help:"Show version and exit"`
}

type LevenshteinStrings

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

func (LevenshteinStrings) Len

func (strs LevenshteinStrings) Len() int

func (LevenshteinStrings) Less

func (strs LevenshteinStrings) Less(i, j int) bool

func (LevenshteinStrings) Swap

func (strs LevenshteinStrings) Swap(i, j int)

type MultiArgument

type MultiArgument struct {
	SingleArgument
	// contains filtered or unexported fields
}

func (*MultiArgument) IsMulti

func (this *MultiArgument) IsMulti() bool

func (*MultiArgument) SetValue

func (this *MultiArgument) SetValue(val string) error

func (*MultiArgument) Validate

func (this *MultiArgument) Validate() error

type NotEnoughArgumentsError

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

func (*NotEnoughArgumentsError) Error

func (e *NotEnoughArgumentsError) Error() string

type SingleArgument

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

func (*SingleArgument) AliasToken

func (this *SingleArgument) AliasToken() string

func (*SingleArgument) AllToken

func (this *SingleArgument) AllToken() string

func (*SingleArgument) Choices

func (this *SingleArgument) Choices() []string

func (*SingleArgument) DoAction

func (this *SingleArgument) DoAction(nega bool) error

func (*SingleArgument) HelpString

func (this *SingleArgument) HelpString(indent string) string

func (*SingleArgument) InChoices

func (this *SingleArgument) InChoices(val string) bool

func (*SingleArgument) IsMulti

func (this *SingleArgument) IsMulti() bool

func (*SingleArgument) IsPositional

func (this *SingleArgument) IsPositional() bool

func (*SingleArgument) IsRequired

func (this *SingleArgument) IsRequired() bool

func (*SingleArgument) IsSet

func (this *SingleArgument) IsSet() bool

func (*SingleArgument) IsSubcommand

func (this *SingleArgument) IsSubcommand() bool

func (*SingleArgument) MetaVar

func (this *SingleArgument) MetaVar() string

func (*SingleArgument) NeedData

func (this *SingleArgument) NeedData() bool

func (*SingleArgument) NegativeToken

func (this *SingleArgument) NegativeToken() string

func (*SingleArgument) Reset

func (this *SingleArgument) Reset()

func (*SingleArgument) SetDefault

func (this *SingleArgument) SetDefault()

func (*SingleArgument) SetValue

func (this *SingleArgument) SetValue(val string) error

func (*SingleArgument) ShortToken

func (this *SingleArgument) ShortToken() string

func (*SingleArgument) String

func (this *SingleArgument) String() string

func (*SingleArgument) Token

func (this *SingleArgument) Token() string

func (*SingleArgument) Validate

func (this *SingleArgument) Validate() error

type SubcommandArgument

type SubcommandArgument struct {
	SingleArgument
	// contains filtered or unexported fields
}

func (*SubcommandArgument) AddSubParser

func (this *SubcommandArgument) AddSubParser(target interface{}, command string, desc string, callback interface{}) (*ArgumentParser, error)

func (*SubcommandArgument) AddSubParserWithHelp

func (this *SubcommandArgument) AddSubParserWithHelp(target interface{}, command string, desc string, callback interface{}) (*ArgumentParser, error)

func (*SubcommandArgument) GetSubParser

func (this *SubcommandArgument) GetSubParser() *ArgumentParser

func (*SubcommandArgument) HelpString

func (this *SubcommandArgument) HelpString(indent string) string

func (*SubcommandArgument) Invoke

func (this *SubcommandArgument) Invoke(args ...interface{}) error

func (*SubcommandArgument) IsSubcommand

func (this *SubcommandArgument) IsSubcommand() bool

func (*SubcommandArgument) String

func (this *SubcommandArgument) String() string

func (*SubcommandArgument) SubHelpString

func (this *SubcommandArgument) SubHelpString(cmd string) (string, error)

type SubcommandArgumentData

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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