varflag

package module
v6.0.0-...-9e95ba7 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2022 License: Apache-2.0 Imports: 11 Imported by: 0

README

varflag

Package flag implements command-line flag parsing into vars.Variables for easy type handling with additional flag types.

PkgGoDev license GitHub last commit tests Go Report Card Coverage Status benchmarks

Flags

note that major version ensures compatibility with https://github.com/mkungla/vars package

go get github.com/mkungla/varflag/v6

String flag

package main

import (
  "fmt"
  "log"
  "os"
  "github.com/mkungla/varflag/v6"
)

func main() {
  os.Args = []string{"/bin/app", "--str", "some value"}
  // create flag named string with default value "default str"
  // and aditional aliases for this flag
  str, err := varflag.New("string", "default str", "some string", "s", "str")
  if err != nil {
    log.Println(err)
    return
  }
  found, err := str.Parse(os.Args)
  if err != nil {
    log.Println(err)
    return
  }
  fmt.Printf("%-12s%s\n", "name", str.Name())
  fmt.Printf("%-12s%s\n", "flag", str.Flag())
  fmt.Printf("%-12s%t\n", "found", found)
  fmt.Printf("%-12s%s\n", "value", str.Value())
  // all flags satisfy Stringer interface
  fmt.Printf("%-12s%s\n", "string", str.String())
  fmt.Printf("%-12s%s\n", "default", str.Default())
  fmt.Printf("%-12s%s\n", "usage", str.Usage())
  fmt.Printf("%-12s%s\n", "aliases-str", str.AliasesString())
  fmt.Printf("%-12s%#v\n", "aliases", str.Aliases())
  // You can mark flag as hidden by calling .Hide()
  // Helpful when you are composing help menu.
  fmt.Printf("%-12s%t\n", "is:hidden", str.IsHidden())
  // by default flag is global regardless which position it was found.
  // You can mark flag non global by calling .BelongsTo(cmdname string).
  fmt.Printf("%-12s%t\n", "is:global", str.IsGlobal())
  fmt.Printf("%-12s%q\n", "command", str.CommandName())
  fmt.Printf("%-12s%d\n", "position", str.Pos())
  fmt.Printf("%-12s%t\n", "present", str.Present())
  // Var is underlying vars.Variable for convinient type conversion
  fmt.Printf("%-12s%s\n", "var", str.Var())
  // you can set flag as required by calling Required before you parse flags.
  fmt.Printf("%-12s%t\n", "required", str.IsRequired())
  // Output:
  // name        string
  // flag        --string
  // found       true
  // value       some value
  // string      some value
  // default     default str
  // usage       some string - default: "default str"
  // aliases-str -s,--str
  // aliases     []string{"s", "str"}
  // is:hidden   false
  // is:global   true
  // command     ""
  // position    2
  // present     true
  // var         some value
  // required    false
}

Duration flag

os.Args = []string{"/bin/app", "--duration", "1h30s"}
dur, _ := varflag.Duration("duration", 1*time.Second, "")
dur.Parse(os.Args)

fmt.Printf("%-12s%d\n", "duration", dur.Value())
fmt.Printf("%-12s%s\n", "duration", dur.Value())
fmt.Printf("%-12s%s\n", "string", dur.String())
fmt.Printf("%-12s%d\n", "int", dur.Var().Int())
fmt.Printf("%-12s%d\n", "int64", dur.Var().Int64())
fmt.Printf("%-12s%d\n", "uint", dur.Var().Uint())
fmt.Printf("%-12s%d\n", "uint64", dur.Var().Uint64())
fmt.Printf("%-12s%f\n", "float64", dur.Var().Float64())
// Output:
// duration    3630000000000
// duration    1h0m30s
// string      1h0m30s
// int         3630000000000
// int64       3630000000000
// uint        3630000000000
// uint64      3630000000000
// float64     3630000000000.000000

Float flag

os.Args = []string{"/bin/app", "--float", "1.001000023"}
f, _ := varflag.Float64("float", 1.0, "")
f.Parse(os.Args)

fmt.Printf("%-12s%.10f\n", "float", f.Value())
fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%.10f\n", "float32", f.Var().Float32())
fmt.Printf("%-12s%.10f\n", "float64", f.Var().Float64())
// Output:
// float       1.0010000230
// string      1.001000023
// float32     1.0010000467
// float64     1.0010000230

Int flag

os.Args = []string{"/bin/app", "--int", fmt.Sprint(math.MinInt64), "int64"}
f, _ := varflag.Int("int", 1, "")
f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%d\n", "value", f.Value())
fmt.Printf("%-12s%d\n", "int", f.Var().Int())
fmt.Printf("%-12s%d\n", "int64", f.Var().Int64())
fmt.Printf("%-12s%d\n", "uint", f.Var().Uint())
fmt.Printf("%-12s%d\n", "uint64", f.Var().Uint64())
fmt.Printf("%-12s%f\n", "float32", f.Var().Float32())
fmt.Printf("%-12s%f\n", "float64", f.Var().Float64())
// Output:
// string      -9223372036854775808
// value       -9223372036854775808
// int         -9223372036854775808
// int64       -9223372036854775808
// uint        0
// uint64      0
// float32     -9223372036854775808.000000
// float64     -9223372036854775808.000000

Uint Flag

os.Args = []string{"/bin/app", "--uint", strconv.FormatUint(math.MaxUint64, 10), "uint64"}
f, _ := varflag.Uint("uint", 1, "")
f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%d\n", "value", f.Value())
fmt.Printf("%-12s%d\n", "int", f.Var().Int())
fmt.Printf("%-12s%d\n", "int64", f.Var().Int64())
fmt.Printf("%-12s%d\n", "uint", f.Var().Uint())
fmt.Printf("%-12s%d\n", "uint64", f.Var().Uint64())
fmt.Printf("%-12s%f\n", "float32", f.Var().Float32())
fmt.Printf("%-12s%f\n", "float64", f.Var().Float64())
// Output:
// string      18446744073709551615
// value       18446744073709551615
// int         9223372036854775807
// int64       9223372036854775807
// uint        18446744073709551615
// uint64      18446744073709551615
// float32     18446744073709551616.000000
// float64     18446744073709551616.000000
}

Bool Flag

Valid bool flag args are

true

--bool, --bool=true, --bool=1 --bool=on, --bool true, --bool 1, --bool on

false

--bool, --bool=false, --bool=0 --bool=off, --bool false, --bool 0, --bool off

os.Args = []string{"/bin/app", "--bool"}
f, _ := varflag.Bool("bool", false, "")
f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%t\n", "value", f.Value())
fmt.Printf("%-12s%t\n", "bool", f.Var().Bool())
// Output:
// string      true
// value       true
// bool        true

Option Flag

os.Args = []string{"/bin/app", "--option", "opt1", "--option", "opt2"}
f, _ := varflag.Option("option", []string{"defaultOpt"}, "", []string{"opt1", "opt2", "opt3", "defaultOpt"})
f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%#v\n", "value", f.Value())

// Output:
// string      opt1|opt2
// value       []string{"opt1", "opt2"}

Bash Brace Expansion Flag

uses githubc.com/mkungla/bexp for Brace Expansion

os.Args = []string{"/bin/app", "--images", "image-{0..2}.jpg"}
f, _ := varflag.Bexp("images", "image-{a,b,c}.jpg", "expand path", "")
f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%#v\n", "value", f.Value())

// Output:
// string      image-0.jpg|image-1.jpg|image-2.jpg
// value       []string{"image-0.jpg", "image-1.jpg", "image-2.jpg"}

Parsing

Parse individual flags

str1, _ := varflag.New("str1", ".", "some string")
str2, _ := varflag.New("str2", "", "some other string")

str1.Parse(os.Args)
str2.Parse(os.Args)

Parse all flags at once

var flags []varflag.Flag

str1, _ := varflag.New("str1", ".", "some string")
str2, _ := varflag.New("str2", "", "some other string")

flags = append(flags, srt1, srt2)
varflag.Parse(flags, os.Args)

Use flag set

str1, err := varflag.New("str1", "", "")
str2, err := varflag.New("str2", "", "")
flags,err := varflag.NewFlagSet("/", 0)
flags.Add(str1, str2)
err := flags.Parse(os.Args)

test

golangci-lint run --config=./.github/golangci.yaml --fix
go test -race -covermode atomic  .

Documentation

Overview

Package varflag implements command-line flag parsing into vars.Variables for easy type handling with additional flag types.

Index

Examples

Constants

View Source
const (
	// FlagRe check flag name against following expression.
	FlagRe = "^[a-z][a-z0-9_-]*[a-z0-9]$"
)

Variables

View Source
var (
	// ErrFlag is returned when flag fails to initialize.
	ErrFlag = errors.New("flag error")
	// ErrParse is used to indicate parse errors.
	ErrParse = errors.New("flag parse error")
	// ErrMissingValue is used when flag value was not in parsed args.
	ErrMissingValue = errors.New("missing value for flag")
	// ErrInvalidValue is used when invalid value was provided.
	ErrInvalidValue = errors.New("invalid value for flag")
	// ErrFlagAlreadyParsed is returned when this flag was already parsed.
	ErrFlagAlreadyParsed = errors.New("flag is already parsed")
	// ErrMissingRequired indicates that required flag was not in argument set.
	ErrMissingRequired = errors.New("missing required flag")
	// ErrMissingOptions is returned when option flag parser does not find options.
	ErrMissingOptions = errors.New("missing options")
	// ErrNoNamedFlag is returned when flag lookup can not find named flag.
	ErrNoNamedFlag = errors.New("no such flag")
)

Functions

func Parse

func Parse(flags []Flag, args []string) error

Parse parses flags against provided args, If one of the flags fails to parse, it will return wrapped error these errors.

Example
os.Args = []string{
	"/bin/app",
	"-v",
	"--str1",
	"some value",
	"arg1",
	"arg2",
	"--str2",
	"some other value",
}

str1, err := varflag.New("str1", ".", "some string")
if err != nil {
	log.Println(err)
	return
}

str2, err := varflag.New("str2", "", "some other string")
if err != nil {
	log.Println(err)
	return
}

_ = varflag.Parse([]varflag.Flag{str1, str2}, os.Args)

fmt.Printf(
	"found %q with value %q, (%t) - it was global flag (%t) in position %d\n",
	str1.Name(),
	str1.Value(),
	str1.Present(),
	str1.IsGlobal(),
	str1.Pos(),
)

fmt.Printf(
	"found %q with value %q, (%t) - it was global flag (%t) in position %d\n",
	str2.Name(),
	str2.Value(),
	str2.Present(),
	str2.IsGlobal(),
	str2.Pos(),
)
Output:

found "str1" with value "some value", (true) - it was global flag (true) in position 3
found "str2" with value "some other value", (true) - it was global flag (true) in position 7

func ValidFlagName

func ValidFlagName(s string) bool

ValidFlagName returns true if s is string which is valid flag name.

Types

type BexpFlag

type BexpFlag struct {
	Common
	// contains filtered or unexported fields
}

BexpFlag expands flag args with bash brace expansion.

func Bexp

func Bexp(name string, value string, usage string, aliases ...string) (*BexpFlag, error)

Bexp returns new Bash Brace Expansion flag.

Example
os.Args = []string{"/bin/app", "--images", "image-{0..2}.jpg"}
f, _ := varflag.Bexp("images", "image-{a,b,c}.jpg", "expand path", "")
_, _ = f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%#v\n", "value", f.Value())
Output:

string      image-0.jpg|image-1.jpg|image-2.jpg
value       []string{"image-0.jpg", "image-1.jpg", "image-2.jpg"}

func (*BexpFlag) Parse

func (f *BexpFlag) Parse(args []string) (ok bool, err error)

Parse BexpFlag.

func (*BexpFlag) Unset

func (f *BexpFlag) Unset()

Unset the int flag value.

func (*BexpFlag) Value

func (f *BexpFlag) Value() []string

Value returns parsed options.

type BoolFlag

type BoolFlag struct {
	Common
	// contains filtered or unexported fields
}

BoolFlag is boolean flag type with default value "false".

func Bool

func Bool(name string, value bool, usage string, aliases ...string) (*BoolFlag, error)

Bool returns new bool flag. Argument "a" can be any nr of aliases.

Example
os.Args = []string{"/bin/app", "--bool"}
f, _ := varflag.Bool("bool", false, "")
_, _ = f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%t\n", "value", f.Value())
fmt.Printf("%-12s%t\n", "bool", f.Var().Bool())
Output:

string      true
value       true
bool        true

func (*BoolFlag) Parse

func (f *BoolFlag) Parse(args []string) (bool, error)

Parse bool flag.

func (*BoolFlag) Unset

func (f *BoolFlag) Unset()

Unset the bool flag value.

func (*BoolFlag) Value

func (f *BoolFlag) Value() bool

Value returns bool flag value, it returns default value if not present or false if default is also not set.

type Common

type Common struct {
	// contains filtered or unexported fields
}

Common is default string flag. Common flag ccan be used to as base for custom flags by owerriding .Parse func.

func New

func New(name string, value string, usage string, aliases ...string) (*Common, error)

New returns new common string flag. Argument "a" can be any nr of aliases.

Example
os.Args = []string{
	"/bin/app",
	"--str",
	"some value",
}
// create flag named string with default value "default str"
// and aditional aliases for this flag
str, err := varflag.New("string", "default str", "some string", "s", "str")
if err != nil {
	log.Println(err)
	return
}
// if you have single flag then parse it directly.
// no need for pkg .Parse
found, err := str.Parse(os.Args)
if err != nil {
	log.Println(err)
	return
}
fmt.Printf("%-12s%s\n", "name", str.Name())
fmt.Printf("%-12s%s\n", "flag", str.Flag())
fmt.Printf("%-12s%t\n", "found", found)
fmt.Printf("%-12s%s\n", "value", str.Value())
// all flags satisfy Stringer interface
fmt.Printf("%-12s%s\n", "string", str.String())
fmt.Printf("%-12s%s\n", "default", str.Default())
fmt.Printf("%-12s%s\n", "usage", str.Usage())
fmt.Printf("%-12s%s\n", "aliases-str", str.AliasesString())
fmt.Printf("%-12s%#v\n", "aliases", str.Aliases())
// You can mark flag as hidden by calling .Hide()
// Helpful when you are composing help menu.
fmt.Printf("%-12s%t\n", "is:hidden", str.IsHidden())
// by default flag is global regardless which position it was found.
// You can mark flag non global by calling .BelongsTo(cmdname string).
fmt.Printf("%-12s%t\n", "is:global", str.IsGlobal())
fmt.Printf("%-12s%q\n", "command", str.CommandName())
fmt.Printf("%-12s%d\n", "position", str.Pos())
fmt.Printf("%-12s%t\n", "present", str.Present())
// Var is underlying vars.Variable for convinient type conversion
fmt.Printf("%-12s%s\n", "var", str.Var())
// you can set flag as required by calling Required before you parse flags.
fmt.Printf("%-12s%t\n", "required", str.IsRequired())
Output:

name        string
flag        --string
found       true
value       some value
string      some value
default     default str
usage       some string - default: "default str"
aliases-str -s,--str
aliases     []string{"s", "str"}
is:hidden   false
is:global   true
command     ""
position    2
present     true
var         some value
required    false

func (*Common) Aliases

func (f *Common) Aliases() []string

Aliases returns all aliases for the flag together with primary "name".

func (*Common) AliasesString

func (f *Common) AliasesString() string

AliasesString returns string representing flag aliases. e.g. used in help menu.

func (*Common) BelongsTo

func (f *Common) BelongsTo(cmdname string)

BelongsTo marks flag non global and belonging to provided named command. Parsing the flag will only succeed if naemd command was found before the flag. This is useful to have same flag both global and sub command level. Special case is .BelongsTo("*") which marks flag to be parsed if any subcommand is present. e.g. verbose flag: you can define 2 BoolFlag's with name "verbose" and alias "v" and mark one of these with BelongsTo("*"). BelongsTo(os.Args[0] | "/") are same as global and will be.

func (*Common) CommandName

func (f *Common) CommandName() string

CommandName returns empty string if command is not set with .BelongsTo When BelongsTo is set to wildcard "*" then this function will return name of the command which triggered this flag to be parsed.

func (*Common) Default

func (f *Common) Default() vars.Variable

Default sets flag default.

func (*Common) Flag

func (f *Common) Flag() string

Flag returns flag with leading - or --.

func (*Common) Hide

func (f *Common) Hide()

Hide flag from help menu.

func (*Common) IsGlobal

func (f *Common) IsGlobal() bool

IsGlobal reports whether this flag is global. By default all flags are global flags. You can mark flag non-global by calling .BelongsTo(cmdname string).

func (*Common) IsHidden

func (f *Common) IsHidden() bool

IsHidden reports whether flag should be visible in help menu.

func (*Common) IsRequired

func (f *Common) IsRequired() bool

IsRequired returns true if this flag is required.

func (*Common) Name

func (f *Common) Name() string

Name returns primary name for the flag usually that is long option.

func (*Common) Parse

func (f *Common) Parse(args []string) (bool, error)

Parse the StringFlag.

func (*Common) Pos

func (f *Common) Pos() int

Pos returns flags position after command and case of global since app name min value is 1 which means first global flag or first flag after command.

func (*Common) Present

func (f *Common) Present() bool

Present reports whether flag was set in commandline.

func (*Common) Required

func (f *Common) Required()

Required sets this flag as required.

func (*Common) String

func (f *Common) String() string

String calls Value().String().

func (*Common) Unset

func (f *Common) Unset()

Unset the value.

func (*Common) Usage

func (f *Common) Usage() string

Usage returns a usage description for that flag.

func (*Common) Value

func (f *Common) Value() string

Value returns string value of flag.

func (*Common) Var

func (f *Common) Var() vars.Variable

Var returns vars.Variable for this flag. where key is flag and Value flags value.

type DurationFlag

type DurationFlag struct {
	Common
	// contains filtered or unexported fields
}

DurationFlag defines a time.Duration flag with specified name.

func Duration

func Duration(name string, value time.Duration, usage string, aliases ...string) (*DurationFlag, error)

Duration returns new duration flag. Argument "a" can be any nr of aliases.

Example
os.Args = []string{"/bin/app", "--duration", "1h30s"}
dur, _ := varflag.Duration("duration", 1*time.Second, "")
_, _ = dur.Parse(os.Args)

fmt.Printf("%-12s%d\n", "duration", dur.Value())
fmt.Printf("%-12s%s\n", "duration", dur.Value())
fmt.Printf("%-12s%s\n", "string", dur.String())
fmt.Printf("%-12s%d\n", "int", dur.Var().Int())
fmt.Printf("%-12s%d\n", "int64", dur.Var().Int64())
fmt.Printf("%-12s%d\n", "uint", dur.Var().Uint())
fmt.Printf("%-12s%d\n", "uint64", dur.Var().Uint64())
fmt.Printf("%-12s%f\n", "float32", dur.Var().Float32())
fmt.Printf("%-12s%f\n", "float64", dur.Var().Float64())
Output:

duration    3630000000000
duration    1h0m30s
string      1h0m30s
int         3630000000000
int64       3630000000000
uint        3630000000000
uint64      3630000000000
float32     3629999980544.000000
float64     3630000000000.000000

func (*DurationFlag) Parse

func (f *DurationFlag) Parse(args []string) (bool, error)

Parse duration flag.

func (*DurationFlag) Unset

func (f *DurationFlag) Unset()

Unset the bool flag value.

func (*DurationFlag) Value

func (f *DurationFlag) Value() time.Duration

Value returns duration flag value, it returns default value if not present or 0 if default is also not set.

type Flag

type Flag interface {
	// Get primary name for the flag. Usually that is long option
	Name() string

	// Get flag default value
	Default() vars.Variable

	// Usage returns a usage description for that flag
	Usage() string

	// Flag returns flag with leading - or --
	// useful for help menus
	Flag() string

	// Return flag aliases
	Aliases() []string

	// AliasesString returns string representing flag aliases.
	// e.g. used in help menu
	AliasesString() string

	// IsHidden reports whether to show that flag in help menu or not.
	IsHidden() bool

	// Hide flag from help menu.
	Hide()

	// IsGlobal reports whether this flag was global and was set before any command or arg
	IsGlobal() bool

	// BelongsTo marks flag non global and belonging to provided named command.
	BelongsTo(cmdname string)

	// CommandName returns empty string if command is not set with .BelongsTo
	// When BelongsTo is set to wildcard "*" then this function will return
	// name of the command which triggered this flag to be parsed.
	CommandName() string

	// Pos returns flags position after command. In case of mulyflag first position is reported
	Pos() int
	// Unset unsets the value for the flag if it was parsed, handy for cases where
	// one flag cancels another like --debug cancels --verbose
	Unset()

	// Present reports whether flag was set in commandline
	Present() bool

	// Var returns vars.Variable for this flag.
	// where key is flag and Value flags value.
	Var() vars.Variable

	// Required sets this flag as required
	Required()

	// IsRequired returns true if this flag is required
	IsRequired() bool

	// Parse value for the flag from given string. It returns true if flag
	// was found in provided args string and false if not.
	// error is returned when flag was set but had invalid value.
	Parse([]string) (bool, error)

	// String calls Value().String()
	String() string
	// contains filtered or unexported methods
}

Flag is howi/cli/flags.Flags interface.

type FlagSet

type FlagSet struct {
	// contains filtered or unexported fields
}

FlagSet holds collection of flags for parsing e.g. global, sub command or custom flag collection.

Example
os.Args = []string{
	"/bin/app", "cmd1", "--flag1", "val1", "--flag2", "flag2-value", "arg1", "--flag3=on",
	"-v",                                                          // global flag can be any place
	"subcmd", "--flag4", "val 4 flag", "arg2", "arg3", "-x", "on", // global flag can be any place
}

// Global app flags
global, _ := varflag.NewFlagSet(os.Args[0], 0)

v, _ := varflag.Bool("verbose", false, "increase verbosity", "v")
x, _ := varflag.Bool("x", false, "print commands")
r, _ := varflag.Bool("random", false, "random flag")
global.Add(v, x, r)

flag1, _ := varflag.New("flag1", "", "first flag for first cmd")
flag2, _ := varflag.New("flag2", "", "another flag for first cmd")
flag3, _ := varflag.Bool("flag3", false, "bool flag for first command")
cmd1, _ := varflag.NewFlagSet("cmd1", 1)
cmd1.Add(flag1, flag2, flag3)

cmd2, _ := varflag.NewFlagSet("cmd2", 0)
flag5, _ := varflag.New("flag5", "", "flag5 for second cmd")
cmd2.Add(flag5)

subcmd, _ := varflag.NewFlagSet("subcmd", 1)
flag4, _ := varflag.New("flag4", "", "flag4 for sub command")
subcmd.Add(flag4)
cmd1.AddSet(subcmd)

global.AddSet(cmd1, cmd2)
_ = global.Parse(os.Args)

// result
fmt.Printf("%-12s%t (%t) - %s (%s)\n", "verbose", v.Present(), v.IsGlobal(), v.String(), v.CommandName())
fmt.Printf("%-12s%t (%t) - %s (%s)\n", "x", x.Present(), x.IsGlobal(), x.String(), x.CommandName())
fmt.Printf("%-12s%t (%t) - %s (%s)\n", "random", r.Present(), r.IsGlobal(), r.String(), r.CommandName())
fmt.Printf("%-12s %v\n", "gloabal args", global.Args())

fmt.Printf("\n%-12s%t\n", "cmd1", cmd1.Present())
fmt.Printf("%-12s%t (%t) - %s\n", "flag1", flag1.Present(), flag1.IsGlobal(), flag1.String())
fmt.Printf("%-12s%t (%t) - %s\n", "flag2", flag2.Present(), flag2.IsGlobal(), flag2.String())
fmt.Printf("%-12s%t (%t) - %s\n", "flag3", flag3.Present(), flag3.IsGlobal(), flag3.String())
fmt.Printf("%-12s %v\n", "cmd1 args", cmd1.Args())

fmt.Printf("\n%-12s%t\n", "subcmd", subcmd.Present())
fmt.Printf("%-12s%t (%t) - %s\n", "flag4", flag4.Present(), flag4.IsGlobal(), flag4.String())
fmt.Printf("%-12s %v\n", "subcmd args", subcmd.Args())

fmt.Printf("\n%-12s%t\n", "cmd2", cmd2.Present())

// flag3 will not be present since it belongs to cmd 2
fmt.Printf("%-12s%t (%t)\n", "flag5", flag5.Present(), flag5.IsGlobal())
Output:

verbose     true (true) - true (/)
x           true (true) - true (/)
random      false (false) - false (/)
gloabal args []

cmd1        true
flag1       true (false) - val1
flag2       true (false) - flag2-value
flag3       true (false) - true
cmd1 args    [arg1]

subcmd      true
flag4       true (false) - val 4 flag
subcmd args  [arg2 arg3]

cmd2        false
flag5       false (false)

func NewFlagSet

func NewFlagSet(name string, argsn uint) (*FlagSet, error)

NewFlagSet is wrapper to parse flags together. e.g. under specific command. Where "name" is command name to search before parsing the flags under this set. argsn is number of command line arguments allowed within this set. If argsn is -gt 0 then parser will stop after finding argsn+1 argument which is not a flag.

func (*FlagSet) AcceptsArgs

func (s *FlagSet) AcceptsArgs() bool

Args returns parsed arguments for this flag set.

func (*FlagSet) Add

func (s *FlagSet) Add(flag ...Flag)

Add flag to flag set.

func (*FlagSet) AddSet

func (s *FlagSet) AddSet(set ...Flags)

AddSet adds flag set.

func (*FlagSet) Args

func (s *FlagSet) Args() []vars.Value

Args returns parsed arguments for this flag set.

func (*FlagSet) Flags

func (s *FlagSet) Flags() []Flag

Flags returns slice of flags in this set.

func (*FlagSet) Get

func (s *FlagSet) Get(name string) (Flag, error)

Get flag of current set.

func (*FlagSet) GetActiveSetTree

func (s *FlagSet) GetActiveSetTree() []Flags

GetSetTree

func (*FlagSet) Len

func (s *FlagSet) Len() int

Len returns nuber of flags in set.

func (*FlagSet) Name

func (s *FlagSet) Name() string

Name returns name of the flag set.

func (*FlagSet) Parse

func (s *FlagSet) Parse(args []string) error

Parse all flags recursively. nolint: gocognit, cyclop

func (*FlagSet) Pos

func (s *FlagSet) Pos() int

Pos returns flagset position from it's parent.

func (*FlagSet) Present

func (s *FlagSet) Present() bool

Present returns true if this set was parsed.

func (*FlagSet) Sets

func (s *FlagSet) Sets() []Flags

Sets retruns subsets of flags under this flagset.

type Flags

type Flags interface {
	// Add flag to flag set
	Add(...Flag)

	// Add sub set of flags to flag set
	AddSet(...Flags)

	// Parse all flags and sub sets
	Parse(args []string) error

	// Was flagset (sub command present)
	Present() bool

	// Name of the flag set
	Name() string

	// Position of flag set
	Pos() int

	// GetActiveSetTree.
	GetActiveSetTree() []Flags

	// Get named flag
	Get(name string) (Flag, error)

	// Len returns number of flags in this set
	// not including subset flags.
	Len() int

	// AcceptsArgs returns true if set accepts any arguments.
	AcceptsArgs() bool

	// Flags returns slice of flags in this set
	Flags() []Flag

	// Sets retruns subsets of flags under this flagset.
	Sets() []Flags
}

Flags provides interface for flag set.

type Float64Flag

type Float64Flag struct {
	Common
	// contains filtered or unexported fields
}

Float64Flag defines a float64 flag with specified name.

func Float64

func Float64(name string, value float64, usage string, aliases ...string) (*Float64Flag, error)

Float64 returns new float flag. Argument "a" can be any nr of aliases.

Example
os.Args = []string{"/bin/app", "--float", "1.001000023"}
f, _ := varflag.Float64("float", 1.0, "")
_, _ = f.Parse(os.Args)

fmt.Printf("%-12s%.10f\n", "float", f.Value())
fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%.10f\n", "float32", f.Var().Float32())
fmt.Printf("%-12s%.10f\n", "float64", f.Var().Float64())
Output:

float       1.0010000230
string      1.001000023
float32     1.0010000467
float64     1.0010000230

func (*Float64Flag) Parse

func (f *Float64Flag) Parse(args []string) (bool, error)

Parse float flag.

func (*Float64Flag) Unset

func (f *Float64Flag) Unset()

Unset the bool flag value.

func (*Float64Flag) Value

func (f *Float64Flag) Value() float64

Value return float64 flag value, it returns default value if not present or 0 if default is also not set.

type IntFlag

type IntFlag struct {
	Common
	// contains filtered or unexported fields
}

IntFlag defines an int flag with specified name,.

func Int

func Int(name string, value int, usage string, aliases ...string) (*IntFlag, error)

Int returns new int flag. Argument "a" can be any nr of aliases.

Example
os.Args = []string{"/bin/app", "--int", fmt.Sprint(math.MinInt64), "int64"}
f, _ := varflag.Int("int", 1, "")
_, _ = f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%d\n", "value", f.Value())
fmt.Printf("%-12s%d\n", "int", f.Var().Int())
fmt.Printf("%-12s%d\n", "int64", f.Var().Int64())
fmt.Printf("%-12s%d\n", "uint", f.Var().Uint())
fmt.Printf("%-12s%d\n", "uint64", f.Var().Uint64())
fmt.Printf("%-12s%f\n", "float32", f.Var().Float32())
fmt.Printf("%-12s%f\n", "float64", f.Var().Float64())
Output:

string      -9223372036854775808
value       -9223372036854775808
int         -9223372036854775808
int64       -9223372036854775808
uint        0
uint64      0
float32     -9223372036854775808.000000
float64     -9223372036854775808.000000

func (*IntFlag) Parse

func (f *IntFlag) Parse(args []string) (bool, error)

Parse int flag.

func (*IntFlag) Unset

func (f *IntFlag) Unset()

Unset the int flag value.

func (*IntFlag) Value

func (f *IntFlag) Value() int

Value returns int flag value, it returns default value if not present or 0 if default is also not set.

type OptionFlag

type OptionFlag struct {
	Common
	// contains filtered or unexported fields
}

OptionFlag is string flag type which can have value of one of the options.

func Option

func Option(name string, value []string, usage string, opts []string, aliases ...string) (*OptionFlag, error)

Option returns new string flag. Argument "opts" is string slice of options this flag accepts.

Example
os.Args = []string{"/bin/app", "--option", "opt1", "--option", "opt2"}
f, _ := varflag.Option("option", []string{"defaultOpt"}, "", []string{"opt1", "opt2", "opt3", "defaultOpt"})
_, _ = f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%#v\n", "value", f.Value())
Output:

string      opt1|opt2
value       []string{"opt1", "opt2"}

func (*OptionFlag) Parse

func (f *OptionFlag) Parse(args []string) (ok bool, err error)

Parse the OptionFlag.

func (*OptionFlag) Value

func (f *OptionFlag) Value() []string

Value returns parsed options.

type UintFlag

type UintFlag struct {
	Common
	// contains filtered or unexported fields
}

UintFlag defines a uint flag with specified name.

func Uint

func Uint(name string, value uint, usage string, aliases ...string) (*UintFlag, error)

Uint returns new uint flag. Argument "a" can be any nr of aliases.

Example
os.Args = []string{"/bin/app", "--uint", strconv.FormatUint(math.MaxUint64, 10), "uint64"}
f, _ := varflag.Uint("uint", 1, "")
_, _ = f.Parse(os.Args)

fmt.Printf("%-12s%s\n", "string", f.String())
fmt.Printf("%-12s%d\n", "value", f.Value())
fmt.Printf("%-12s%d\n", "int", f.Var().Int())
fmt.Printf("%-12s%d\n", "int64", f.Var().Int64())
fmt.Printf("%-12s%d\n", "uint", f.Var().Uint())
fmt.Printf("%-12s%d\n", "uint64", f.Var().Uint64())
fmt.Printf("%-12s%f\n", "float32", f.Var().Float32())
fmt.Printf("%-12s%f\n", "float64", f.Var().Float64())
Output:

string      18446744073709551615
value       18446744073709551615
int         9223372036854775807
int64       9223372036854775807
uint        18446744073709551615
uint64      18446744073709551615
float32     18446744073709551616.000000
float64     18446744073709551616.000000

func (*UintFlag) Parse

func (f *UintFlag) Parse(args []string) (bool, error)

Parse uint flag.

func (*UintFlag) Unset

func (f *UintFlag) Unset()

Unset the int flag value.

func (*UintFlag) Value

func (f *UintFlag) Value() uint

Value returns uint flag value, it returns default value if not present or 0 if default is also not set.

Jump to

Keyboard shortcuts

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