getopt

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2020 License: BSD-3-Clause Imports: 10 Imported by: 321

README

getopt build status

Package getopt provides traditional getopt processing for implementing commands that use traditional command lines. The standard Go flag package cannot be used to write a program that parses flags the way ls or ssh does, for example. There are two versions, v1 and v2, both named getopt, that use the following import paths:

	"github.com/pborman/getopt"     // version 1
	"github.com/pborman/getopt/v2"  // version 2

This README describes version 2 of the package, which has a simplified API.

Usage

Getopt supports functionality found in both the standard BSD getopt as well as (one of the many versions of) the GNU getopt_long. Being a Go package, this package makes common usage easy, but still enables more controlled usage if needed.

Typical usage:

	Declare flags and have getopt return pointers to the values.
	helpFlag := getopt.Bool('?', "display help")
	cmdFlag := getopt.StringLong("command", 'c', "default", "the command")

	Declare flags against existing variables.
	var (
		fileName = "/the/default/path"
		timeout = time.Second * 5
		verbose bool
	)
	func init() {
		getopt.Flag(&verbose, 'v', "be verbose")
		getopt.FlagLong(&fileName, "path", 0, "the path")
		getopt.FlagLong(&timeout, "timeout", 't', "some timeout")
	}

	func main() {
		Parse the program arguments
		getopt.Parse()
		Get the remaining positional parameters
		args := getopt.Args()
		...

If you don't want the program to exit on error, use getopt.Getopt:

		err := getopt.Getopt(nil)
		if err != nil {
			code to handle error
			fmt.Fprintln(os.Stderr, err)
		}

Flag Syntax

Support is provided for both short (-f) and long (--flag) options. A single option may have both a short and a long name. Each option may be a flag or a value. A value takes an argument.

Declaring no long names causes this package to process arguments like the traditional BSD getopt.

Short flags may be combined into a single parameter. For example, "-a -b -c" may also be expressed "-abc". Long flags must stand on their own "--alpha --beta"

Values require an argument. For short options the argument may either be immediately following the short name or as the next argument. Only one short value may be combined with short flags in a single argument; the short value must be after all short flags. For example, if f is a flag and v is a value, then:

	-vvalue    (sets v to "value")
	-v value   (sets v to "value")
	-fvvalue   (sets f, and sets v to "value")
	-fv value  (sets f, and sets v to "value")
	-vf value  (set v to "f" and value is the first parameter)

For the long value option val:

	--val value (sets val to "value")
	--val=value (sets val to "value")
	--valvalue  (invalid option "valvalue")

Values with an optional value only set the value if the value is part of the same argument. In any event, the option count is increased and the option is marked as seen.

	-v -f          (sets v and f as being seen)
	-vvalue -f     (sets v to "value" and sets f)
	--val -f       (sets v and f as being seen)
	--val=value -f (sets v to "value" and sets f)

There is no convience function defined for making the value optional. The SetOptional method must be called on the actual Option.

	v := String("val", 'v', "", "the optional v")
	Lookup("v").SetOptional()

	var s string
	FlagLong(&s, "val", 'v', "the optional v).SetOptional()

Parsing continues until the first non-option or "--" is encountered.

The short name "-" can be used, but it either is specified as "-" or as part of a group of options, for example "-f-". If there are no long options specified then "--f" could also be used. If "-" is not declared as an option then the single "-" will also terminate the option processing but unlike "--", the "-" will be part of the remaining arguments.

Advanced Usage

Normally the parsing is performed by calling the Parse function. If it is important to see the order of the options then the Getopt function should be used. The standard Parse function does the equivalent of:

func Parse() {
	if err := getopt.Getopt(os.Args, nil); err != nil {
		fmt.Fprintln(os.Stderr, err)
		s.usage()
		os.Exit(1)
	}
}

When calling Getopt it is the responsibility of the caller to print any errors.

Normally the default option set, CommandLine, is used. Other option sets may be created with New.

After parsing, the sets Args will contain the non-option arguments. If an error is encountered then Args will begin with argument that caused the error.

It is valid to call a set's Parse a second time to amend the current set of flags or values. As an example:

	var a = getopt.Bool('a', "", "The a flag")
	var b = getopt.Bool('b', "", "The a flag")
	var cmd = ""

	var opts = getopt.CommandLine

	opts.Parse(os.Args)
	if opts.NArgs() > 0 {
		cmd = opts.Arg(0)
		opts.Parse(opts.Args())
	}

If called with set to { "prog", "-a", "cmd", "-b", "arg" } then both a and b would be set, cmd would be set to "cmd", and opts.Args() would return { "arg" }.

Unless an option type explicitly prohibits it, an option may appear more than once in the arguments. The last value provided to the option is the value.

Builtin Types

The Flag and FlagLong functions support most standard Go types. For the list, see the description of FlagLong below for a list of supported types.

There are also helper routines to allow single line flag declarations. These types are: Bool, Counter, Duration, Enum, Int16, Int32, Int64, Int, List, Signed, String, Uint16, Uint32, Uint64, Uint, and Unsigned.

Each comes in a short and long flavor, e.g., Bool and BoolLong and include functions to set the flags on the standard command line or for a specific Set of flags.

Except for the Counter, Enum, Signed and Unsigned types, all of these types can be declared using Flag and FlagLong by passing in a pointer to the appropriate type.

Declaring New Flag Types

A pointer to any type that implements the Value interface may be passed to Flag or FlagLong.

VALUEHELP

All non-flag options are created with a "valuehelp" as the last parameter. Valuehelp should be 0, 1, or 2 strings. The first string, if provided, is the usage message for the option. If the second string, if provided, is the name to use for the value when displaying the usage. If not provided the term "value" is assumed.

The usage message for the option created with

	StringLong("option", 'o', "defval", "a string of letters")

is

	-o, -option=value

while the usage message for the option created with

	StringLong("option", 'o', "defval", "a string of letters", "string")

is

	-o, -option=string

Documentation

Overview

Package getopt (v1) provides traditional getopt processing for implementing commands that use traditional command lines. The standard Go flag package cannot be used to write a program that parses flags the way ls or ssh does, for example.

A new version of this package (v2) (whose package name is also getopt) is available as:

"github.com/pborman/getopt/v2"

Getopt supports functionality found in both the standard BSD getopt as well as (one of the many versions of) the GNU getopt_long. Being a Go package, this package makes common usage easy, but still enables more controlled usage if needed.

Typical usage:

// Declare the flags to be used
helpFlag := getopt.Bool('?', "display help")
cmdFlag := getopt.StringLong("command", 'c', "", "the command")

func main() {
	// Parse the program arguments
	getopt.Parse()
	// Get the remaining positional parameters
	args := getopt.Args()

If you don't want the program to exit on error, use getopt.Getopt:

err := getopt.Getopt(nil)
if err != nil {
	// code to handle error
	fmt.Fprintln(os.Stderr, err)
}

Support is provided for both short (-f) and long (--flag) options. A single option may have both a short and a long name. Each option may be a flag or a value. A value takes an argument.

Declaring no long names causes this package to process arguments like the traditional BSD getopt.

Short flags may be combined into a single parameter. For example, "-a -b -c" may also be expressed "-abc". Long flags must stand on their own "--alpha --beta"

Values require an argument. For short options the argument may either be immediately following the short name or as the next argument. Only one short value may be combined with short flags in a single argument; the short value must be after all short flags. For example, if f is a flag and v is a value, then:

-vvalue    (sets v to "value")
-v value   (sets v to "value")
-fvvalue   (sets f, and sets v to "value")
-fv value  (sets f, and sets v to "value")
-vf value  (set v to "f" and value is the first parameter)

For the long value option val:

--val value (sets val to "value")
--val=value (sets val to "value")
--valvalue  (invalid option "valvalue")

Values with an optional value only set the value if the value is part of the same argument. In any event, the option count is increased and the option is marked as seen.

-v -f          (sets v and f as being seen)
-vvalue -f     (sets v to "value" and sets f)
--val -f       (sets v and f as being seen)
--val=value -f (sets v to "value" and sets f)

There is no convience function defined for making the value optional. The SetOptional method must be called on the actual Option.

v := String("val", 'v', "", "the optional v")
Lookup("v").SetOptional()

var s string
StringVar(&s, "val", 'v', "the optional v).SetOptional()

Parsing continues until the first non-option or "--" is encountered.

The short name "-" can be used, but it either is specified as "-" or as part of a group of options, for example "-f-". If there are no long options specified then "--f" could also be used. If "-" is not declared as an option then the single "-" will also terminate the option processing but unlike "--", the "-" will be part of the remaining arguments.

Normally the parsing is performed by calling the Parse function. If it is important to see the order of the options then the Getopt function should be used. The standard Parse function does the equivalent of:

func Parse() {
	if err := getopt.Getopt(os.Args, nil); err != nil {
		fmt.Fprintln(os.Stderr, err)
		s.usage()
		os.Exit(1)
	}

When calling Getopt it is the responsibility of the caller to print any errors.

Normally the default option set, CommandLine, is used. Other option sets may be created with New.

After parsing, the sets Args will contain the non-option arguments. If an error is encountered then Args will begin with argument that caused the error.

It is valid to call a set's Parse a second time to amend the current set of flags or values. As an example:

var a = getopt.Bool('a', "", "The a flag")
var b = getopt.Bool('b', "", "The a flag")
var cmd = ""

var opts = getopt.CommandLine

opts.Parse(os.Args)
if opts.NArgs() > 0 {
    cmd = opts.Arg(0)
    opts.Parse(opts.Args())
}

If called with set to { "prog", "-a", "cmd", "-b", "arg" } then both and and b would be set, cmd would be set to "cmd", and opts.Args() would return { "arg" }.

Unless an option type explicitly prohibits it, an option may appear more than once in the arguments. The last value provided to the option is the value.

SYNTAX

For each option type there are an unfortunately large number of ways, 8, to initialize the option. This number is derived from three attributes:

  1. Short or Long name
  2. Normal vs Var
  3. Command Line vs Option Set

The first two variations provide 4 signature:

Option(name rune, [value type,]  helpvalue... string)
OptionLong(name string, short rune, [value type,]  helpvalue... string)
OptionVar(p *type, name rune, helpvalue... string)
OptionVarLong(p *type, name string, short rune, helpvalue... string)

Foo can actually be expressed in terms of FooLong:

func Foo(name rune, value type, helpvalue... string) *type {
    return FooLong("", name, value, helpvalue...)
}

Normally Foo is used, unless long options are needed. Setting short to 0 creates only a long option.

The difference bentween Foo and FooVar is that you pass a pointer, p, to the location of the value to FooVar. The default value is simply *p. The initial value of *p is the defaut value of the option.

Foo is actually a wrapper around FooVar:

func Foo(name rune, value type, helpvalue... string) *type {
    p := value
    FooVar(&p, name, helpvalue... string)
    return &p
}

The third variation provides a top-level function and a method on a Set:

func Option(...)
func (s *Set) Option(...)

The top-level function is simply:

func Option(...) *type {
    return CommandLine.Option(...) {
}

To simplfy documentation, typically only the main top-level function is fully documented. The others will have documentation when there is something special about them.

VALUEHELP

All non-flag options are created with a "valuehelp" as the last parameter. Valuehelp should be 0, 1, or 2 strings. The first string, if provided, is the usage message for the option. If the second string, if provided, is the name to use for the value when displaying the usage. If not provided the term "value" is assumed.

The usage message for the option created with

StringLong("option", 'o', "defval", "a string of letters")

is

-o, -option=value

StringLong("option", 'o', "defval", "a string of letters", "string")

is

-o, -option=string

Index

Constants

View Source
const (
	NoError          = ErrorCode(iota)
	UnknownOption    // an invalid option was encountered
	MissingParameter // the options parameter is missing
	ExtraParameter   // a value was set to a long flag
	Invalid          // attempt to set an invalid value
)
View Source
const (
	InProgress     = State(iota) // Getopt is still running
	Dash                         // Returned on "-"
	DashDash                     // Returned on "--"
	EndOfOptions                 // End of options reached
	EndOfArguments               // No more arguments
	Terminated                   // Terminated by callback function
	Failure                      // Terminated due to error
	Unknown                      // Indicates internal error
)

Variables

View Source
var CommandLine = New()

The default set of command-line options.

View Source
var DisplayWidth = 80

DisplayWidth is used to determine where to split usage long lines.

View Source
var HelpColumn = 20

HelpColumn is the maximum column position that help strings start to display at. If the option usage is too long then the help string will be displayed on the next line. For example:

-a   this is the a flag
-u, --under=location
     the u flag's usage is quite long

Functions

func AddOption

func AddOption(o Option)

AddOption add the option o to set CommandLine if o is not already in set CommandLine.

func Arg

func Arg(n int) string

Arg returns the n'th command-line argument. Arg(0) is the first remaining argument after options have been processed.

func Args

func Args() []string

Args returns the non-option command line arguments.

func Bool

func Bool(name rune, helpvalue ...string) *bool

Bool creates a flag option that is a bool. Bools normally do not take a value however one can be assigned by using the long form of the option:

--option=true
--o=false

Its value is case insenstive and one of true, false, t, f, on, off, t and 0.

func BoolLong

func BoolLong(name string, short rune, helpvalue ...string) *bool

func Counter

func Counter(name rune, helpvalue ...string) *int

Counter creates a counting flag stored as an int. Each time the option is seen while parsing the value is incremented. The value of the counter may be explicitly set by using the long form:

--counter=5
--c=5

Further instances of the option will increment from the set value.

func CounterLong

func CounterLong(name string, short rune, helpvalue ...string) *int

func Duration

func Duration(name rune, value time.Duration, helpvalue ...string) *time.Duration

Duration creates an option that parses its value as a time.Duration.

func DurationLong

func DurationLong(name string, short rune, value time.Duration, helpvalue ...string) *time.Duration

func Enum

func Enum(name rune, values []string, helpvalue ...string) *string

Enum creates an option that can only be set to one of the enumerated strings passed in values. Passing nil or an empty slice results in an option that will always fail.

func EnumLong

func EnumLong(name string, short rune, values []string, helpvalue ...string) *string

func GetCount

func GetCount(name interface{}) int

GetCount returns the number of times the Option associated with name has been seen while parsing the command line arguments. Name should either be a rune (the short name) or a string (the long name).

func GetValue

func GetValue(name interface{}) string

GetValue returns the final value set to the command-line Option with name. If the option has not been seen while parsing s then the default value is returned. Name should either be a rune (the short name) or a string (the long name).

func Getopt

func Getopt(fn func(Option) bool) error

Getops returns the result of calling Getop in the default option set with the command line arguments found in os.Args. The fn function, which may be nil, is passed to Getopt.

func Int

func Int(name rune, value int, helpvalue ...string) *int

Int creates an option that parses its value as an integer.

func Int16

func Int16(name rune, value int16, helpvalue ...string) *int16

Int16 creates an option that parses its value as an int16.

func Int16Long

func Int16Long(name string, short rune, value int16, helpvalue ...string) *int16

func Int32

func Int32(name rune, value int32, helpvalue ...string) *int32

Int32 creates an option that parses its value as an int32.

func Int32Long

func Int32Long(name string, short rune, value int32, helpvalue ...string) *int32

func Int64

func Int64(name rune, value int64, helpvalue ...string) *int64

Int64 creates an option that parses its value as an int64.

func Int64Long

func Int64Long(name string, short rune, value int64, helpvalue ...string) *int64

func IntLong

func IntLong(name string, short rune, value int, helpvalue ...string) *int

func IsSet

func IsSet(name interface{}) bool

IsSet returns true if the Option associated with name was seen while parsing the command line arguments. Name should either be a rune (the short name) or a string (the long name).

func List

func List(name rune, helpvalue ...string) *[]string

List creates an option that returns a slice of strings. The parameters passed are converted from a comma seperated value list into a slice. Subsequent occurrences append to the list.

func ListLong

func ListLong(name string, short rune, helpvalue ...string) *[]string

func NArgs

func NArgs() int

NArgs returns the number of non-option command line arguments.

func Parse

func Parse()

Parse calls Parse in the default option set with the command line arguments found in os.Args.

func PrintUsage

func PrintUsage(w io.Writer)

PrintUsage calls PrintUsage in the default option set.

func Reset

func Reset()

Reset resets all the command line options to the initial state so it appears none of them have been seen.

func SetParameters

func SetParameters(parameters string)

SetParameters sets the parameters string for printing the command line usage. It defaults to "[parameters ...]"

func SetProgram

func SetProgram(program string)

SetProgram sets the program name to program. Nomrally it is determined from the zeroth command line argument (see os.Args).

func SetUsage

func SetUsage(usage func())

SetUsage sets the function used by Parse to display the commands usage on error. It defaults to calling PrintUsage(os.Stderr).

func Signed

func Signed(name rune, value int64, l *SignedLimit, helpvalue ...string) *int64

Signed creates an option that is stored in an int64 and is constrained by the limits pointed to by l. The Max and Min values are only used if at least one of the values are not 0. If Base is 0, the base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

func SignedLong

func SignedLong(name string, short rune, value int64, l *SignedLimit, helpvalue ...string) *int64

func String

func String(name rune, value string, helpvalue ...string) *string

String returns a value option that stores is value as a string. The initial value of the string is passed in value.

func StringLong

func StringLong(name string, short rune, value string, helpvalue ...string) *string

func Uint

func Uint(name rune, value uint, helpvalue ...string) *uint

Uint creates an option that parses its value as an unsigned integer.

func Uint16

func Uint16(name rune, value uint16, helpvalue ...string) *uint16

Uint16 creates an option that parses its value as an uint16.

func Uint16Long

func Uint16Long(name string, short rune, value uint16, helpvalue ...string) *uint16

func Uint32

func Uint32(name rune, value uint32, helpvalue ...string) *uint32

Uint32 creates an option that parses its value as an uint32.

func Uint32Long

func Uint32Long(name string, short rune, value uint32, helpvalue ...string) *uint32

func Uint64

func Uint64(name rune, value uint64, helpvalue ...string) *uint64

Uint64 creates an option that parses its value as a uint64.

func Uint64Long

func Uint64Long(name string, short rune, value uint64, helpvalue ...string) *uint64

func UintLong

func UintLong(name string, short rune, value uint, helpvalue ...string) *uint

func Unsigned

func Unsigned(name rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64

Unsigned creates an option that is stored in a uint64 and is constrained by the limits pointed to by l. The Max and Min values are only used if at least one of the values are not 0. If Base is 0, the base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

func UnsignedLong

func UnsignedLong(name string, short rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64

func Usage

func Usage()

Usage calls the usage function in the default option set.

func Visit

func Visit(fn func(Option))

Visit visits the command-line options in lexicographical order, calling fn for each. It visits only those options that have been set.

func VisitAll

func VisitAll(fn func(Option))

VisitAll visits the options in s in lexicographical order, calling fn for each. It visits all options, even those not set.

Types

type Error

type Error struct {
	ErrorCode        // General reason of failure.
	Err       error  // The actual error.
	Parameter string // Parameter passed to option, if any
	Name      string // Option that cause error, if any
}

An Error is returned by Getopt when it encounters an error.

func (*Error) Error

func (i *Error) Error() string

Error returns the error message, implementing the error interface.

type ErrorCode

type ErrorCode int

An ErrorCode indicates what sort of error was encountered.

func (ErrorCode) String

func (e ErrorCode) String() string

type Option

type Option interface {
	// Name returns the name of the option.  If the option has been seen
	// then the last way it was referenced (short or long) is returned
	// otherwise if there is a short name then this will be the short name
	// as a string, else it will be the long name.
	Name() string

	// IsFlag returns true if Option is a flag.
	IsFlag() bool

	// Seen returns true if the flag was seen.
	Seen() bool

	// Count returns the number of times the flag was seen.
	Count() int

	// String returns the last value the option was set to.
	String() string

	// Value returns the Value of the option.
	Value() Value

	// SetOptional makes the value optional.  The option and value are
	// always a single argument.  Either --option or --option=value.  In
	// the former case the value of the option does not change but the Set()
	// will return true and the value returned by Count() is incremented.
	// The short form is either -o or -ovalue.  SetOptional returns
	// the Option
	SetOptional() Option

	// SetFlag makes the value a flag.  Flags are boolean values and
	// normally do not taken a value.  They are set to true when seen.
	// If a value is passed in the long form then it must be on, case
	// insenstive, one of "true", "false", "t", "f", "on", "off", "1", "0".
	// SetFlag returns the Option
	SetFlag() Option

	// Reset resets the state of the option so it appears it has not
	// yet been seen, including resetting the value of the option
	// to its original default state.
	Reset()
}

An Option can be either a Flag or a Value

func BoolVar

func BoolVar(p *bool, name rune, helpvalue ...string) Option

func BoolVarLong

func BoolVarLong(p *bool, name string, short rune, helpvalue ...string) Option

func CounterVar

func CounterVar(p *int, name rune, helpvalue ...string) Option

func CounterVarLong

func CounterVarLong(p *int, name string, short rune, helpvalue ...string) Option

func DurationVar

func DurationVar(p *time.Duration, name rune, helpvalue ...string) Option

func DurationVarLong

func DurationVarLong(p *time.Duration, name string, short rune, helpvalue ...string) Option

func EnumVar

func EnumVar(p *string, name rune, values []string, helpvalue ...string) Option

EnumVar creates an enum option that defaults to the starting value of *p. If *p is not found in values then a reset of this option will fail.

func EnumVarLong

func EnumVarLong(p *string, name string, short rune, values []string, helpvalue ...string) Option

func Int16Var

func Int16Var(p *int16, name rune, helpvalue ...string) Option

func Int16VarLong

func Int16VarLong(p *int16, name string, short rune, helpvalue ...string) Option

func Int32Var

func Int32Var(p *int32, name rune, helpvalue ...string) Option

func Int32VarLong

func Int32VarLong(p *int32, name string, short rune, helpvalue ...string) Option

func Int64Var

func Int64Var(p *int64, name rune, helpvalue ...string) Option

func Int64VarLong

func Int64VarLong(p *int64, name string, short rune, helpvalue ...string) Option

func IntVar

func IntVar(p *int, name rune, helpvalue ...string) Option

func IntVarLong

func IntVarLong(p *int, name string, short rune, helpvalue ...string) Option

func ListVar

func ListVar(p *[]string, name rune, helpvalue ...string) Option

ListVar creats a list option and places the values in p. If p is pointing to a list of values then those are considered the default values. The first time name is seen in the options the list will be set to list specified by the parameter to the option. Subsequent instances of the option will append to the list.

func ListVarLong

func ListVarLong(p *[]string, name string, short rune, helpvalue ...string) Option

func Lookup

func Lookup(name interface{}) Option

Lookup returns the Option associated with name. Name should either be a rune (the short name) or a string (the long name).

func SignedVar

func SignedVar(p *int64, name rune, l *SignedLimit, helpvalue ...string) Option

func SignedVarLong

func SignedVarLong(p *int64, name string, short rune, l *SignedLimit, helpvalue ...string) Option

func StringVar

func StringVar(p *string, name rune, helpvalue ...string) Option

func StringVarLong

func StringVarLong(p *string, name string, short rune, helpvalue ...string) Option

func Uint16Var

func Uint16Var(p *uint16, name rune, helpvalue ...string) Option

func Uint16VarLong

func Uint16VarLong(p *uint16, name string, short rune, helpvalue ...string) Option

func Uint32Var

func Uint32Var(p *uint32, name rune, helpvalue ...string) Option

func Uint32VarLong

func Uint32VarLong(p *uint32, name string, short rune, helpvalue ...string) Option

func Uint64Var

func Uint64Var(p *uint64, name rune, helpvalue ...string) Option

func Uint64VarLong

func Uint64VarLong(p *uint64, name string, short rune, helpvalue ...string) Option

func UintVar

func UintVar(p *uint, name rune, helpvalue ...string) Option

func UintVarLong

func UintVarLong(p *uint, name string, short rune, helpvalue ...string) Option

func UnsignedVar

func UnsignedVar(p *uint64, name rune, l *UnsignedLimit, helpvalue ...string) Option

func UnsignedVarLong

func UnsignedVarLong(p *uint64, name string, short rune, l *UnsignedLimit, helpvalue ...string) Option

func Var

func Var(p Value, name rune, helpvalue ...string) Option

Var creates an option of the specified name. The type and value of the option are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. All options are ultimately created as a Var.

func VarLong

func VarLong(p Value, name string, short rune, helpvalue ...string) Option

type Set

type Set struct {
	State // State of getopt
	// contains filtered or unexported fields
}

func New

func New() *Set

New returns a newly created option set.

func (*Set) AddOption

func (s *Set) AddOption(o Option)

AddOption add the option o to set s if o is not already in set s.

func (*Set) Arg

func (s *Set) Arg(n int) string

Arg returns the n'th argument. Arg(0) is the first remaining argument after options have been processed.

func (*Set) Args

func (s *Set) Args() []string

Args returns the non-option arguments.

func (*Set) Bool

func (s *Set) Bool(name rune, helpvalue ...string) *bool

func (*Set) BoolLong

func (s *Set) BoolLong(name string, short rune, helpvalue ...string) *bool

func (*Set) BoolVar

func (s *Set) BoolVar(p *bool, name rune, helpvalue ...string) Option

func (*Set) BoolVarLong

func (s *Set) BoolVarLong(p *bool, name string, short rune, helpvalue ...string) Option

func (*Set) Counter

func (s *Set) Counter(name rune, helpvalue ...string) *int

func (*Set) CounterLong

func (s *Set) CounterLong(name string, short rune, helpvalue ...string) *int

func (*Set) CounterVar

func (s *Set) CounterVar(p *int, name rune, helpvalue ...string) Option

func (*Set) CounterVarLong

func (s *Set) CounterVarLong(p *int, name string, short rune, helpvalue ...string) Option

func (*Set) Duration

func (s *Set) Duration(name rune, value time.Duration, helpvalue ...string) *time.Duration

func (*Set) DurationLong

func (s *Set) DurationLong(name string, short rune, value time.Duration, helpvalue ...string) *time.Duration

func (*Set) DurationVar

func (s *Set) DurationVar(p *time.Duration, name rune, helpvalue ...string) Option

func (*Set) DurationVarLong

func (s *Set) DurationVarLong(p *time.Duration, name string, short rune, helpvalue ...string) Option

func (*Set) Enum

func (s *Set) Enum(name rune, values []string, helpvalue ...string) *string

func (*Set) EnumLong

func (s *Set) EnumLong(name string, short rune, values []string, helpvalue ...string) *string

func (*Set) EnumVar

func (s *Set) EnumVar(p *string, name rune, values []string, helpvalue ...string) Option

func (*Set) EnumVarLong

func (s *Set) EnumVarLong(p *string, name string, short rune, values []string, helpvalue ...string) Option

func (*Set) GetCount

func (s *Set) GetCount(name interface{}) int

GetCount returns the number of times the Option associated with name has been seen while parsing s's arguments. Name should either be a rune (the short name) or a string (the long name).

func (*Set) GetValue

func (s *Set) GetValue(name interface{}) string

GetValue returns the final value set to the Option in s associated with name. If the option has not been seen while parsing s then the default value is returned. Name should either be a rune (the short name) or a string (the long name).

func (*Set) Getopt

func (s *Set) Getopt(args []string, fn func(Option) bool) (err error)

Parse uses Getopt to parse args using the options set for s. The first element of args is used to assign the program for s if it is not yet set. Getop calls fn, if not nil, for each option parsed.

Getopt returns nil when all options have been processed (a non-option argument was encountered, "--" was encountered, or fn returned false).

On error getopt returns a refernce to an InvalidOption (which implements the error interface).

func (*Set) Int

func (s *Set) Int(name rune, value int, helpvalue ...string) *int

func (*Set) Int16

func (s *Set) Int16(name rune, value int16, helpvalue ...string) *int16

func (*Set) Int16Long

func (s *Set) Int16Long(name string, short rune, value int16, helpvalue ...string) *int16

func (*Set) Int16Var

func (s *Set) Int16Var(p *int16, name rune, helpvalue ...string) Option

func (*Set) Int16VarLong

func (s *Set) Int16VarLong(p *int16, name string, short rune, helpvalue ...string) Option

func (*Set) Int32

func (s *Set) Int32(name rune, value int32, helpvalue ...string) *int32

func (*Set) Int32Long

func (s *Set) Int32Long(name string, short rune, value int32, helpvalue ...string) *int32

func (*Set) Int32Var

func (s *Set) Int32Var(p *int32, name rune, helpvalue ...string) Option

func (*Set) Int32VarLong

func (s *Set) Int32VarLong(p *int32, name string, short rune, helpvalue ...string) Option

func (*Set) Int64

func (s *Set) Int64(name rune, value int64, helpvalue ...string) *int64

func (*Set) Int64Long

func (s *Set) Int64Long(name string, short rune, value int64, helpvalue ...string) *int64

func (*Set) Int64Var

func (s *Set) Int64Var(p *int64, name rune, helpvalue ...string) Option

func (*Set) Int64VarLong

func (s *Set) Int64VarLong(p *int64, name string, short rune, helpvalue ...string) Option

func (*Set) IntLong

func (s *Set) IntLong(name string, short rune, value int, helpvalue ...string) *int

func (*Set) IntVar

func (s *Set) IntVar(p *int, name rune, helpvalue ...string) Option

func (*Set) IntVarLong

func (s *Set) IntVarLong(p *int, name string, short rune, helpvalue ...string) Option

func (*Set) IsSet

func (s *Set) IsSet(name interface{}) bool

IsSet returns true if the Option associated with name was seen while parsing s. Name should either be a rune (the short name) or a string (the long name).

func (*Set) List

func (s *Set) List(name rune, helpvalue ...string) *[]string

func (*Set) ListLong

func (s *Set) ListLong(name string, short rune, helpvalue ...string) *[]string

func (*Set) ListVar

func (s *Set) ListVar(p *[]string, name rune, helpvalue ...string) Option

func (*Set) ListVarLong

func (s *Set) ListVarLong(p *[]string, name string, short rune, helpvalue ...string) Option

func (*Set) Lookup

func (s *Set) Lookup(name interface{}) Option

Lookup returns the Option associated with name in s. Name should either be a rune (the short name) or a string (the long name).

func (*Set) NArgs

func (s *Set) NArgs() int

NArgs returns the number of non-option arguments.

func (*Set) Parse

func (s *Set) Parse(args []string)

Parse uses Getopt to parse args using the options set for s. The first element of args is used to assign the program for s if it is not yet set. On error, Parse displays the error message as well as a usage message on standard error and then exits the program.

func (*Set) PrintOptions

func (s *Set) PrintOptions(w io.Writer)

PrintOptions prints the list of options in s to w.

func (*Set) PrintUsage

func (s *Set) PrintUsage(w io.Writer)

PrintUsage prints the usage of the program to w.

func (*Set) Reset

func (s *Set) Reset()

Reset resets all the options in s to the initial state so it appears none of them have been seen.

func (*Set) SetParameters

func (s *Set) SetParameters(parameters string)

SetParameters sets the parameters string for printing the s's usage. It defaults to "[parameters ...]"

func (*Set) SetProgram

func (s *Set) SetProgram(program string)

SetProgram sets s's program name to program. Nomrally it is determined from the zeroth argument passed to Getopt or Parse.

func (*Set) SetUsage

func (s *Set) SetUsage(usage func())

SetUsage sets the function used by Parse to display usage on error. It defaults to calling f.PrintUsage(os.Stderr).

func (*Set) Signed

func (s *Set) Signed(name rune, value int64, l *SignedLimit, helpvalue ...string) *int64

func (*Set) SignedLong

func (s *Set) SignedLong(name string, short rune, value int64, l *SignedLimit, helpvalue ...string) *int64

func (*Set) SignedVar

func (s *Set) SignedVar(p *int64, name rune, l *SignedLimit, helpvalue ...string) Option

func (*Set) SignedVarLong

func (s *Set) SignedVarLong(p *int64, name string, short rune, l *SignedLimit, helpvalue ...string) Option

func (*Set) String

func (s *Set) String(name rune, value string, helpvalue ...string) *string

func (*Set) StringLong

func (s *Set) StringLong(name string, short rune, value string, helpvalue ...string) *string

func (*Set) StringVar

func (s *Set) StringVar(p *string, name rune, helpvalue ...string) Option

func (*Set) StringVarLong

func (s *Set) StringVarLong(p *string, name string, short rune, helpvalue ...string) Option

func (*Set) Uint

func (s *Set) Uint(name rune, value uint, helpvalue ...string) *uint

func (*Set) Uint16

func (s *Set) Uint16(name rune, value uint16, helpvalue ...string) *uint16

func (*Set) Uint16Long

func (s *Set) Uint16Long(name string, short rune, value uint16, helpvalue ...string) *uint16

func (*Set) Uint16Var

func (s *Set) Uint16Var(p *uint16, name rune, helpvalue ...string) Option

func (*Set) Uint16VarLong

func (s *Set) Uint16VarLong(p *uint16, name string, short rune, helpvalue ...string) Option

func (*Set) Uint32

func (s *Set) Uint32(name rune, value uint32, helpvalue ...string) *uint32

func (*Set) Uint32Long

func (s *Set) Uint32Long(name string, short rune, value uint32, helpvalue ...string) *uint32

func (*Set) Uint32Var

func (s *Set) Uint32Var(p *uint32, name rune, helpvalue ...string) Option

func (*Set) Uint32VarLong

func (s *Set) Uint32VarLong(p *uint32, name string, short rune, helpvalue ...string) Option

func (*Set) Uint64

func (s *Set) Uint64(name rune, value uint64, helpvalue ...string) *uint64

func (*Set) Uint64Long

func (s *Set) Uint64Long(name string, short rune, value uint64, helpvalue ...string) *uint64

func (*Set) Uint64Var

func (s *Set) Uint64Var(p *uint64, name rune, helpvalue ...string) Option

func (*Set) Uint64VarLong

func (s *Set) Uint64VarLong(p *uint64, name string, short rune, helpvalue ...string) Option

func (*Set) UintLong

func (s *Set) UintLong(name string, short rune, value uint, helpvalue ...string) *uint

func (*Set) UintVar

func (s *Set) UintVar(p *uint, name rune, helpvalue ...string) Option

func (*Set) UintVarLong

func (s *Set) UintVarLong(p *uint, name string, short rune, helpvalue ...string) Option

func (*Set) Unsigned

func (s *Set) Unsigned(name rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64

func (*Set) UnsignedLong

func (s *Set) UnsignedLong(name string, short rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64

func (*Set) UnsignedVar

func (s *Set) UnsignedVar(p *uint64, name rune, l *UnsignedLimit, helpvalue ...string) Option

func (*Set) UnsignedVarLong

func (s *Set) UnsignedVarLong(p *uint64, name string, short rune, l *UnsignedLimit, helpvalue ...string) Option

func (*Set) Var

func (s *Set) Var(p Value, name rune, helpvalue ...string) Option

func (*Set) VarLong

func (s *Set) VarLong(p Value, name string, short rune, helpvalue ...string) Option

func (*Set) Visit

func (s *Set) Visit(fn func(Option))

Visit visits the options in s in lexicographical order, calling fn for each. It visits only those options that have been set.

func (*Set) VisitAll

func (s *Set) VisitAll(fn func(Option))

VisitAll visits the command-line flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

type SignedLimit

type SignedLimit struct {
	Base int   // Base for conversion as per strconv.ParseInt
	Bits int   // Number of bits as per strconv.ParseInt
	Min  int64 // Minimum allowed value if both Min and Max are not 0
	Max  int64 // Maximum allowed value if both Min and Max are not 0
}

type State

type State int

A Termination says why Getopt returned.

type UnsignedLimit

type UnsignedLimit struct {
	Base int    // Base for conversion as per strconv.ParseInt
	Bits int    // Number of bits as per strconv.ParseInt
	Min  uint64 // Minimum allowed value if both Min and Max are not 0
	Max  uint64 // Maximum allowed value if both Min and Max are not 0
}

type Value

type Value interface {
	Set(string, Option) error
	String() string
}

Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.) Set is passed the string to set the value to as well as the Option that is being processed.

Jump to

Keyboard shortcuts

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