flag

package module
v0.0.0-...-a7f6954 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License: Apache-2.0 Imports: 12 Imported by: 15

README

简介

flag库是标准库的增强版本,让你的命令行程序飞起来

Build Status

演示

flag

功能

兼容go标准库

package main

import (
    "fmt"
    "github.com/guonaihong/flag"
)

func main() {
    op := flag.String("dir", "", "open dir")
    flag.Parse()
    fmt.Printf("op = %s\n", *op)
}
// 运行
// go run main.go -dir test.file
// 输出
// op = test.file

数组类型选项

很方便写出curl -H选项效果

package main

import (
    "fmt"
    "github.com/guonaihong/flag"
)

func main() {
    h := flag.StringSlice("H, header", []string{}, "http header")
    flag.Parse()
    fmt.Printf("%#v\n", *h)
}

// 运行
// go run main.go -H "appkey:123" -H "User-Agent: main" --header "Accept: */*"
// 输出
// []string{"appkey:123", "User-Agent: main", "Accept: */*"}

多选项支持

package main

import (
	"fmt"
	"github.com/guonaihong/flag"
)

func main() {
	long := flag.String("l, long", "", "short long option")
	flag.Parse()
	fmt.Printf("long = %s\n", *long)
}

// 运行
// go run main.go -l hello
// go run main.go -long hello
// 输出
// long = hello

matchvar

详情 #9 很多时候使用bool选项,都是命令行传递bool选项 代码里面设置一个默认值,如下。

var openNull bool
delimiter := byte('\n')
command.Opt("0, null", "end each output line with NUL, not newline").
                Flags(flag.Posix).
                Var(&openNull)
if openNull {
    delimiter = byte(0)
}

现在可以使用MatchVar函数简化类似代码,如果命令函数传递-0或者-null,delimiter的值为'\n'

package main

import (
        "fmt"
        "github.com/guonaihong/flag"
)

func main() {

        delimiter := byte(0)

        flag.Opt("0, null", "end each output line with NUL, not newline").
                Flags(flag.Posix).
                MatchVar(&delimiter, byte('\n'))
        flag.Parse()

        fmt.Printf("%d\n", delimiter)
}

// 运行
// go run main.go -0
// 输出
// 10

posix风格

  • 命令组合
package main

import (
    "fmt"
    "github.com/guonaihong/flag"
)

func main() {
    showEnds := flag.Opt("E, show-end", "display $ at end of each line").
        Flags(flag.PosixShort).NewBool(false)

    showTabs := flag.Opt("T, show-tabs", "display TAB characters as ^I").
        Flags(flag.PosixShort).NewBool(false)

    flag.Parse()
    fmt.Printf("showEnds:%t, showTabs:%t\n", *showEnds, *showTabs)
}

// 运行
// go run main.go -TE
// 输出
// showEnds:true, showTabs:true
  • 贪婪模式
package main

import (
	"fmt"
	"github.com/guonaihong/flag"
)

func main() {
	var heads []string

	flag.Opt("H, header", "Pass custom header LINE to server (H)").
		Flags(flag.GreedyMode).Var(&heads)

	flag.Parse()
	fmt.Printf("%#v\n", heads)
}

// 运行
// go run main.go -H appkey:test  hello:world love:you
// 输出
// []string{"appkey:test", "hello:world", "love:you"}
  • -vvv 或者-v -v -v

package main

import (
        "fmt"
        "github.com/guonaihong/flag"
)

func main() {
        var bs []bool

        flag.Opt("v", "test bool slice").Flags(flag.PosixShort).Var(&bs)

        flag.Parse()

        switch len(bs) {
        case 0:
                fmt.Printf("No verbose info\n")
        case 1:
                fmt.Printf("Some verbose info\n")
        case 2:
                fmt.Printf("Tons of verbose info\n")
        default:
                fmt.Printf("别闹了\n")
        }

}

// 运行
// go run main.go -v
// 输出
// Some verbose info

// 运行
// go run main.go -vv
// 输出
// Tons of verbose info

// 运行
// go run main.go -vvv
// 输出
// 别闹了

子母命令

如果要实现一个主命令包含3个子命令(http, websocket, tcp),其中http子命令又包含5个命令行选项,可以使用如下用法

package main

import (
	"fmt"
	"github.com/guonaihong/flag"
	"os"
)

type httpOption struct {
	Header     []string
	Forms      []string
	FormString string
	Url        string
	Data       string
}

type wsOption struct {
	Ac int
	An int
}

type streamOption struct {
}

func main() {
	parent := flag.NewParentCommand(os.Args[0])

	parent.SubCommand("http", "Use the http subcommand", func() {
		argv0 := os.Args[0]
		argv := parent.Args()

		command := flag.NewFlagSet(argv0, flag.ExitOnError)

		ho := httpOption{}

		command.Opt("H, header", "Pass custom header LINE to server (H)").Var(&ho.Header)
		command.Opt("F, form", "Specify HTTP multipart POST data (H)").Var(&ho.Forms)
		command.Opt("form-string", "Specify HTTP multipart POST data (H)").Var(&ho.Forms)
		command.Opt("url", "Specify a URL to fetch").Var(&ho.Url)
		command.Opt("d, data", "HTTP POST data").Var(&ho.Data)

		command.Parse(argv)
	})

	parent.SubCommand("ws, websocket", "Use the websocket subcommand", func() {
		argv := parent.Args()
		command := flag.NewFlagSet(os.Args[0], flag.ExitOnError)

		wo := wsOption{}

		command.Opt("an", "Number of requests to perform").DefaultVar(&wo.An, 1)
		command.Opt("ac", "Number of multiple requests to make").DefaultVar(&wo.Ac, 1)

		command.Parse(argv)

		fmt.Printf("option = %#v\n", wo)
	})

	parent.SubCommand("tcp, udp", "Use the tcp or udp subcommand", func() {
		//conn.Main(os.Args[0], parent.Args())
	})

	parent.Parse(os.Args[1:])
}

// 运行帮助信息
// go run main.go -h
// 输出
// Usage of /tmp/go-build387723503/b001/exe/main:
//  http             Use the http subcommand
//  tcp, udp         Use the tcp or udp subcommand
//  ws, websocket    Use the websocket subcommand

// 运行websocket子命令帮助信息
// go run 
// Usage of /tmp/go-build229109289/b001/exe/main:
//  -ac int
//    	Number of multiple requests to make
//  -an int
//    	Number of requests to perform

// 运行websocket子命令
// go run main.go websocket -ac 2 -an 2
// 输出
// option = main.wsOption{Ac:2, An:2}

泛型接口函数

package main

import (
	"fmt"
	"github.com/guonaihong/flag"
	_ "os"
)

type TestOption struct {
	Int     int
	Int64   int64
	Strings []string
	Int64s  []int64

	Int2 int
}

func main() {
	option := TestOption{}

    // DefaultVar是带默认值的泛型函数
    // Var是不带默认值的泛型函数
	flag.Opt("i, int", "test int").DefaultVar(&option.Int, 0)
	flag.Opt("i64, int64", "test int64").DefaultVar(&option.Int64, int64(0))
	flag.Opt("s, strings", "test []string").DefaultVar(&option.Strings, []string{})
	flag.Opt("i64s, int64s", "test []int64").DefaultVar(&option.Int64s, []int64{})
	flag.Opt("i2", "test int2").Var(&option.Int2)
	flag.Parse()

	fmt.Printf("%#v\n", option)
}

// 运行
// go run main.go -i 3 -i64 64 -i64s 64 -i64s 1 -i64s 2 -i64s 3 -s a -s b -s c
// 输出
// main.TestOption{Int:3, Int64:64, Strings:[]string{"a", "b", "c"}, Int64s:[]int64{64, 1, 2, 3}, Int2:0}

绑定结构体

package main

import (
	"fmt"
	"github.com/guonaihong/flag"
	_ "os"
)

type TestOption struct {
	Int     int      `opt:"i, int" usage:"test int"`
	Int64   int64    `opt:"i64, int64" usage:"test int64"`
	Strings []string `opt:"s, strings" usage:"test []string"`
	Int64s  []int64  `opt:"i64s, int64s" usage:"test []int64"`

	Int2 int `opt:"i2" usage:"test int2"`
}

func main() {
	option := TestOption{}

	flag.ParseStruct(&option)

	fmt.Printf("%#v\n", option)
}

// 运行
// go run main.go -i 3 -i64 64 -i64s 64 -i64s 1 -i64s 2 -i64s 3 -s a -s b -s c
// 输出
// main.TestOption{Int:3, Int64:64, Strings:[]string{"a", "b", "c"}, Int64s:[]int64{64, 1, 2, 3}, Int2:0}

Documentation

Overview

Package flag implements command-line flag parsing.

Usage:

Define flags using flag.String(), Bool(), Int(), etc.

This declares an integer flag, -flagname, stored in the pointer ip, with type *int.

import "flag"
var ip = flag.Int("flagname", 1234, "help message for flagname")

If you like, you can bind the flag to a variable using the Var() functions.

var flagvar int
func init() {
	flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}

Or you can create custom flags that satisfy the Value interface (with pointer receivers) and couple them to flag parsing by

flag.Var(&flagVal, "name", "help message for flagname")

For such flags, the default value is just the initial value of the variable.

After all flags are defined, call

flag.Parse()

to parse the command line into the defined flags.

Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.

fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)

After parsing, the arguments following the flags are available as the slice flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg()-1.

Command line flag syntax:

-flag
-flag=x
-flag x  // non-boolean flags only

One or two minus signs may be used; they are equivalent. The last form is not permitted for boolean flags because the meaning of the command

cmd -x *

where * is a Unix shell wildcard, will change if there is a file called 0, false, etc. You must use the -flag=false form to turn off a boolean flag.

Flag parsing stops just before the first non-flag argument ("-" is a non-flag argument) or after the terminator "--".

Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags may be:

1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False

Duration flags accept any input valid for time.ParseDuration.

The default set of command-line flags is controlled by top-level functions. The FlagSet type allows one to define independent sets of flags, such as to implement subcommands in a command-line interface. The methods of FlagSet are analogous to the top-level functions for the command-line flag set.

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

import (
	"errors"
	"flag"
	"fmt"
	"strings"
	"time"
)

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

// Example 2: Two flags 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"
	)
	flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage)
	flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)")
}

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

// String is the method to format the flag's value, part of the flag.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 flag value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the flag.
// It's a comma-separated list, so we split it.
func (i *interval) Set(value string) error {
	// If we wanted to allow the flag 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 flag already set")
	}
	for _, dt := range strings.Split(value, ",") {
		duration, err := time.ParseDuration(dt)
		if err != nil {
			return err
		}
		*i = append(*i, duration)
	}
	return nil
}

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

var intervalFlag interval

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

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

Index

Examples

Constants

View Source
const (
	Posix  = PosixShort
	Greedy = GreedyMode
)

alias

Variables

View Source
var CommandLine = NewFlagSet(os.Args[0], 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 ErrHelp = errors.New("flag: help requested")

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

View Source
var ErrVersion = errors.New("flag: version requested")
View Source
var Usage = func() {
	CommandLine.printVersionAuthor()
	fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0])
	PrintDefaults()
}

Usage prints a usage message documenting all defined command-line flags to CommandLine's output, which by default is os.Stderr. It is called when an error occurs while parsing flags. The function is a variable that may be changed to point to a custom function. By default it prints a simple header and calls PrintDefaults; for details about the format of the output and how to control it, see the documentation for PrintDefaults. Custom usage functions may choose to exit the program; by default exiting happens anyway as the command line's error handling strategy is set to ExitOnError.

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. Arg returns an empty string if the requested element does not exist.

func Args

func Args() []string

Args returns the non-flag command-line arguments.

func Author

func Author(author string)

func Bool

func Bool(name string, value bool, usage 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)

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) *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. The flag accepts a value acceptable to time.ParseDuration.

func DurationSlice

func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration

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

func DurationSliceVar

func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string)

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

func DurationVar

func DurationVar(p *time.Duration, name string, value time.Duration, usage 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. The flag accepts a value acceptable to time.ParseDuration.

func Float64

func Float64(name string, value float64, usage 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)

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 Int

func Int(name string, value int, usage 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) *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 Int64Slice

func Int64Slice(name string, value []int64, usage string) *[]int64

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

func Int64SliceVar

func Int64SliceVar(p *[]int64, name string, value []int64, usage string)

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

func Int64Var

func Int64Var(p *int64, name string, value int64, usage 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)

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.

func ParseStruct

func ParseStruct(s interface{})

func Parsed

func Parsed() bool

Parsed reports whether the command-line flags have been parsed.

func PrintDefaults

func PrintDefaults()

PrintDefaults prints, to standard error unless configured otherwise, a usage message showing the default settings of all defined command-line flags. For an integer valued flag x, the default output has the form

-x int
	usage-message-for-x (default 7)

The usage message will appear on a separate line for anything but a bool flag with a one-byte name. For bool flags, the type is omitted and if the flag name is one byte the usage message appears on the same line. The parenthetical default is omitted if the default is the zero value for the type. The listed type, here int, can be changed by placing a back-quoted name in the flag's usage string; the first such item in the message is taken to be a parameter name to show in the message and the back quotes are stripped from the message when displayed. For instance, given

flag.String("I", "", "search `directory` for include files")

the output will be

-I directory
	search directory for include files.

func Set

func Set(name, value string) error

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

func String

func String(name string, value string, usage 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, value []string, usage string) *[]string

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

func StringSliceVar

func StringSliceVar(p *[]string, name string, value []string, usage string)

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

func StringVar

func StringVar(p *string, name string, value string, usage 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) *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) *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)

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)

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 UnquoteUsage

func UnquoteUsage(flag *Flag) (name string, usage string)

UnquoteUsage extracts a back-quoted name from the usage string for a flag and returns it and the un-quoted usage. Given "a `name` to show" it returns ("name", "a name to show"). If there are no back quotes, the name is an educated guess of the type of the flag's value, or the empty string if the flag is boolean.

func Var

func Var(value Value, name string, usage string)

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 Version

func Version(version string)

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 FlagSet.Parse behaves if the parse fails.

const (
	ContinueOnError ErrorHandling = iota // Return a descriptive error.
	ExitOnError                          // Call os.Exit(2).
	PanicOnError                         // Call panic with a descriptive error.
)

These constants cause FlagSet.Parse to behave as described if the parse fails.

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 (as text); for usage message

	Regex string
	Short []string
	Long  []string
	// contains filtered or unexported fields
}

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.

func Opt

func Opt(name string, usage string) *Flag

func (*Flag) DefaultVar

func (f *Flag) DefaultVar(p, defValue interface{})

func (*Flag) Flags

func (f *Flag) Flags(flag Flags) *Flag

func (*Flag) MatchVar

func (f *Flag) MatchVar(p, matchValue interface{})

func (*Flag) NewBool

func (f *Flag) NewBool(defValue bool) *bool

func (*Flag) NewBoolSlice

func (f *Flag) NewBoolSlice(defValue []bool) *[]bool

func (*Flag) NewDuration

func (f *Flag) NewDuration(defValue time.Duration) *time.Duration

func (*Flag) NewFloat64

func (f *Flag) NewFloat64(defValue float64) *float64

func (*Flag) NewInt

func (f *Flag) NewInt(defValue int) *int

func (*Flag) NewInt64

func (f *Flag) NewInt64(defValue int64) *int64

func (*Flag) NewInt64Slice

func (f *Flag) NewInt64Slice(defValue []int64) *[]int64

func (*Flag) NewString

func (f *Flag) NewString(defValue string) *string

func (*Flag) NewStringSlice

func (f *Flag) NewStringSlice(defValue []string) *[]string

func (*Flag) NewUint

func (f *Flag) NewUint(defValue uint) *uint

func (*Flag) NewUint64

func (f *Flag) NewUint64(defValue uint64) *uint64

func (*Flag) Var

func (f *Flag) Var(p interface{})

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. What happens after Usage is called depends
	// on the ErrorHandling setting; for the command line, this defaults
	// to ExitOnError, which exits the program after calling Usage.
	Usage func()
	// contains filtered or unexported fields
}

A FlagSet represents a set of defined flags. The zero value of a FlagSet has no name and has ContinueOnError error handling.

func NewFlagSet

func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

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

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. Arg returns an empty string if the requested element does not exist.

func (*FlagSet) Args

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

Args returns the non-flag arguments.

func (*FlagSet) Author

func (f *FlagSet) Author(author string) *FlagSet

func (*FlagSet) Bool

func (f *FlagSet) Bool(name string, value bool, usage 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)

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) *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. The flag accepts a value acceptable to time.ParseDuration.

func (*FlagSet) DurationSlice

func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration

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

func (*FlagSet) DurationSliceVar

func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string)

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

func (*FlagSet) DurationVar

func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage 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. The flag accepts a value acceptable to time.ParseDuration.

func (*FlagSet) ErrorHandling

func (f *FlagSet) ErrorHandling() ErrorHandling

ErrorHandling returns the error handling behavior of the flag set.

func (*FlagSet) Float64

func (f *FlagSet) Float64(name string, value float64, usage 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)

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) Init

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

Init sets the name and error handling property for a flag 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) *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) *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) Int64Slice

func (f *FlagSet) Int64Slice(name string, value []int64, usage string) *[]int64

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

func (*FlagSet) Int64SliceVar

func (f *FlagSet) Int64SliceVar(p *[]int64, name string, value []int64, usage string)

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

func (*FlagSet) Int64Var

func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage 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)

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) Opt

func (f *FlagSet) Opt(name string, usage string) *Flag

func (*FlagSet) OptOpt

func (f *FlagSet) OptOpt(opt Flag) *Flag

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 were set but not defined.

func (*FlagSet) ParseStruct

func (f *FlagSet) ParseStruct(arguments []string, s interface{}) error

func (*FlagSet) Parsed

func (f *FlagSet) Parsed() bool

Parsed reports whether f.Parse has been called.

func (*FlagSet) PrintDefaults

func (f *FlagSet) PrintDefaults()

PrintDefaults prints, to standard error unless configured otherwise, the default values of all defined command-line flags in the set. See the documentation for the global function PrintDefaults for more information.

func (*FlagSet) Set

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

Set sets the value of the named flag.

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) *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, value []string, usage string) *[]string

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

func (*FlagSet) StringSliceVar

func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string)

StringSliceVar defines a string flag with specified name, default value, and usage string. The argument p points to a string slice 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)

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) *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) *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)

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)

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, name string, usage string)

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) Version

func (f *FlagSet) Version(version string) *FlagSet

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 Flags

type Flags int
const (
	PosixShort Flags = 1 << iota
	GreedyMode
	RegexKeyIsValue
	NotValue
)

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 InvalidVarError

type InvalidVarError struct {
	Type reflect.Type
}

func (*InvalidVarError) Error

func (e *InvalidVarError) Error() string

type ParentCommand

type ParentCommand struct {
	Usage func()
	// contains filtered or unexported fields
}

func NewParentCommand

func NewParentCommand(name string) *ParentCommand

func (*ParentCommand) Args

func (p *ParentCommand) Args() []string

func (*ParentCommand) Output

func (p *ParentCommand) Output() io.Writer

func (*ParentCommand) Parse

func (p *ParentCommand) Parse(arguments []string) error

func (*ParentCommand) PrintDefaults

func (p *ParentCommand) PrintDefaults()

func (*ParentCommand) SetOutput

func (p *ParentCommand) SetOutput(output io.Writer)

func (*ParentCommand) SubCommand

func (p *ParentCommand) SubCommand(name string, usage string, subProcess func())

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.)

If a Value has an IsBoolFlag() bool method returning true, the command-line parser makes -name equivalent to -name=true rather than using the next command-line argument.

Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

Jump to

Keyboard shortcuts

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