options

package module
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2023 License: Apache-2.0 Imports: 11 Imported by: 9

README

options build status GoDoc

Structured getopt processing for Go programs using the github.com/pborman/getopt/v2 package.

The options package makes adding getopt style command line options to Go programs as easy as declaring a structure:

package main

import (
	"fmt"
	"time"

	"github.com/pborman/options"
)

var opts = struct {
	Help    options.Help  `getopt:"--help           display help"`
	Name    string        `getopt:"--name=NAME      name of the widget"`
	Count   int           `getopt:"--count -c=COUNT number of widgets"`
	Verbose bool          `getopt:"-v               be verbose"`
	N       int           `getopt:"-n=NUMBER        set n to NUMBER"`
	Timeout time.Duration `getopt:"--timeout        duration of run"`
	Lazy    string
}{
	Name: "gopher",
}

func main() {
	args := options.RegisterAndParse(&opts)

	if opts.Verbose {
		fmt.Printf("Command line parameters: %q\n", args)
	}
	fmt.Printf("Name: %s\n", opts.Name)
}

The options.Help type causes the command's usage to be displayed to standard error and the command to exit when the option is parsed from the command line.

The options package also supports reading options from file specified on the command line or an optional defaults file:

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/pborman/options"
)

var opts = struct {
	Flags   options.Flags `getopt:"--flags=PATH     read options from PATH"`
	Name    string        `getopt:"--name=NAME      name of the widget"`
	Count   int           `getopt:"--count -c=COUNT number of widgets"`
	Verbose bool          `getopt:"-v               be verbose"`
	N       int           `getopt:"-n=NUMBER        set n to NUMBER"`
	Timeout time.Duration `getopt:"--timeout        duration of run"`
	Lazy    string
}{
	Name: "gopher",
}

func main() {
	options.Register(&opts)
	// read defaults from ~/.example.flags if the file exists.
	if err := opts.Flags.Set("?${HOME}/.example.flags", nil); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	args := options.Parse()

	if opts.Verbose {
		fmt.Printf("Command line parameters: %q\n", args)
	}
	fmt.Printf("Name: %s\n", opts.Name)
}

Using the following .example.flags file in your home directory that contains:

v = true
name = "github user"

The above program produces the following output:

$ go run x.go a parameter
Command line parameters: ["a" "parameter"]
Name: github user

$ go run x.go --help     
unknown option: --help
Usage: x [-v] [-c COUNT] [--flags PATH] [--lazy value] [-n NUMBER] [--name NAME] [--timeout value] [parameters ...]
 -c, --count=COUNT  number of widgets
     --flags=PATH   read options from PATH
     --lazy=value   unspecified
 -n NUMBER          set n to NUMBER
     --name=NAME    name of the widget [gopher]
     --timeout=value
                    duration of run
 -v                 be verbose
exit status 1

Documentation

Overview

Package options provides a structured interface for getopt style flag parsing. It is particularly helpful for parsing an option set more than once and possibly concurrently. This package was designed to make option specification simpler and more concise. It is a wrapper around the github.com/pborman/getopt/v2 package.

Package options also provides a facility to specify command line options in a text file by using the Flags type (described below).

Option Decorations

Options are declared in a structure that contains all information needed for the options. Each exported field of the structure represents an option. The fields tag is used to provide additional details. The tag contains up to four pieces of information:

Long name of the option (e.g. --name)
Short name of the option (e.g., -n)
Parameter name (e.g. NAME)
Description (e.g., "Sets the name to NAME")

The syntax of a tag is:

[--option[=PARAM]] [-o] [--] description

The long and/or short options must come first in the tag. The parameter name is specified by appending =PARAM to one of the declared options (e.g., --option=VALUE). The description is everything following the option declaration(s). The options and description message are delimited by one or more white space characters. An empty option (- or --) terminates option declarations, everything following is the description. This enables the description to start with a -, e.g. "-v -- -v means verbose".

Example Tags

The following are example tags

"--name=NAME -n sets the name to NAME"
"-n=NAME        sets the name to NAME"
"--name         sets the name"

A tag of just "-" causes the field to be ignored an not used as an option. An empty tag or missing tag causes the tag to be auto-generated.

Name string -> "--name unspecified"
N int       -> "-n unspecified"

Types

The fields of the structure can be any type that can be passed to getopt.Flag as a pointer (e.g., string, []string, int, bool, time.Duration, etc). This includes any type that implements getopt.Value.

Example Structure

The following structure declares 7 options and sets the default value of Count to be 42. The --flags option is used to read option values from a file.

type theOptions struct {
    Flags   options.Flags `getopt:"--flags=PATH     read defaults from path"`
    Name    string        `getopt:"--name=NAME      name of the widget"`
    Count   int           `getopt:"--count -c=COUNT number of widgets"`
    Verbose bool          `getopt:"-v               be verbose"`
    N       int           `getopt:"-n=NUMBER        set n to NUMBER"`
    Timeout time.Duration `getopt:"--timeout        duration of run"`
    Lazy    string
}
var myOptions = theOptions {
    Count: 42,
}

The help message generated from theOptions is:

Usage:  [-v] [-c COUNT] [--flags PATH] [--lazy value] [-n NUMBER] [--name NAME] [--timeout value] [parameters ...]
 -c, --count=COUNT    number of widgets
     --flags=PATH     read defaults from PATH
     --lazy=value     unspecified
 -n NUMBER            set n to NUMBER
     --name=NAME      name of the widget
     --timeout=value  duration of run
 -v                   be verbose

Usage

The following are various ways to use the above declaration.

// Register myOptions, parse the command line, and set args to the
// remaining command line parameters
args := options.RegisterAndParse(&myOptions)

// Validate myOptions.
err := options.Validate(&myOptions)
if err != nil { ... }

// Register myOptions as command line options.
options.Register(&myOptions)

// Register myOptions as a new getopt Set.
set := getopt.New()
options.RegisterSet(&myOptions, set)

// Register a new instance of myOptions
vopts, set := options.RegisterNew(&myOptions)
opts := vopts.(*theOptions)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Dup

func Dup(i interface{}) interface{}

Dup returns a shallow duplicate of i or panics. Dup panics if i is not a pointer to struct or has an invalid getopt tag. Dup does not copy non-exported fields or fields whose getopt tag is "-".

Dup is normally used to create a unique instance of the set of options so i can be used multiple times.

func Lookup

func Lookup(i interface{}, option string) interface{}

Lookup returns the value of the field in i for the specified option or nil. Lookup can be used if the structure declaring the options is not available. Lookup returns nil if i is invalid or does not have an option named option.

Example

Fetch the verbose flag from an anonymous structure:

i, set := options.RegisterNew(&struct {
	Verbose bool `getopt:"--verbose -v be verbose"`
})
set.Getopt(args, nil)
v := options.Lookup(i, "verbose").(bool)

func Parse

func Parse() []string

Parse calls getopt.Parse and returns getopt.Args().

func PrintUsage added in v1.3.1

func PrintUsage(w io.Writer)

PrintUsage calls PrintUsage in the default option set.

func Register

func Register(i interface{})

Register registers the fields in i with the standard command-line option set. It panics for the same reasons that RegisterSet panics.

func RegisterAndParse

func RegisterAndParse(i interface{}) []string

RegisterAndParse and calls Register(i), getopt.Parse(), and returns getopt.Args().

func RegisterEncoding

func RegisterEncoding(name string, dec FlagsDecoder)

RegisterEncoding registers the decoder dec with the specified name. The encoder is is specified using the "encoding" tag (e.g., `encoding:"name"`).

func RegisterNew

func RegisterNew(name string, i interface{}) (interface{}, *getopt.Set)

RegisterNew creates a new getopt Set, duplicates i, calls RegisterSet, and then returns them. RegisterNew should be used when the options in i might be parsed multiple times requiring a new instance of i each time.

func RegisterSet

func RegisterSet(name string, i interface{}, set *getopt.Set) error

RegisterSet registers the fields in i, to the getopt Set set. RegisterSet returns an error if i is not a pointer to struct, has an invalid getopt tag, or contains a field of an unsupported option type. RegisterSet ignores non-exported fields or fields whose getopt tag is "-".

If a Flags field is encountered, name is the name used to identify the set when parsing options.

See the package documentation for a description of the structure to pass to RegisterSet.

func SetDisplayWidth added in v1.3.1

func SetDisplayWidth(w int)

SetDisplayWidth sets the width of the display when printing usage. It defaults to 80.

func SetHelpColumn added in v1.3.1

func SetHelpColumn(c int)

SetHelpColumn sets 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. It defaults to 20.

func SetParameters added in v1.3.1

func SetParameters(parameters string)

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

func SetProgram added in v1.3.1

func SetProgram(program string)

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

func SetUsage added in v1.3.1

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 SimpleDecoder

func SimpleDecoder(data []byte) (map[string]interface{}, error)

SimpleDecoder decodes data as a set of name=value pairs, one pair per line. Keys and values are separated by an equals sign (=), with optional white space on either side of the equal sign. Comments are introduced by the pound (#) character, unless prefaced by a backslash (\). \X is replaced with X. A backslash at the end of the line is ignored (no line concatination). If the value begins and ends with double quote ("), the double duotes are trimmed (but no futher processing is done). A non-backslashed # within quotes still introduces a comment.

Examples lines:

# this is a comment
name=value
name=a value
name = a value  # with a comment
name= "a value"
name = \# is the value # this is the comment
name = " a value with spaces "
set.name = value # set name in Options set "name"

func SubRegisterAndParse added in v1.2.0

func SubRegisterAndParse(i interface{}, args []string) ([]string, error)

SubRegisterAndParse is similar to RegisterAndParse except it is provided the arguments as args and on error the error is returned rather than written to standard error and the exiting the program. This is done by creating a new getopt set, registering i with that set, and then calling Getopt on the set with args.

SubRegisterAndParse is useful when you want to parse arguments other than os.Args (which is what RegisterAndParse does).

The first element of args is equivalent to a command name and is not parsed.

EXAMPLE:

func nameCommand(args []string) error {
	opts := &struct {
		Name string `getopt:"--name NAME the name to use"`
	}{
		Name: "none",
	}
	// If args does not include the subcommand name then prepend it
	args = append([]string{"name"}, args...)

	args, err := options.SubRegisterAndParse(opts, args)
	if err != nil {
		return err
	}
	fmt.Printf("The name is %s\n", opts.Name)
	fmt.Printf("The parameters are: %q\n", args)
}

func Usage added in v1.3.1

func Usage()

Usage calls the usage function in the default option set.

func Validate

func Validate(i interface{}) error

Validate validates i as a set of options or returns an error.

Use Validate to assure that a later call to one of the Register functions will not panic. Validate is typically called by an init function on structures that will be registered later.

Types

type Flags

type Flags struct {
	Sets          []Set
	IgnoreUnknown bool
	Decoder       FlagsDecoder
	// contains filtered or unexported fields
}

A Flags is an getopt.Value that reads initial command line flags from a file named by the flags value. The flags read from the file are effectively read prior to any other command line flag. If a flag is set both in a flags file and on the command line directly, the command line value is the value that is used.

It is an error if the specified file does not exist unless the pathname is prefixed with a ? (the ? is stripped), e.g., --flags=?my-flags.

The format of the flags file can be specified by either using the SetEncoding method or by using the "encoding" struct Flags field tag.

The default file encoding is provided by the SimpleDecoder function (registered as the encoding "simple"). Other file encodings can be specified by either using the SetEncoding or supplying the encoding tag in options structure (see below for more details).

Consider the file name my-flags:

name = bob
v = true
n = 42

Passing --flags=my-flags is the equivalent of prefacing the command line argumebts with "--name=bob -v -n=42". Below are are example command lines and the resulting value of name:

--flags my-flags                # name is bob
--flags my-flags --name fred    # name is fred
--name fred --flags my-flags    # name is fred

The Sets field specifies the options that the read flags modify. If the same flag appears in two sets, only the first set is modified. The default getopt.Set is a single element of either getopt.CommandLine or the getopt.Set passed to RegisterSet or returned by RegisterNew.

The encoding can be changed from SimpleDecoder, a.k.a. "simple" by either using the SetEncoding method or by specifying the registered encoding as a struct tag to the Flags field in an options structure, e.g.:

Flags options.Flags `getopt:"--flags specify flags file" encoding:"json"`

(Importing the package github.com/pborman/options/json registers the json encoding.)

Unless IgnoreUnknown is set, it is an error to pass in a JSON blob that references an unknown option.

func NewFlags

func NewFlags(name string) *Flags

NewFlags returns a new Flags registered on the standard CommandLine as a long named option.

Typical usage:

options.NewFlags("flags")

To ignore unknown flag names:

options.NewFlags("flags").IgnoreUnknown = true

func (*Flags) Rescan

func (f *Flags) Rescan(name string, set *getopt.Set) error

Rescan sets values in set from the values previously set in f.

func (*Flags) Set

func (f *Flags) Set(value string, opt getopt.Option) error

Set implements getopt.Value. Set can be called directly by passing a nil getopt.Option. Set is a no-op if value is the empty string. Set does simple environment variable expansion on value.

The expansion forms ${NAME} and ${NAME:-VALUE} are supported. In the latter case VALUE will be used if NAME is not found or set to the empty string. Use "${$" to represent a literal "${".

var myOptions struct {
	...
	Flags options.Flags `getopt:"--flags specify flags file"`
}{}
func init() {
	options.Register(&myOptions)
	options.Flags.Set("?${HOME}/.my.flags", nil)
}

or

options.NewFlags("flags").Set("?${HOME}/.my.flags", nil)

func (*Flags) SetEncoding

func (f *Flags) SetEncoding(decoder FlagsDecoder) *Flags

SetEncoding returns f after setting the decoding function to decoder. For example:

flags := options.NewFlags("flags").SetEncoding(json.Decoder)

func (*Flags) String

func (f *Flags) String() string

String implements getopt.Value.

type FlagsDecoder

type FlagsDecoder func([]byte) (map[string]interface{}, error)

A FlagsDecoder the data in bytes as a set of key value pairs. The values must be type assertable to a strconv.TextMarshaller, a fmt.Stringer, a string, a bool, or one of the non-complex numeric types (e.g., int).

type Help added in v1.1.0

type Help bool

A Help option causes PrintUsage to be called if the the option is set. Normally os.Exit(0) will be called when the option is seen. Setting the defaulted value to true will prevent os.Exit from being called.

Normal Usage

var myOptions = struct {
	Help options.Help `getopt:"--help display command usage"`
	...
}{}

func (*Help) Set added in v1.1.0

func (h *Help) Set(value string, opt getopt.Option) error

Set implements getopt.Value.

func (*Help) String added in v1.1.0

func (h *Help) String() string

String implements getopt.Value.

type Set

type Set struct {
	Name string
	*getopt.Set
}

A Set is a named getopt.Set.

Directories

Path Synopsis
Example usage of the options package.
Example usage of the options package.
Package flags is a simplified version github.com/pborman/options that works with the standard flag package and possibly other flag packages.
Package flags is a simplified version github.com/pborman/options that works with the standard flag package and possibly other flag packages.
Package json provides JSON flag decoding for the github.com/pborman/options packge.
Package json provides JSON flag decoding for the github.com/pborman/options packge.

Jump to

Keyboard shortcuts

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