flag

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2024 License: Unlicense Imports: 15 Imported by: 2

README

turbo_flag

a drop in replacement for flag package which is included in the core go, but with additional capabilities like

  • Writing command-line apps with subcommands
  • Loading configuration file like json,yaml,toml.
  • Binding variable/s to values from a configuration file
  • Loading .env files
  • Binding variable/s to environment variable/s
  • Enumeration of the values of the flag
  • Short alias for a flag

etc.

NOTE: following functions/methods has been deprecated because they were not adding any value to the working of the core flag package:
FlagSet.PrintDefaults(): was an alias for usage itself
FlagSet.Usage(): rather you can use GetDefaultUsage() which will return a string to print to the console
ErrHelp: not needed
FlagSet.outPut
FlagSet.SetOutput(io.Writer): not needed
automatic handling of --help or -h flag has been removed
drop in replacement to core flag
import "flag"

fs:=flag.NewFlagSet("demo",flag.ContinueOnError)
help:=fs.Bool("help",false,"prints help")

just change the import to "github.com/ondbyte/turbo_flag"

import "github.com/ondbyte/turbo_flag"

fs:=flag.NewFlagSet("demo",flag.ContinueOnError)
help:=fs.Bool("help",false,"prints help")

what additional features it has over flag

loading configurations

lets load a file called demo.json having content

{
    "database":{
        "password":"12345"
    }
}

now bind the cfg

fs := NewFlagSet("test", ContinueOnError)
// only main command can load the cfg, sub commands / flagset will be preloaded with the same configuration while creating
err = fs.LoadCfg("./test_config/demo.json")
password := fs.String("password", "", "",fs.Cfg("database.password"))

fmt.Println(*password)
//prints "12345"
NOTE: supported config file types:
json, yaml/yml, toml.
NOTE:
if you need to ignore flags suplied to your program (i e act like viper) dont call FlagSet.Parse(args) but rather call FlagSet.ParseWithoutArgs(args)
binding environment variables
fs := flag.NewFlagSet("demo", flag.ExitOnError)
//now to bind a flag to a ENV/s
dbPassword:=fs.String("dbPassword","","the password usage",fs.Env( "POSTGRES_PASSWORD", "DB_PASSWORD")) 
//env's set are POSTGRES_PASSWORD=abc
fmt.Println(*dbPassword)
//prints "abc"
setting alias for a flag

useful for adding a short flag for another flag

fs := flag.NewFlagSet("demo", flag.ExitOnError)
dbPassword:=fs.String("dbPassword","","the password usage string",fs.Alias("p"))
//every property of the original flag will be copied
//when you run the program using "go run . -p "xyz"
fmt.Println(*dbPassword)
//prints "xyz"
setting enums/options/allowed values for a flag
//its an error if the default value of a flag is not one of the enums
fs := NewFlagSet("yourProgram", ContinueOnError,fs.Enum("a", "b", "c"))
option := fs.String("option", "c", "")
//from the commandline  allowed values are
//yourProgram -option a
//yourProgram -option b
//yourProgram -option c
// otherwise its a error
Sub-commands

example: a git program with commit and remote sub-commands

var (
	branchName = ""
	remoteName = ""
)

func main() {
	//run our program
	os.Args = []string{"commit", "--branch", "stable"}
	flag.MainCmdFs("git", flag.ContinueOnError, os.Args, git)
}

func git(fs *flag.FlagSet, args []string) {
	fs.SubCmdFs("commit", commit)
	fs.SubCmdFs("remote", remote)
	//lets try to commit with branch as argument
	err := fs.Parse(args)
	if err != nil {
		panic(err)
	}
	if branchName != "stable" {
		panic("branchNameFs should be stable")
	}
	//lets run remote with name argument
	err = fs.Parse([]string{"remote", "--name", "origin"})
	if err != nil {
		panic(err)
	}
	if remoteName != "origin" {
		panic("remoteNameFs should be origin")
	}
}

func commit(fs *flag.FlagSet, args []string) {
	var branch string
	fs.StringVar(&branch, "branch", "", "", fs.Alias("b"))

	err := fs.Parse(args)
	if err != nil {
		panic(err)
	}
	branchName = branch
}

func remote(fs *flag.FlagSet, args []string) {
	var name string
	fs.StringVar(&name, "name", "", "", fs.Alias("n"))

	err := fs.Parse(args)
	if err != nil {
		panic(err)
	}
	remoteName = name
}

alternative


var (
	branchName = ""
	remoteName = ""
)

func main() {
	//run our program
	os.Args = []string{"commit", "--branch", "stable"}
	flag.MainCmd("git", flag.ContinueOnError, os.Args, git)
}

func git(cmd flag.CMD, args []string) {
	cmd.SubCmd("commit", commit)
	cmd.SubCmd("remote", remote)
	//lets try to commit with branch as argument
	err := cmd.Parse(args)
	if err != nil {
		panic(err)
	}
	if branchName != "stable" {
		panic("branchName should be stable")
	}
	//lets run remote with name argument
	err = cmd.Parse([]string{"remote", "--name", "origin"})
	if err != nil {
		panic(err)
	}
	if remoteName != "origin" {
		panic("remoteName should be origin")
	}
}

func commit(fs flag.CMD, args []string) {
	var branch string
	fs.StringVar(&branch, "branch", "", "", fs.Alias("b"))

	err := fs.Parse(args)
	if err != nil {
		panic(err)
	}
	branchName = branch
}

func remote(fs flag.CMD, args []string) {
	var name string
	fs.StringVar(&name, "name", "", "", fs.Alias("n"))

	err := fs.Parse(args)
	if err != nil {
		panic(err)
	}
	remoteName = name
}

Documentation

Index

Examples

Constants

This section is empty.

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

Deprecated: rather call GetDefaultUsage() based on the error you get while calling Parse(args) ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.

View Source
var Usage = CommandLine.Usage

Deprecated: 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 Alias

func Alias(flags ...string) *flagFeature

binds flag/s with names to the flag you are defining, useful in adding short flags (bind flag help to flag h), every property of the flag will be copied. https://github.com/ondbyte/turbo_flag#setting-alias-for-a-flag

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 Bool

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

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 Cfg

func Cfg(cfgs ...string) *flagFeature

binds configurations value from config file to the to flag, use dot notation of the config key to bind. https://github.com/ondbyte/turbo_flag#loading-configurations

func Duration

func Duration(name string, value time.Duration, usage string, features ...*flagFeature) *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 DurationVar

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

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 Enum

func Enum(enums ...string) *flagFeature

bind enums to the flag, if you do this only entries in the enums will be the possible values for flag you are currently defining https://github.com/ondbyte/turbo_flag#setting-enumsoptionsallowed-values-for-a-flag

func Env

func Env(envs ...string) *flagFeature

binds env/s to the to flag you are defining https://github.com/ondbyte/turbo_flag#binding-environment-variables

func EnvToMap

func EnvToMap(content string) (map[string]string, error)

EnvToMap parses an environment file content and returns the key-value pairs as a map.

func Float64

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

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 Func

func Func(name, usage string, fn func(string) error)

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

Example
package main

import (
	"errors"
	"flag"
	"fmt"
	"net"
	"os"
)

func main() {
	fs := flag.NewFlagSet("ExampleFunc", flag.ContinueOnError)
	fs.SetOutput(os.Stdout)
	var ip net.IP
	fs.Func("ip", "`IP address` to parse", func(s string) error {
		ip = net.ParseIP(s)
		if ip == nil {
			return errors.New("could not parse IP")
		}
		return nil
	})
	fs.Parse([]string{"-ip", "127.0.0.1"})
	fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())

	// 256 is not a valid IPv4 component
	fs.Parse([]string{"-ip", "256.0.0.1"})
	fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())

}
Output:

{ip: 127.0.0.1, loopback: true}

invalid value "256.0.0.1" for flag -ip: could not parse IP
Usage of ExampleFunc:
  -ip IP address
    	IP address to parse
{ip: <nil>, loopback: false}

func GetDefaultUsage

func GetDefaultUsage() (usage string, err error)

returns a well formatted short usage to print while user passes help flag

func GetDefaultUsageLong

func GetDefaultUsageLong() (usage string, err error)

returns a well formatted detailed (with additional details about the features of the flag) usage to print while user passes help flag

func GetFirstSubCommandWithArgs

func GetFirstSubCommandWithArgs(args []string) (string, []string, bool)

func Int

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

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, features ...*flagFeature)

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 JSONToMap

func JSONToMap(content string) (map[string]interface{}, error)

JSONToMap reads the contents of a JSON file from a string and returns a map[interface{}]interface{}

func LoadCfg

func LoadCfg(path string) (err error)

loads a cfg to this default flagset any sub command defined will also derive from this

func LoadEnv

func LoadEnv(path string) error

loads all environment variables from a env file using os.SetEnv effectively making it easier to bind the flags to a env

func MainCmd

func MainCmd(name string, usage string, errorHandling ErrorHandling, args []string, fn func(fs CMD, args []string))

calls fn when this command with name is invoked, pass os.Args or your custom arguments to args the same will be passed to fn with a new CMD with name and error handling set to errorHandling

see here https://github.com/ondbyte/turbo_flag#alternative

func MainCmdFs

func MainCmdFs(name string, usage string, errorHandling ErrorHandling, args []string, fn func(fs *FlagSet, args []string))

calls fn when this command with name is invoked, pass os.Args or your custom arguments to args the same will be passed to fn with a new FlagSet with name and error handling set to errorHandling

see here https://github.com/ondbyte/turbo_flag#sub-commands

func MapToJSON

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

MapToJSON writes a map to a JSON string

func MapToTOML

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

map to a TOML string

func MapToYAML

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

MapToYAML writes a map to a YAML string

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() error

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 ParseWithoutArgs

func ParseWithoutArgs() error

ParseWithoutArgs parses everything like binding cfg, binding env, binding to other flags etc but arguments passed to the program won't be parsed and considered, when you require flag set to act like config loader (viper'ish) still takes in arguments to parse the sub commands passed and run it

func Parsed

func Parsed() bool

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

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, features ...*flagFeature) *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 StringVar

func StringVar(p *string, name string, value string, usage string, features ...*flagFeature)

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 SubCmd

func SubCmd(name string, usage string, fn func(cmd CMD, args []string))

adds a new sub flagset to the parent flagset, loads the config file if it exists in the parent the sub command fn recieves the new FlagSet and the arguments thats for the sub command you can add new flags to this sub flagset and call fs.Parse with the arguments you recieved in this function

func SubCmdFs

func SubCmdFs(name string, usage string, fn func(fs *FlagSet, args []string))

if you are using NewCmd(..) constructor then use the SubCmd(..) method rather than this or else use this if you are using NewFlagSet(..). adds a new sub flagset to the parent flagset, loads the config file if it exists in the parent the sub command fn recieves the new FlagSet and the arguments thats for the sub command you can add new flags to this sub flagset and call fs.Parse with the arguments you recieved in this function

func TOMLToMap

func TOMLToMap(content string) (map[string]interface{}, error)

func TextVar

func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string, features ...*flagFeature)

TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.

func Uint

func Uint(name string, value uint, usage string, features ...*flagFeature) *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, features ...*flagFeature) *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, features ...*flagFeature)

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, features ...*flagFeature)

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, features ...*flagFeature)

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.

func YAMLToMap

func YAMLToMap(content string) (map[string]interface{}, error)

YAMLToMap reads the contents of a YAML file from a string and returns a map[interface{}]interface{}

Types

type CMD

type CMD interface {

	// ParseWithoutArgs parses the command-line arguments without consuming any of them.
	// It returns an error if there are any unparsed flags or any error encountered during flag parsing.
	ParseWithoutArgs(args []string) error

	// loads all environment variables from a env file using os.SetEnv
	// effectively making it easier to bind the flags to a env
	LoadEnv(path string) error

	// loads a configuration file at path to this command so you can bind configurations
	LoadCfg(path string) (err error)

	// introduces a subcommand to this command
	// you can pass a callback which will recieve a new CMD with name name and args you should parse with the CMD
	// you recieved after defining the flags
	SubCmd(name string, usage string, fn func(cmd CMD, args []string))

	// add the values possible for the flag you are defining
	Enum(enums ...string) *flagFeature

	// alias for the fla you are defining, like h for a flag named help
	Alias(flags ...string) *flagFeature

	// bind the cfg value from the configurtion file you loaded to the flag you are defining
	Cfg(cfgs ...string) *flagFeature

	//bind env to the flag you are defining
	Env(envs ...string) *flagFeature

	// BoolVar defines a bool flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to a bool variable in which to store the value of the flag.
	BoolVar(p *bool, name string, value bool, usage string, features ...*flagFeature)

	// Bool defines a bool flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of a bool variable that stores the value of the flag.
	Bool(name string, value bool, usage string, features ...*flagFeature) *bool

	// IntVar defines an int flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to an int variable in which to store the value of the flag.
	IntVar(p *int, name string, value int, usage string, features ...*flagFeature)

	// Int defines an int flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of an int variable that stores the value of the flag.
	Int(name string, value int, usage string, features ...*flagFeature) *int

	// Int64Var defines an int64 flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to an int64 variable in which to store the value of the flag.
	Int64Var(p *int64, name string, value int64, usage string, features ...*flagFeature)

	// Int64 defines an int64 flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of an int64 variable that stores the value of the flag.
	Int64(name string, value int64, usage string, features ...*flagFeature) *int64

	// UintVar defines a uint flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to a uint variable in which to store the value of the flag.
	UintVar(p *uint, name string, value uint, usage string, features ...*flagFeature)

	// Uint defines a uint flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of a uint variable that stores the value of the flag.
	Uint(name string, value uint, usage string, features ...*flagFeature) *uint

	// Uint64Var defines a uint64 flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to a uint64 variable in which to store the value of the flag.
	Uint64Var(p *uint64, name string, value uint64, usage string, features ...*flagFeature)

	// Uint64 defines a uint64 flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of a uint64 variable that stores the value of the flag.
	Uint64(name string, value uint64, usage string, features ...*flagFeature) *uint64

	// StringVar defines a string flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to a string variable in which to store the value of the flag.
	StringVar(p *string, name string, value string, usage string, features ...*flagFeature)

	// String defines a string flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of a string variable that stores the value of the flag.
	String(name string, value string, usage string, features ...*flagFeature) *string

	// Float64Var defines a float64 flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to a float64 variable in which to store the value of the flag.
	Float64Var(p *float64, name string, value float64, usage string, features ...*flagFeature)

	// Float64 defines a float64 flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of a float64 variable that stores the value of the flag.
	Float64(name string, value float64, usage string, features ...*flagFeature) *float64

	// DurationVar defines a time.Duration flag with specified name, default value, usage string, and optional flag features.
	// The argument p points to a time.Duration variable in which to store the value of the flag.
	DurationVar(p *time.Duration, name string, value time.Duration, usage string, features ...*flagFeature)

	// Duration defines a time.Duration flag with specified name, default value, usage string, and optional flag features.
	// The return value is the address of a time.Duration variable that stores the value of the flag.
	Duration(name string, value time.Duration, usage string, features ...*flagFeature) *time.Duration

	// TextVar defines a flag with specified name, default value, usage string, and optional flag features.
	// The argument p is an encoding.TextUnmarshaler that is used to unmarshal the flag value.
	TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string, features ...*flagFeature)

	// Var defines a flag with specified name, usage string, and optional flag features.
	// The argument value is a Value interface that provides the flag's value and default value.
	Var(value Value, name string, usage string, features ...*flagFeature)

	// Name returns the name of the FlagSet.
	Name() string

	// Set sets the value of the named flag.
	// It returns an error if the flag does not exist or the value is invalid.
	Set(name, value string) error

	// GetDefaultUsage returns the default usage string for the CMD.
	GetDefaultUsage() (usage string, err error)

	// returns a well formatted detailed (with additional details about the features of the flag) usage to print while user passes help flag
	GetDefaultUsageLong() (usage string, err error)

	// Func defines a flag with specified name, usage string, and function to be called when the flag is parsed.
	// The provided function is called with the flag's value as its argument.
	Func(name, usage string, fn func(string) error, features ...*flagFeature)

	// Parse parses the command-line arguments.
	// It returns an error if there are any unparsed flags or any error encountered during flag parsing.
	Parse(arguments []string) error

	// Parsed returns whether the command-line arguments have been parsed.
	Parsed() bool
}

CMD is just a interface for *flag.FlagSet

func NewCmd

func NewCmd(name string, usage string, errorHandling ErrorHandling) CMD

alias to the NewFlagSet but returns CMD interface which has old methods filtered out. this or MainCmd(...) recommended over this and NewFlagSet.

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) or for -h/-help Exit(0).
	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
	// 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 (*Flag) Set

func (f *Flag) Set(s string) error

type FlagSet

type FlagSet struct {
	// Deprecated: rather use GetDefaultUsage() and use the result to show the default usage message
	// 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()

	SubCmds map[string]*subCommand
	// 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.

Flag names must be unique within a FlagSet. An attempt to define a flag whose name is already in use will cause a panic.

func NewFlagSet

func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

NewFlagSet returns a new, empty flag set with the specified name and error handling property. If the name is not empty, it will be printed in the default usage message and in error messages. NewCmd is recommended over this

func (*FlagSet) Alias

func (fs *FlagSet) Alias(flags ...string) *flagFeature

binds flag/s with names to the flag you are defining, useful in adding short flags (bind flag help to flag h), every property of the flag will be copied. https://github.com/ondbyte/turbo_flag#setting-alias-for-a-flag

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

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

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

func (fs *FlagSet) Cfg(cfgs ...string) *flagFeature

binds configurations value from config file to the to flag, use dot notation of the config key to bind. https://github.com/ondbyte/turbo_flag#loading-configurations

func (*FlagSet) Duration

func (f *FlagSet) Duration(name string, value time.Duration, usage string, features ...*flagFeature) *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) DurationVar

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

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

func (fs *FlagSet) Enum(enums ...string) *flagFeature

bind enums to the flag, if you do this only entries in the enums will be the possible values for flag you are currently defining https://github.com/ondbyte/turbo_flag#setting-enumsoptionsallowed-values-for-a-flag

func (*FlagSet) Env

func (fs *FlagSet) Env(envs ...string) *flagFeature

binds env/s to the to flag you are defining https://github.com/ondbyte/turbo_flag#binding-environment-variables

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, features ...*flagFeature) *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, features ...*flagFeature)

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

func (f *FlagSet) Func(name, usage string, fn func(string) error, features ...*flagFeature)

Func 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) GetDefaultUsage

func (f *FlagSet) GetDefaultUsage() (usage string, err error)

returns a well formatted short usage to print while user passes help flag

func (*FlagSet) GetDefaultUsageLong

func (f *FlagSet) GetDefaultUsageLong() (usage string, err error)

returns a well formatted detailed (with additional details about the features of the flag) usage to print while user passes help flag

func (*FlagSet) GetFlagForPtr

func (fs *FlagSet) GetFlagForPtr(ptr interface{}) (*Flag, error)

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, features ...*flagFeature) *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, features ...*flagFeature) *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, features ...*flagFeature)

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, features ...*flagFeature)

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

func (fs *FlagSet) LoadCfg(path string) (err error)

loads a cfg to this flagset any sub command defined will also derive from this

func (*FlagSet) LoadEnv

func (fs *FlagSet) LoadEnv(path string) error

loads all environment variables from a env file using os.SetEnv effectively making it easier to bind the flags to a env

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

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

Parse parses everything like binding cfg, binding env, binding to other flags etc then parses the arguments and any argument found will override any prior mentioned bindings. 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) ParseWithoutArgs

func (f *FlagSet) ParseWithoutArgs(args []string) error

ParseWithoutArgs parses everything like binding cfg, binding env, binding to other flags etc but arguments passed to the program won't be parsed and considered, when you require flag set to act like config loader (viper'ish) still takes in arguments to parse the sub commands passed and run it

func (*FlagSet) Parsed

func (f *FlagSet) Parsed() bool

Parsed reports whether f.Parse has been called.

func (*FlagSet) PrintDefaults deprecated

func (f *FlagSet) PrintDefaults()

Deprecated: This function is no longer recommended for use. use GetDefaultUsage() instead. 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 deprecated

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

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

func (*FlagSet) SetUsage

func (f *FlagSet) SetUsage(usage string)

func (*FlagSet) String

func (f *FlagSet) String(name string, value string, usage string, features ...*flagFeature) *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) StringVar

func (f *FlagSet) StringVar(p *string, name string, value string, usage string, features ...*flagFeature)

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

func (fs *FlagSet) SubCmd(name string, usage string, fn func(cmd CMD, args []string))

adds a new sub flagset to the parent flagset, loads the config file if it exists in the parent the sub command fn recieves the new FlagSet and the arguments thats for the sub command you can add new flags to this sub flagset and call fs.Parse with the arguments you recieved in this function

func (*FlagSet) SubCmdFs

func (fs *FlagSet) SubCmdFs(name string, usage string, fn func(fs *FlagSet, args []string))

if you are using NewCmd(..) constructor then use the SubCmd(..) method rather than this or else use this if you are using NewFlagSet(..). adds a new sub flagset to the parent flagset, loads the config file if it exists in the parent the sub command fn recieves the new FlagSet and the arguments thats for the sub command you can add new flags to this sub flagset and call fs.Parse with the arguments you recieved in this function

func (*FlagSet) TextVar

func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string, features ...*flagFeature)

TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.

func (*FlagSet) Uint

func (f *FlagSet) Uint(name string, value uint, usage string, features ...*flagFeature) *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, features ...*flagFeature) *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, features ...*flagFeature)

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, features ...*flagFeature)

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, features ...*flagFeature)

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() any
}

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, except the type used by Func.

type Value

type Value interface {
	String() string
	Set(s 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.

Example
package main

import (
	"flag"
	"fmt"
	"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); err != nil {
		return err
	} else {
		*v.URL = *u
	}
	return nil
}

var u = &url.URL{}

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

	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