Documentation
¶
Overview ¶
Package cflag Wraps and extends go `flag.FlagSet` to build simple command line applications
- Support auto render a pretty help panel
- Allow to add shortcuts for flag option
- Allow binding named arguments
- Allow set required for argument or option
- Allow set validator for argument or option
Example ¶
package main
import (
"github.com/gookit/goutil/cflag"
"github.com/gookit/goutil/cliutil"
)
func main() {
opts := struct {
age int
name string
str1 string
bol bool
}{}
c := cflag.New(func(c *cflag.CFlags) {
c.Desc = "this is a demo command"
c.Version = "0.5.1"
})
c.IntVar(&opts.age, "age", 0, "this is a int option;;a")
c.StringVar(&opts.name, "name", "", "this is a string option and required;true")
c.StringVar(&opts.str1, "str1", "def-val", "this is a string option with default value;;s")
c.AddArg("arg1", "this is arg1", true, nil)
c.AddArg("arg2", "this is arg2", true, nil)
c.AddArg("arg3", "this is arg3 with default", false, "def-val")
c.Func = func(c *cflag.CFlags) error {
// do something ...
cliutil.Infoln("hello, this is", c.Name())
cliutil.Infoln("option.age =", opts.age)
cliutil.Infoln("option.name =", opts.name)
cliutil.Infoln("option.str1 =", opts.str1)
cliutil.Infoln("arg1 =", c.Arg("arg1").String())
cliutil.Infoln("arg2 =", c.Arg("arg2").String())
cliutil.Infoln("arg3 =", c.Arg("arg3").String())
return nil
}
// c.MustParse(os.Args[1:])
c.MustParse(nil)
}
Output:
Index ¶
- Constants
- Variables
- func AddPrefix(name string) string
- func AddPrefixes(name string, shorts []string) string
- func AddPrefixes2(name string, shorts []string, nameAtEnd bool) string
- func DebugMsg(format string, args ...any)
- func FilterNames(names []string) []string
- func IsFlagHelpErr(err error) bool
- func IsGoodName(name string) bool
- func IsZeroValue(opt *flag.Flag, value string) (bool, bool)
- func LimitInt(min, max int) comdef.IntCheckFunc
- func ReplaceShorts(args []string, shortsMap map[string]string, ...) []string
- func SetDebug(open bool)
- func SplitShortcut(shortcut string) []string
- func WithDesc(desc string) func(c *CFlags)
- func WithVersion(version string) func(c *CFlags)
- func WrapColorForCode(s string) string
- type Booleans
- type CFlags
- func (c *CFlags) AddArg(name, desc string, requireDefaultArrayed ...any)
- func (c *CFlags) AddShortcuts(name string, shorts ...string)
- func (c *CFlags) AddValidator(name string, fn OptCheckFn)
- func (c *CFlags) Arg(name string) *FlagArg
- func (c *CFlags) BinFile() string
- func (c *CFlags) BindArg(arg *FlagArg)
- func (c *CFlags) ConfigOpt(name string, fn func(opt *FlagOpt))
- func (c *CFlags) DoParse(args []string) error
- func (c *CFlags) DoParseStopOnArg(args []string) error
- func (c *CFlags) MustParse(args []string)
- func (c *CFlags) MustRun(args []string)
- func (c *CFlags) Name() string
- func (c *CFlags) Parse(args []string) error
- func (c *CFlags) Prepare() error
- func (c *CFlags) QuickRun()
- func (c *CFlags) RemainArgs() []string
- func (c *CFlags) RenderOptionsHelp(buf *strutil.Buffer)
- func (c *CFlags) ShowHelp()
- func (c *CFlags) WithConfigFn(fns ...func(c *CFlags)) *CFlags
- type ConfString
- type EnumString
- func (s *EnumString) Enum() []string
- func (s *EnumString) EnumString() string
- func (s *EnumString) FlagTypeDesc() string
- func (s *EnumString) Get() any
- func (s *EnumString) Set(value string) error
- func (s *EnumString) SetEnum(enum []string)
- func (s *EnumString) String() string
- func (s *EnumString) WithEnum(enum []string) *EnumString
- type ExtendedFlagType
- type FlagArg
- type FlagOpt
- type IntVar
- type Ints
- type IntsString
- type KVStrMap
- type KVString
- type OptCheckFn
- type RepeatableFlag
- type SafeFuncVar
- type StrVar
- type String
- type Strings
Examples ¶
Constants ¶
const ParseStopMark = "--"
ParseStopMark string
const (
// RegGoodName match a good option, argument name
RegGoodName = `^[a-zA-Z][\w-]*$`
)
Variables ¶
var Debug = envutil.GetBool("CFLAG_DEBUG")
Debug mode
var ErrStopRun = errors.New("stop run")
ErrStopRun error
Functions ¶
func AddPrefixes ¶
AddPrefixes for render flag options help, name will first add.
func AddPrefixes2 ¶ added in v0.5.6
AddPrefixes2 for render flag options help, can custom name add position.
func FilterNames ¶ added in v0.5.7
FilterNames for option names, will clear there are: "-+= "
func IsZeroValue ¶
IsZeroValue determines whether the string represents the zero value for a flag.
from flag.isZeroValue() and more return the second arg for check is string.
func LimitInt ¶ added in v0.6.11
func LimitInt(min, max int) comdef.IntCheckFunc
LimitInt limit int value range
func ReplaceShorts ¶ added in v0.5.6
func ReplaceShorts(args []string, shortsMap map[string]string, stopFn ...func(string) (bool, bool)) []string
ReplaceShorts replace shorts to full option. will stop on ParseStopMark The optional stopFn can stop replacement early and mark current option consumes the next arg value. It is used by app-level parsing to avoid rewriting command args.
For example:
eg: '-f' -> '--file'. eg: '-n=tom' -> '--name=tom'.
func SplitShortcut ¶ added in v0.5.6
SplitShortcut string to []string
func WrapColorForCode ¶ added in v0.5.13
WrapColorForCode convert "hello `keywords`" to "hello <mga>keywords</>"
Types ¶
type Booleans ¶ added in v0.5.13
type Booleans []bool
Booleans The bool flag list, repeatable. eg: -v -v => []bool{true, true}
func (*Booleans) IsRepeatable ¶ added in v0.6.7
IsRepeatable on input
type CFlags ¶
type CFlags struct {
*flag.FlagSet
// Desc command description
Desc string
Usage string // command usage contents
// Version command version number
Version string
// Example command usage examples
Example string
// LongHelp custom help
LongHelp string
// HelpOnEmptyArgs show help when not input args. default: false
HelpOnEmptyArgs bool
// HelpFunc custom help render func
HelpFunc func(c *CFlags)
// AfterFlagParse handler. return false to stop continue run Func.
// - fire on flag options parsed, before binding arguments
AfterFlagParse func(c *CFlags) bool
// BeforeRun handler for the command. return false to stop run Func.
//
// TIP: You can do some processing or intercept command execution before running.
BeforeRun func(c *CFlags) bool
// Func handler for the command
Func func(c *CFlags) error
// contains filtered or unexported fields
}
CFlags wrap and extends the go flag.FlagSet
eg:
// Can be set required and shorts on desc: // format1: desc;required cmd.IntVar(&age, "age", 0, "your age;true") // format2: desc;required;shorts cmd.IntVar(&age, "age", 0, "your age;true;a")
func New ¶
New create new instance.
Usage:
cmd := cflag.New(func(c *cflag.CFlags) {
c.Version = "0.1.2"
c.Desc = "this is my cli tool"
})
// binding opts and args
cmd.Parse(nil)
func NewWith ¶ added in v0.7.2
NewWith create new instance.
Usage:
cmd := cflag.NewWith("0.1.2", "this is my cli tool")
// binding opts and args
cmd.Parse(nil)
func (*CFlags) AddArg ¶
AddArg binding for command, by position
c.AddArg("name", "desc ...")
c.AddArg("name", "desc ...", required: bool)
c.AddArg("name", "desc ...", required: bool, default: any)
c.AddArg("name", "desc ...", required: bool, default: any, isArray: bool)
func (*CFlags) AddShortcuts ¶
AddShortcuts for option flag
func (*CFlags) AddValidator ¶
func (c *CFlags) AddValidator(name string, fn OptCheckFn)
AddValidator for a flag option
func (*CFlags) DoParse ¶ added in v0.7.2
DoParse parse options and validate, collect args. (internal use)
func (*CFlags) DoParseStopOnArg ¶ added in v0.8.0
DoParseStopOnArg parse options and stop at first argument.
func (*CFlags) Parse ¶
Parse flags and run command func.
If args is nil, will parse os.Args
- will auto handle display help on with --help, -h
func (*CFlags) QuickRun ¶ added in v0.5.6
func (c *CFlags) QuickRun()
QuickRun parse OS flags and run command, will auto handle error
func (*CFlags) RenderOptionsHelp ¶ added in v0.7.2
RenderOptionsHelp 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.
from flag.PrintDefaults
func (*CFlags) WithConfigFn ¶
WithConfigFn for command
type ConfString ¶ added in v0.6.5
ConfString The config-string flag, INI format, like nginx-config.
Example:
--config 'k0=val0;k1=val1' => string map {k0:val0, k1:val1}
func (*ConfString) Set ¶ added in v0.6.5
func (s *ConfString) Set(value string) error
Set new value, will check value is right
func (*ConfString) SetData ¶ added in v0.6.5
func (s *ConfString) SetData(mp map[string]string)
SetData value
type EnumString ¶ added in v0.5.13
type EnumString struct {
// contains filtered or unexported fields
}
EnumString limit input value is in the enum list. implemented flag.Value interface
Usage:
var enumStr = cflag.NewEnumString("php", "go", "java")
c.VarOpt(&enumStr, "lang", "", "input language name")
func NewEnumString ¶ added in v0.6.6
func NewEnumString(enum ...string) EnumString
NewEnumString instance
func (*EnumString) EnumString ¶ added in v0.6.7
func (s *EnumString) EnumString() string
EnumString to string
func (*EnumString) FlagTypeDesc ¶ added in v0.7.0
func (s *EnumString) FlagTypeDesc() string
FlagTypeDesc message. will display on the flag description end.
func (*EnumString) Set ¶ added in v0.5.13
func (s *EnumString) Set(value string) error
Set new value, will check value is right
func (*EnumString) SetEnum ¶ added in v0.5.13
func (s *EnumString) SetEnum(enum []string)
SetEnum values
func (*EnumString) String ¶ added in v0.5.13
func (s *EnumString) String() string
String input value to string
func (*EnumString) WithEnum ¶ added in v0.6.6
func (s *EnumString) WithEnum(enum []string) *EnumString
WithEnum values
type ExtendedFlagType ¶ added in v0.7.0
type ExtendedFlagType interface {
// FlagTypeDesc flag type description. use for enum and more custom types.
FlagTypeDesc() string
}
ExtendedFlagType interface.
type FlagArg ¶
type FlagArg struct {
// Value for the flag argument
*structs.Value
// Name of the argument
Name string
// Desc arg description
Desc string
// Index of the argument
Index int
// Required argument
Required bool
// Arrayed argument. MUST on the last
Arrayed bool // support arrayed argument
// Validator for check value
Validator func(val string) error
// contains filtered or unexported fields
}
FlagArg struct
type FlagOpt ¶
type FlagOpt struct {
// Shortcuts short names. eg: ["o", "a"]
Shortcuts []string
// Required option
Required bool
// Validator for check option value
Validator OptCheckFn
}
FlagOpt struct
type IntVar ¶ added in v0.6.11
type IntVar struct {
// check func
CheckFn comdef.IntCheckFunc
// contains filtered or unexported fields
}
IntVar int value can with a check func
Limit min and max value:
iv := cflag.IntValue{CheckFn: cflag.LimitInt(1, 10)}
fs.IntVar(&iv, "int", 1, "the int value")
func NewIntVar ¶ added in v0.6.11
func NewIntVar(checkFn comdef.IntCheckFunc) IntVar
NewIntVar create a new IntVar instance with check func
type Ints ¶ added in v0.5.13
type Ints []int
Ints The int flag list, repeatable
implemented flag.Value interface
func (*Ints) IsRepeatable ¶ added in v0.6.7
IsRepeatable on input
type IntsString ¶ added in v0.6.7
type IntsString struct {
// value and size validate
ValueFn func(val int) error
SizeFn func(ln int) error
// contains filtered or unexported fields
}
IntsString The ints-string flag. eg: --get 1,2,3
Implemented the flag.Value interface
func (*IntsString) Set ¶ added in v0.6.7
func (o *IntsString) Set(value string) error
Set new value. eg: "12"
func (*IntsString) String ¶ added in v0.6.7
func (o *IntsString) String() string
String input value to string
type KVString ¶ added in v0.6.6
KVString The kv-string flag, allow input multi.
Implemented the flag.Value interface.
Usage:
type myOpts struct {
vars cflag.KVString
}
var mo &myOpts{ vars: cflag.NewKVString() }
Example:
--var name=inhere => string map {name:inhere}
--var name=inhere --var age=234 => string map {name:inhere, age:234}
func (*KVString) IsRepeatable ¶ added in v0.6.7
IsRepeatable on input
type RepeatableFlag ¶ added in v0.6.7
type RepeatableFlag interface {
// IsRepeatable mark option flag can be set multi times
IsRepeatable() bool
}
RepeatableFlag interface.
type StrVar ¶ added in v0.6.11
type StrVar struct {
// check func
CheckFn comdef.StrCheckFunc
// contains filtered or unexported fields
}
StrVar string value can with a check func
Usage:
sv := cflag.StrVar{}
fs.Var(&sv, "str", "the string value")
func NewStrVar ¶ added in v0.6.11
func NewStrVar(checkFn comdef.StrCheckFunc) StrVar
NewStrVar create a new StrVar with check func
type String ¶ added in v0.5.13
type String string
String a special string
Usage:
// case 1:
var names cflag.String
c.VarOpt(&names, "names", "", "multi name by comma split")
--names "tom,john,joy"
names.Split(",") // -> []string{"tom","john","joy"}
// case 2:
var ids cflag.String
c.VarOpt(&ids, "ids", "", "multi id by comma split")
--names "23,34,56"
names.Ints(",") // -> []int{23,34,56}



