params

package module
v0.0.0-...-225c817 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2024 License: BSD-3-Clause Imports: 15 Imported by: 10

README

go-params

POSIX compliant argument parser for Go!

Usage Documentation: https://pkg.go.dev/github.com/pschou/go-params

Introduction

What would the module look like if GoLang provided a full-featured flag/parameter parsing package? What if it offers flexibility, simplicity while also maintaining the familiar look-and-feel other open-source packages provide? As programmers, we must provide that comfort level to our users, match the look-and-feel used by other commonly used Linux packages. This a community effort as by matching other common usage packages, we ultimately lower our users' learning curve and blend in with the rest of the technologies available. Welcome to the solution for GoLang that does just this, go-param.

As there are many examples of programs that handle parameters differently, let us choose two commonly used packages of which to model and build a generic module to mimic. The two selected are ldapsearch and curl. The first has been around for over two decades, and the second is fairly new. Both are well used and understood by the Linux community as a whole. The goal here is to lower the bar of learning and make the flags operate as close as other linux tools operate to ease user's learning curve. The goal is finished! With this param package, GoLang can output the same help and parse the same parameter inputs.

Src: https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html

POSIX recommends these conventions for command line arguments. getopt (see Getopt) and argp_parse (see Argp) make it easy to implement them.

  • Arguments are options if they begin with a hyphen delimiter (‘-’).
  • Multiple options may follow a hyphen delimiter in a single token if the options do not take arguments. Thus, ‘-abc’ is equivalent to ‘-a -b -c’.
  • Option names are single alphanumeric characters (as for isalnum; see Classification of Characters, https://www.gnu.org/software/libc/manual/html_node/Classification-of-Characters.html).
  • Certain options require an argument. For example, the ‘-o’ command of the ld command requires an argument—an output file name.
  • An option and its argument may or may not appear as separate tokens. (In other words, the whitespace separating them is optional.) Thus, ‘-o foo’ and ‘-ofoo’ are equivalent.
  • Options typically precede other non-option arguments.

The implementations of getopt and argp_parse in the GNU C Library normally make it appear as if all the option arguments were specified before all the non-option arguments for the purposes of parsing, even if the user of your program intermixed option and non-option arguments. They do this by reordering the elements of the argv array. This behavior is nonstandard; if you want to suppress it, define the _POSIX_OPTION_ORDER environment variable. See Standard Environment, https://www.gnu.org/software/libc/manual/html_node/Standard-Environment.html.

  • The argument ‘--’ terminates all options; any following arguments are treated as non-option arguments, even if they begin with a hyphen.
  • A token consisting of a single hyphen character is interpreted as an ordinary non-option argument. By convention, it is used to specify input from or output to the standard input and output streams.
  • Options may be supplied in any order, or appear multiple times. The interpretation is left up to the particular application program. GNU adds long options to these conventions. Long options consist of ‘--’ followed by a name made of alphanumeric characters and dashes. Option names are typically one to three words long, with hyphens to separate words. Users can abbreviate the option names as long as the abbreviations are unique.

To specify an argument for a long option, write ‘--name=value’. This syntax enables a long option to accept an argument that is itself optional.

Eventually, GNU systems will provide completion for long option names in the shell.

About

This package is a fork of the Go standard library flag and gnuflag. As this package is a rewrite to enable additional functionality and usability, one will find it is significantly different from the source. The driving motivation was to provide a solution to the missing toolbox, an excellent flag parser that is simple and is very similar to other gnu programs. Being very similar to other gnu programs lowers the learning curve for users to use flags in go-built-tools. Modeled gnu programs used in the creation of this tool are the openldap and curl help flags.

Goals

This re-write includes some notable differences:

  • Support for both --longflag and -l single-character flag syntax.
  • Addition of "present" flag with no parameters needed.
  • Boolean flags always require a boolean input, true, t, 1, false, f, or 0 with either space ' ' or '=' separator.
  • Flag stacking -abc is the same as -a -b -c for present flags.
  • Unicode support for inputs and printing with alignment.
  • Multiple flags for a single target value -i, --include.
  • Custom exemplars demonstrating the needed input type
    --time DURATION   How long to wait for a reply.  (Default: 5s)
    
  • Custom definable functions to handle the parsing of parameters.
  • Ability to allow more than one input per parameter --port-range 1080 1090, by using the custom var and the needed count.
  • Collect a dynamic number of strings per flag into a slice, like multiple packages afer an --install flag.
    ctl --install pkgA pkgB pkgC --remove pkgX
    
  • Allow interspersed parameters. If set -a data -b is the same as -a -b data.

Example

Here is what it looks like when implemented:

import (
  ...
  "github.com/pschou/go-params"
  ...
)

var version = "0.0"
func main() {
  // Set a custom header,
  params.Usage = func() {
    fmt.Fprintf(os.Stderr, "My Sample, Version: %s\n\n" +
      "Usage: %s [options...]\n\n", version, os.Args[0])
    params.PrintDefaults()
  }

  // An example boolean flag, used like this: -tls true -tls false, or optionally: -tls=true -tls=false
  var tls_enabled = params.Bool("tls", true, "Enable listener TLS", "BOOL")

  // An example of a present flag, returns true if it was seen
  var verbose = params.Pres("debug", "Verbose output")

  // Start of a grouping set
  params.GroupingSet("Listener")
  var listen = params.String("listen", ":7443", "Listen address for forwarder", "HOST:PORT")
  var verify_server = params.Bool("verify-server", true, "Verify server, do certificate checks", "BOOL")
  var secure_server = params.Bool("secure-server", true, "Enforce minimum of TLS 1.2 on server side", "BOOL")

  // Start of another grouping set
  params.GroupingSet("Target")
  var target = params.String("target", "127.0.0.1:443", "Sending address for forwarder", "HOST:PORT")
  var verify_client = params.Bool("verify-client", true, "Verify client, do certificate checks", "BOOL")
  var secure_client = params.Bool("secure-client", true, "Enforce minimum of TLS 1.2 on client side", "BOOL")
  // To enable both -H and --host as options, all one needs to do is add a space "host" -> "host H"
  var tls_host = params.String("host", "", "Hostname to verify outgoing connection with", "FQDN")

  // Start of our last grouping set
  params.GroupingSet("Certificate")
  var cert_file = params.String("cert", "/etc/pki/server.pem", "File to load with CERT - automatically reloaded every minute\n", "FILE")
  var key_file = params.String("key", "/etc/pki/server.pem", "File to load with KEY - automatically reloaded every minute\n", "FILE")
  var root_file = params.String("ca", "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", "File to load with ROOT CAs - reloaded every minute by adding any new entries\n", "FILE")

  // Indicate that we want all the flags indented for ease of reading
  params.CommandLine.Indent = 2

  // Let us parse everything!
  params.Parse()

  // ... Variables are ready for use now!
}

This example was taken directly from the SSL-Forwarder program (below) so one may compare the output and see what it looks like in the finished product.

Real World Examples

Here are some examples which demonstrate the likeness of this parameter parsing tool:

SSL-Forwarder -- https://github.com/pschou/ssl-forwarder

$ ./ssl-forwarder -h
...
Usage: ./ssl-forwarder [options...]

Options:
  --debug                 Verbose output
  --tls BOOL              Enable listener TLS  (Default: true)
Listener options:
  --listen HOST:PORT      Listen address for forwarder  (Default: ":7443")
  --secure-server BOOL    Enforce minimum of TLS 1.2 on server side  (Default: true)
  --verify-server BOOL    Verify server, do certificate checks  (Default: true)
Target options:
  --host FQDN             Hostname to verify outgoing connection with  (Default: "")
  --secure-client BOOL    Enforce minimum of TLS 1.2 on client side  (Default: true)
  --target HOST:PORT      Sending address for forwarder  (Default: "127.0.0.1:443")
  --verify-client BOOL    Verify client, do certificate checks  (Default: true)
Certificate options:
  --ca FILE               File to load with ROOT CAs - reloaded every minute by adding any new entries
                            (Default: "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem")
  --cert FILE             File to load with CERT - automatically reloaded every minute
                            (Default: "/etc/pki/server.pem")
  --key FILE              File to load with KEY - automatically reloaded every minute
                            (Default: "/etc/pki/server.pem")

Prom-collector -- https://github.com/pschou/prom-collector

$ ./prom-collector -h
Prometheus Collector, written by Paul Schou (github.com/pschou/prom-collector) in December 2020
Prsonal use only, provided AS-IS -- not responsible for loss.
Usage implies agreement.

Usage: ./prom-collector [options...]

Options:
--ca FILE             File to load with ROOT CAs - reloaded every minute by adding any new entries
                        (Default: "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem")
--cert FILE           File to load with CERT - automatically reloaded every minute
                        (Default: "/etc/pki/server.pem")
--debug               Verbose output
--json JSON_FILE      Path into which to put all the prometheus endpoints for polling
                        (Default: "/dev/shm/metrics.json")
--key FILE            File to load with KEY - automatically reloaded every minute
                        (Default: "/etc/pki/server.pem")
--listen HOST:PORT    Listen address for metrics  (Default: ":9550")
--path DIRECTORY      Path into which to put the prometheus data  (Default: "/dev/shm/collector")
--prefix URL_PREFIX   Used for all incoming requests, useful for a reverse proxy endpoint
                        (Default: "/collector")
--secure-server BOOL  Enforce TLS 1.2+ on server side  (Default: true)
--tls BOOL            Enable listener TLS  (Default: false)
--verify-server BOOL  Verify or disable server certificate check  (Default: true)

jqURL -- https://github.com/pschou/jqURL

$ jqurl -h
jqURL - URL and JSON parser tool, Written by Paul Schou (github.com/pschou/jqURL)
Usage:
  ./jqurl [options] "JSON Parser" URLs

Options:
  -C, --cache          Use local cache to speed up static queries
      --cachedir DIR   Path for cache  (Default="/dev/shm")
      --debug          Debug / verbose output
      --flush          Force redownload, when using cache
  -i, --include        Include header in output
      --max-age DURATION  Max age for cache  (Default=4h0m0s)
  -o, --output FILE    Write output to <file> instead of stdout  (Default="")
  -P, --pretty         Pretty print JSON with indents
  -r, --raw-output     Raw output, no quotes for strings
Request options:
  -d, --data STRING    Data to use in POST (use @filename to read from file)  (Default="")
  -H, --header 'HEADER: VALUE'  Custom header to pass to server
                         (Default="content-type: application/json")
  -k, --insecure       Ignore certificate validation checks
  -L, --location       Follow redirects
  -m, --max-time DURATION  Timeout per request  (Default=15s)
      --max-tries TRIES  Maximum number of tries  (Default=30)
  -X, --request METHOD  Method to use for HTTP request (ie: POST/GET)  (Default="GET")
      --retry-delay DURATION  Delay between retries  (Default=7s)
Certificate options:
      --cacert FILE    Use certificate authorities, PEM encoded  (Default="")
  -E, --cert FILE      Use client cert in request, PEM encoded  (Default="")
      --key FILE       Key file for client cert, PEM encoded  (Default="")

Last, but not least, a test example using some unicode:

-A          for bootstrapping, allow 'any' type  (Default: false)
    --Alongflagname  disable bounds checking  (Default: false)
-C          a boolean defaulting to true  (Default: true)
-D          set relative path for local imports  (Default: "")
-E          issue 23543  (Default: "0")
-F STR      issue 23543  (Default: "0")
-I          a non-zero number  (Default: 2.7)
-K          a float that defaults to zero  (Default: 0)
-M          a multiline
            help
            string  (Default: "")
-N          a non-zero int  (Default: 27)
-O          a flag
            multiline help string  (Default: true)
-Z          an int that defaults to zero  (Default: 0)
-G, --grind STR  issue 23543  (Default: "0")
    --maxT  set timeout for dial  (Default: 0s)
-世         a present flag
    --世界  unicode string  (Default: "hello")

Documentation

Overview

Package param implements command-line parameter parsing in the GNU style.
It is different and adds capabilities beyond the standard flag package,
the only difference being the extra argument to Parse.

Command line param syntax:
	-f		// single letter flag
	-fg		// two single letter flags together
	--flag	// multiple letter flag
	--flag x  // non-present flags only
	-f x		// non-present flags only
	-fx		// if f is a non-present flag, x is its argument.

The last three forms are not permitted for boolean flags because the
meaning of the command
	cmd -f *
will change if there is a file called 0, false, etc.  There is currently
no way to turn off a boolean flag.

Flag parsing stops after the terminator "--", or just before the first
non-flag argument ("-" is a non-flag argument) if the interspersed
argument to Parse is false.

TODOs:

Example
// These examples demonstrate more intricate uses of the params package.
package main

import (
	"errors"
	"fmt"
	"github.com/pschou/go-params"
	"strings"
	"time"
)

// Example 1: A single string params called "species" with default value "gopher".
var species = params.String("species", "gopher", "the species we are studying", "TEXT")

// Example 2: Two paramss sharing a variable, so we can have a shorthand.
// The order of initialization is undefined, so make sure both use the
// same default value. They must be set up with an init function.
var gopherType string

func init() {
	const (
		defaultGopher = "pocket"
		usage         = "the variety of gopher"
	)
	params.StringVar(&gopherType, "gopher_type", defaultGopher, usage, "TYPE")
	params.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)", "")
}

// Example 3: A user-defined params type, a slice of durations.
type interval []time.Duration

// String is the method to format the params's value, part of the params.Value interface.
// The String method's output will be used in diagnostics.
func (i *interval) String() string {
	return fmt.Sprint(*i)
}

// Set is the method to set the params value, part of the params.Value interface.
// Set's argument is a string to be parsed to set the params.
// It's a comma-separated list, so we split it.
func (i *interval) Set(value []string) error {
	// If we wanted to allow the params to be set multiple times,
	// accumulating values, we would delete this if statement.
	// That would permit usages such as
	//	-deltaT 10s -deltaT 15s
	// and other combinations.
	if len(*i) > 0 {
		return errors.New("interval params already set")
	}
	for _, dt := range strings.Split(value[0], ",") {
		duration, err := time.ParseDuration(dt)
		if err != nil {
			return err
		}
		*i = append(*i, duration)
	}
	return nil
}

// Define a params to accumulate durations. Because it has a special type,
// we need to use the Var function and therefore create the params during
// init.

var intervalFlag interval

func init() {
	// Tie the command-line params to the intervalFlag variable and
	// set a usage message.
	params.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events", "VALS", 1)
}

func main() {
	// All the interesting pieces are with the variables declared above, but
	// to enable the params package to see the paramss defined there, one must
	// execute, typically at the start of main (not init!):
	//	params.Parse()
	// We don't run it here because this is not a main function and
	// the testing suite has already parsed the paramss.
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var CommandLine = NewFlagSet("", ExitOnError)

CommandLine is the default set of command-line flags, parsed from os.Args. The top-level functions such as BoolVar, Arg, and so on are wrappers for the methods of CommandLine.

View Source
var Default = "Default: "

Word for default

View Source
var ErrHelp = errors.New("help requested")

ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.

View Source
var Usage = func() {
	if len(CommandLine.Title) > 0 {
		fmt.Fprintf(CommandLine.Output(), "%s\n\n", CommandLine.Title)
	}
	post := ""
	if len(CommandLine.Params) > 0 {
		post = "[options...] [args...]"
	} else if len(CommandLine.formal) > 1 {
		post = "[options...]"
	} else {
		post = "[option]"
	}
	fmt.Fprintf(CommandLine.Output(), "Usage: %s %s\n", path.Base(os.Args[0]), post)
	PrintDefaults()
}

Usage prints to standard error a usage message documenting all defined command-line flags. The function is a variable that may be changed to point to a custom function.

Functions

func Arg

func Arg(i int) string

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

func Args

func Args() []string

Args returns the non-flag command-line arguments.

func Bool

func Bool(name string, value bool, usage string, typeExp string) *bool

Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.

func BoolVar

func BoolVar(p *bool, name string, value bool, usage string, typeExp string)

BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.

func Duration

func Duration(name string, value time.Duration, usage string, typeExp string) *time.Duration

Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag.

func DurationVar

func DurationVar(p *time.Duration, name string, value time.Duration, usage string, typeExp string)

DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag.

func FlagFunc

func FlagFunc(name, usage string, typeExp string, argsNeeded int, fn func([]string) error)

FlagFunc defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

func Float64

func Float64(name string, value float64, usage string, typeExp string) *float64

Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.

func Float64Var

func Float64Var(p *float64, name string, value float64, usage string, typeExp string)

Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.

func GroupingSet

func GroupingSet(grouping string)

GroupingSet creates a grouping set for new flags added. This is helpful if there are many flags and they can be organized in smaller groupings.

func Int

func Int(name string, value int, usage string, typeExp string) *int

Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.

func Int64

func Int64(name string, value int64, usage string, typeExp string) *int64

Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.

func Int64Var

func Int64Var(p *int64, name string, value int64, usage string, typeExp string)

Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.

func IntVar

func IntVar(p *int, name string, value int, usage string, typeExp string)

IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.

func NArg

func NArg() int

NArg is the number of arguments remaining after flags have been processed.

func NFlag

func NFlag() int

NFlag returns the number of command-line flags that have been set.

func Parse

func Parse()

Parse parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program. If AllowIntersperse is set, arguments and flags can be interspersed, that is flags can follow positional arguments.

func Parsed

func Parsed() bool

Parsed returns true if the command-line flags have been parsed.

func Pres

func Pres(name string, usage string) *bool

Pres defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.

func PresVar

func PresVar(p *bool, name string, usage string)

PresVar defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.

func PrintDefaults

func PrintDefaults()

PrintDefaults prints to standard error the default values of all defined command-line flags.

func Set

func Set(name string, value []string) error

Set sets the value of the named command-line flag.

func SetAllowIntersperse

func SetAllowIntersperse(allowIntersperse bool)

SetAllowIntersperse tells the parser if flags can be interspersed with other arguments. If AllowIntersperse is set to true, arguments and flags can be interspersed, that is flags can follow positional arguments.

Example of true:

prog -flag1 input1 input2 -flag2

Example of false: (default)

prog -flag1 -flag2 input1 input2

func String

func String(name string, value string, usage string, typeExp string) *string

String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

func StringSlice

func StringSlice(name string, usage string, typeExp string, perFlag int) *[]string

StringSlice defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

Example
fs := params.NewFlagSet("ExampleFunc", params.ContinueOnError)
fs.SetOutput(os.Stdout)
var install, remove []string

fs.StringSliceVar(&install, "i install", "List of packages to install", "PACKAGES", -1)
fs.StringSliceVar(&remove, "r remove", "List of packages to install", "PACKAGES", -1)
fs.Parse([]string{"--install", "a", "b", "-r", "c", "-i", "d"})

fmt.Printf("{install: %#v, remove: %#v}\n\n", install, remove)
fs.PrintDefaults()

// {install: []string{"a", "b", "d"}, remove: []string{"c"}}
//
// Options:
//   -i, --install PACKAGES  List of packages to install
//   -r, --remove PACKAGES  List of packages to install
Output:

func StringSliceVar

func StringSliceVar(p *([]string), name string, usage string, typeExp string, perFlag int)

StringSliceVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

func StringVar

func StringVar(p *string, name string, value string, usage string, typeExp string)

StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

func Uint

func Uint(name string, value uint, usage string, typeExp string) *uint

Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.

func Uint64

func Uint64(name string, value uint64, usage string, typeExp string) *uint64

Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.

func Uint64Var

func Uint64Var(p *uint64, name string, value uint64, usage string, typeExp string)

Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.

func UintVar

func UintVar(p *uint, name string, value uint, usage string, typeExp string)

UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.

func Var

func Var(value Value, name string, usage string, typeExp string, argsNeeded int)

Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.

func Visit

func Visit(fn func(*Flag))

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

func VisitAll

func VisitAll(fn func(*Flag))

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

Types

type ErrorHandling

type ErrorHandling int

ErrorHandling defines how to handle flag parsing errors.

const (
	ContinueOnError ErrorHandling = iota
	ExitOnError
	PanicOnError
)

type Flag

type Flag struct {
	Name         []string                      // name as it appears on command line
	Usage        string                        // help message
	Value        Value                         // value as set
	DefValue     string                        // default value
	TypeExpected string                        // helpful hint on what is expected
	ArgsNeeded   int                           // arg count wanted
	Grouping     string                        // organize flags into groups
	Options      func(string, string) []string // function to return possible outcomes for bash completion
}

A Flag represents the state of a flag.

func Lookup

func Lookup(name string) *Flag

Lookup returns the Flag structure of the named command-line flag, returning nil if none exists.

type FlagSet

type FlagSet struct {
	// Usage is the function called when an error occurs while parsing flags.
	// The field is a function (not a method) that may be changed to point to
	// a custom error handler.
	Usage func()

	Title string

	Params []Param // argument parsers for after flags

	// SetUsageIndent tells the DefaultPrinter how many spaces to add to before
	// printing the usage for each flag.  By default this is 0 and determined by
	// the maximum comma seperated name length.
	Indent      int // beginning of line space
	UsageIndent int // usage column position

	UsageSpace int // minimum number of spaces required before usage
	TypeSpace  int // minimum number of spaces required before input type string

	ShowGroupings   bool                     // Show the flags in groups
	GroupingHeaders func(string, int) string // function used to generate headers, like "Options:"

	ShowDefaultVal bool // Display the (Default: "") example

	// FlagKnownAs allows different projects to customise what their flags are
	// known as, e.g. 'flag', 'option', 'item'. All error/log messages
	// will use that name when referring to an individual items/flags in this set.
	// For example, if this value is 'option', the default message 'value for param'
	// will become 'value for option'.
	// Default value is 'flag'.
	FlagKnownAs string
	// contains filtered or unexported fields
}

A FlagSet represents a set of defined flags.

func NewFlagSet

func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

NewFlagSet returns a new, empty parameter set with the specified name and error handling property.

func NewFlagSetWithFlagKnownAs

func NewFlagSetWithFlagKnownAs(name string, errorHandling ErrorHandling, aka string) *FlagSet

NewFlagSetWithFlagKnownAs returns a new, empty parameter set with the specified name and error handling property. All error messages and other references to the individual params will use aka, for e.g. if aka = 'option', the message will be 'value for option' not 'value for param'.

func (*FlagSet) Arg

func (f *FlagSet) Arg(i int) string

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

func (*FlagSet) Args

func (f *FlagSet) Args() []string

Args returns the non-flag arguments.

func (*FlagSet) Bool

func (f *FlagSet) Bool(name string, value bool, usage string, typeExp string) *bool

Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.

func (*FlagSet) BoolVar

func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string, typeExp string)

BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.

func (*FlagSet) Duration

func (f *FlagSet) Duration(name string, value time.Duration, usage string, typeExp string) *time.Duration

Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag.

func (*FlagSet) DurationVar

func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string, typeExp string)

DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag.

func (*FlagSet) ErrorHandling

func (f *FlagSet) ErrorHandling() ErrorHandling

ErrorHandling returns the error handling behavior of the flag set.

func (*FlagSet) FlagFunc

func (f *FlagSet) FlagFunc(name, usage string, typeExp string, argsNeeded int, fn func([]string) error)

FlagFunc defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

func (*FlagSet) Float64

func (f *FlagSet) Float64(name string, value float64, usage string, typeExp string) *float64

Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.

func (*FlagSet) Float64Var

func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string, typeExp string)

Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.

func (*FlagSet) GroupingSet

func (f *FlagSet) GroupingSet(grouping string)

GroupingSet creates a grouping set for new flags added. This is helpful if there are many flags and they can be organized in smaller groupings.

func (*FlagSet) Init

func (f *FlagSet) Init(name string, errorHandling ErrorHandling)

Init sets the name and error handling property for a parameter set. By default, the zero FlagSet uses an empty name and the ContinueOnError error handling policy.

func (*FlagSet) Int

func (f *FlagSet) Int(name string, value int, usage string, typeExp string) *int

Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.

func (*FlagSet) Int64

func (f *FlagSet) Int64(name string, value int64, usage string, typeExp string) *int64

Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.

func (*FlagSet) Int64Var

func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string, typeExp string)

Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.

func (*FlagSet) IntVar

func (f *FlagSet) IntVar(p *int, name string, value int, usage string, typeExp string)

IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.

func (*FlagSet) Lookup

func (f *FlagSet) Lookup(name string) *Flag

Lookup returns the Flag structure of the named flag, returning nil if none exists.

func (*FlagSet) NArg

func (f *FlagSet) NArg() int

NArg is the number of arguments remaining after flags have been processed.

func (*FlagSet) NFlag

func (f *FlagSet) NFlag() int

NFlag returns the number of flags that have been set.

func (*FlagSet) Name

func (f *FlagSet) Name() string

Name returns the name of the flag set.

func (*FlagSet) Output

func (f *FlagSet) Output() io.Writer

Output returns the destination for usage and error messages. os.Stderr is returned if output was not set or was set to nil.

func (*FlagSet) Parse

func (f *FlagSet) Parse(arguments []string) error

Parse parses flag definitions from the argument list, which should not include the command name. Must be called after all flags in the FlagSet are defined and before flags are accessed by the program. The return value will be ErrHelp if --help or -h was set but not defined. If AllowIntersperse is set, arguments and flags can be interspersed, that is flags can follow positional arguments.

func (*FlagSet) Parsed

func (f *FlagSet) Parsed() bool

Parsed reports whether f.Parse has been called.

func (*FlagSet) Pres

func (f *FlagSet) Pres(name string, usage string) *bool

PresVar defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.

func (*FlagSet) PresVar

func (f *FlagSet) PresVar(p *bool, name string, usage string)

PresVar defines a present flag with specified name and usage string. The return value is the address of a bool variable that stores true if seen.

func (*FlagSet) PrintDefaults

func (f *FlagSet) PrintDefaults()

PrintDefaults prints, to standard error unless configured otherwise, the default values of all defined flags in the set. If there is more than one name for a given flag, the usage information and default value from the shortest will be printed (or the least alphabetically if there are several equally short flag names).

func (*FlagSet) Set

func (f *FlagSet) Set(name string, value []string) error

Set sets the value of the named flag.

func (*FlagSet) SetAllowIntersperse

func (f *FlagSet) SetAllowIntersperse(allowIntersperse bool)

SetAllowIntersperse tells the parser if flags can be interspersed with other arguments. If AllowIntersperse is set to true, arguments and flags can be interspersed, that is flags can follow positional arguments.

Example of true:

prog -flag1 input1 input2 -flag2

Example of false: (default)

prog -flag1 -flag2 input1 input2

func (*FlagSet) SetOutput

func (f *FlagSet) SetOutput(output io.Writer)

SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used.

func (*FlagSet) String

func (f *FlagSet) String(name string, value string, usage string, typeExp string) *string

String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

func (*FlagSet) StringSlice

func (f *FlagSet) StringSlice(name string, usage string, typeExp string, perFlag int) *[]string

StringSlice defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

func (*FlagSet) StringSliceVar

func (f *FlagSet) StringSliceVar(p *([]string), name string, usage string, typeExp string, perFlag int)

StringSliceVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

func (*FlagSet) StringVar

func (f *FlagSet) StringVar(p *string, name string, value string, usage string, typeExp string)

StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

func (*FlagSet) Uint

func (f *FlagSet) Uint(name string, value uint, usage string, typeExp string) *uint

Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.

func (*FlagSet) Uint64

func (f *FlagSet) Uint64(name string, value uint64, usage string, typeExp string) *uint64

Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.

func (*FlagSet) Uint64Var

func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string, typeExp string)

Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.

func (*FlagSet) UintVar

func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string, typeExp string)

UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.

func (*FlagSet) Var

func (f *FlagSet) Var(value Value, flagStr string, usage string, typeExp string, args int)

Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.

func (*FlagSet) Visit

func (f *FlagSet) Visit(fn func(*Flag))

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

func (*FlagSet) VisitAll

func (f *FlagSet) VisitAll(fn func(*Flag))

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

type Getter

type Getter interface {
	Value
	Get() interface{}
}

Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

type Param

type Param struct {
	Usage        string                                                  // help message
	Value        Value                                                   // value as set
	DefValue     string                                                  // default value
	TypeExpected string                                                  // helpful hint on what is expected
	Options      []string                                                // Available options for tab-fill
	OptionsFunc  func(flagsSeen []Flag, argsSeen []string) []string      // Get options for bash completion
	Test         func(flagsSeen []Flag, argsSeen []string) (bool, error) // Options
}

type Value

type Value interface {
	String() string
	Set([]string) error
}

Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)

Example
package main

import (
	"fmt"
	"github.com/pschou/go-params"
	"net/url"
)

type URLValue struct {
	URL *url.URL
}

func (v URLValue) String() string {
	if v.URL != nil {
		return v.URL.String()
	}
	return ""
}

func (v URLValue) Set(s []string) error {
	if u, err := url.Parse(s[0]); err != nil {
		return err
	} else {
		*v.URL = *u
	}
	return nil
}

var u = &url.URL{}

func main() {
	fs := params.NewFlagSet("ExampleValue", params.ExitOnError)
	fs.Var(&URLValue{u}, "url", "The URL to parse", "ADDRESS", 1)

	fs.Parse([]string{"--url", "https://golang.org/pkg/flag/"})
	fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)

}
Output:

{scheme: "https", host: "golang.org", path: "/pkg/flag/"}

Jump to

Keyboard shortcuts

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