getopt

package module
v0.0.0-...-158f808 Latest Latest
Warning

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

Go to latest
Published: May 10, 2024 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package getopt provides GNU-style argument parsing for both short and long arguments.

Differences from Posix getopt:

  1. There are no global variables. All operations are performed on a Getopt struct that maintains state between successive calls.
  2. The opterr setting is permanently false. Errors are never printed anywhere by this library. Instead, errors are returned and the caller can choose what to do with them. The text of the errors corresponds to messages that would be printed by GNU getopt. The leading ':' in the option spec that controls error-reporting is accepted for compatibility, but it's ignored.
  3. A struct is returned instead of just the matched option character. The struct includes the option character, any value that would have been in optarg, as well as any value that would have been returned in the longindex argument to getopt_long.
  4. The optopt value is not used. Instead, the relevant unrecognized character or option name is available in the Option field of whatever error gets returned.
  5. The Flag and Val fields of Option have type rune, not int.
  6. The list of options and arguments cannot be changed in the middle of parsing. The argument list and option definition are set once at the start, and then you just call Getopt or GetoptLong with no parameters.

Index

Constants

View Source
const (
	// RequireOrder means don't recognize them as options; stop option processing when the first non-option is seen.
	// This is what POSIX specifies should happen.
	RequireOrder ordering = iota

	// Permute means permute the contents of Args as we scan, so that eventually all the non-options are at the end.
	// This allows options to be given in any order, even with programs that were not written to expect this.
	Permute

	// ReturnInOrder is an option available to programs that were written to expect options and other arguments in
	// any order and that care about the ordering of the two. We describe each non-option argument as if it were the
	// argument of an option with character code 1.
	ReturnInOrder
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AmbiguousOptionError

type AmbiguousOptionError struct {
	Option     string
	Candidates []string
	// contains filtered or unexported fields
}

AmbiguousOptionError is returned when there is no exact match for Option, but more than one abbreviated match, which are given in Candidates.

func (AmbiguousOptionError) Error

func (e AmbiguousOptionError) Error() string

type ArgumentDisposition

type ArgumentDisposition int

ArgumentDisposition is an enum specifying whether an option expects to be followed by an argument. Use it when defining the Option list for long options.

const (
	NoArgument       ArgumentDisposition = iota // The option does not take an argument.
	RequiredArgument                            // The option requires an argument.
	OptionalArgument                            // The option takes an optional argument.
)

These values are used for the HasArg field of Options.

type ArgumentNotAllowedError

type ArgumentNotAllowedError struct {
	Option string
	// contains filtered or unexported fields
}

ArgumentNotAllowedError is returned when Option does not accept arguments but one is provided anyway.

func (ArgumentNotAllowedError) Error

func (e ArgumentNotAllowedError) Error() string

type ArgumentRequiredError

type ArgumentRequiredError struct {
	Option string
	// contains filtered or unexported fields
}

ArgumentRequiredError is returned when Option expects an argument and none is given.

func (ArgumentRequiredError) Error

func (e ArgumentRequiredError) Error() string

type Getopt

type Getopt struct {
	Args []string // Args holds a copy of the argument list. It gets permuted during parsing.
	// contains filtered or unexported fields
}

Getopt is an option parser.

func New

func New(args []string, opts string) *Getopt

New creates a new Getopt initialized as by Reset.

func NewLong

func NewLong(args []string, opts string, longOptions []Option) *Getopt

NewLong creates a new Getopt initialized as by ResetLong.

func (*Getopt) Getopt

func (g *Getopt) Getopt() (*Opt, error)

Getopt scans elements of Args for option characters.

If an element of Args starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If Getopt is called repeatedly, it returns successively each of the option characters from each of the option elements.

If Getopt finds another option character, it returns an Opt and updates 'optind' and 'nextchar' so that the next call to Getopt can resume the scan with the following option character or argument.

If there are no more option characters, Getopt returns nil. Then 'optind' is the index in Args of the first argument that is not an option. (The arguments have been permuted so that those that are not options now come last.)

If an option character is seen that was not listed in the opt string when calling New or Reset, then Getopt returns an UnrecognizedOptionError. It does not print messages to stderr; in that respect, it behaves as if the Posix value opterr is always false.

If an option wants an argument, then the following text in the same Args element, or the text of the following Args element, is returned in Opt.Arg. If the option's argument is optional, then if there is text in the current Args element, it is returned in Opt.Arg. Otherwise, Opt.Arg will be nil.

Long-named options begin with '--' instead of '-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same Args element, separated from the option name by a '=', or else the in next Args element. When Getopt finds a long-named option, it returns an Opt whose C field is 0 if that option's 'Flag' field is non-nil, or the value of the option's 'Val' field if the 'Flag' field is nil. The Opt.LongInd field is only valid when a long-named option has been found.

The elements of Args aren't really const, because we permute them.

func (*Getopt) GetoptLong

func (g *Getopt) GetoptLong() (*Opt, error)

GetoptLong is identical to Getopt.

func (*Getopt) GetoptLongOnly

func (g *Getopt) GetoptLongOnly() (*Opt, error)

GetoptLongOnly is identical to Getopt and GetoptLong, except that '-' as well as '--' can introduce long-named options.

func (*Getopt) Optind

func (g *Getopt) Optind() int

Optind returns the argument index of the next argument to be scanned. When Getopt returns -1, Optind will be the index of the first non-option element in Args, which is where the caller should pick up scanning.

To reset the scanner, call Optreset instead of setting optind=0.

func (*Getopt) Reset

func (g *Getopt) Reset(args []string, opts string)

Reset initializes the Getopt for a new round of argument-parsing, using the argument list and short option specification passed in here. Unlike the Posix getopt, this library stores the argument list and the option definition in the Getopt struct so that each successive call in the parsing loop doesn't need to repeat the same list of parameters.

The opts string is a list of characters that are recognized option letters, optionally followed by colons to specify that that letter takes an argument (returned via Opt.Arg). If a letter in opts is followed by two colons, its argument is optional. This behavior mimics the GNU extension.

The argument '--' causes premature termination of argument scanning, explicitly telling Getopt that there are no more options.

If opts begins with '-', then non-option arguments are treated as arguments to the option 1. This behavior mimics the GNU extension. If opts begins with '+', or if POSIXLY_CORRECT is set in the environment at the time Reset is called, then arguments will not be permuted during parsing.

The argument list is assumed to include the program name at index 0; it is not returned or processed as a real argument.

func (*Getopt) ResetLong

func (g *Getopt) ResetLong(args []string, opts string, longOptions []Option)

ResetLong initializes the Getopt for a new round of argument-parsing using the argument list and short and long option specifications given.

If opts includes 'W' followed by ';', then a GNU extension is enabled that allows long options to be specified as arguments to the short option '-W'. The argument sequence '-W foo=bar' will behave just as if it were '--foo=bar'.

type Opt

type Opt struct {
	C       rune
	Arg     *string
	LongInd int
}

Opt is a result from Getopt. If C is 0, then a long option was matched, Flag pointed at a variable and it has been assigned a value from Val, but Opt.Arg holds the argument for that option, if any, and LongInd holds the index of the long option that matched. If C is 1, then ordering is ReturnInOrder and Arg points to the current non-option argument. Otherwise, C holds the rune value of the matched short option or Val of the matched long option (in which case LongInd also holds the index of the matched long option).

type Option

type Option struct {
	Name   string
	HasArg ArgumentDisposition
	Flag   *rune
	Val    rune
}

Option describes the long-named options requested by the application. The longopts arguments to NewLong, ResetLong, and others are slices of these types.

If Flag is not nil, then it points to a variable that will have its value set to Val when the option is found, but will be left unchanged if the option is not found.

To have a long-named option do something other than set a rune to a compiled-in constant, such as set a value from Opt.Arg, set the option's Flag to nil and its Val to a nonzero value (such as the option's equivalent single-letter option character, if there is one). For long options that have a nil Flag, Getopt returns the Val field in Opt.C.

type UnrecognizedOptionError

type UnrecognizedOptionError struct {
	Option string
	// contains filtered or unexported fields
}

UnrecognizedOptionError is returned when Option on the command line is not a recogized option.

func (UnrecognizedOptionError) Error

func (e UnrecognizedOptionError) Error() string

Jump to

Keyboard shortcuts

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