gflag

package
v3.2.4 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: MIT Imports: 24 Imported by: 0

README

Gflag

gflag provide command line options and arguments parse, binding, management.

GoDoc

Please see https://pkg.go.dev/github.com/gookit/gcli/v3

Install

go get github.com/gookit/gcli/v3/gflag

Flags

  • options - start with - or --, and the first character must be a letter
  • arguments - not start with - or --, and after options.
Flag Options
  • Support long option. eg: --long --long value
  • Support short option. eg: -s -a value
  • Support define array option
    • eg: --tag php --tag go will get tag: [php, go]
Flag Arguments
  • Support binding named argument
  • Support define array argument

Usage

package main

import (
	"fmt"
	"os"

	"github.com/gookit/gcli/v3/gflag"
	"github.com/gookit/goutil"
)

var name string

func main() {
	gf := gflag.New("testFlags")
	gf.StrOpt(&name, "name", "n", "", "")

	gf.SetHandle(func(p *gflag.Parser) error {
		fmt.Println(p.Name())
		return nil
	})

	goutil.MustOK(gf.Parse(os.Args[1:]))
}
Run
go run demo.go

Binding methods

Binding cli options
Bool(name, shorts string, defVal bool, desc string) *bool
BoolOpt(ptr *bool, name, shorts string, defVal bool, desc string)
BoolVar(ptr *bool, opt *CliOpt)
Float64Opt(p *float64, name, shorts string, defVal float64, desc string)
Float64Var(ptr *float64, opt *CliOpt)

Int(name, shorts string, defValue int, desc string) *int
Int64(name, shorts string, defValue int64, desc string) *int64
Int64Opt(ptr *int64, name, shorts string, defValue int64, desc string)
Int64Var(ptr *int64, opt *CliOpt)
IntOpt(ptr *int, name, shorts string, defValue int, desc string)
IntVar(ptr *int, opt *CliOpt)

Str(name, shorts string, defValue, desc string) *string
StrOpt(p *string, name, shorts, defValue, desc string)
StrVar(p *string, opt *CliOpt)

Uint(name, shorts string, defVal uint, desc string) *uint
Uint64(name, shorts string, defVal uint64, desc string) *uint64
Uint64Opt(ptr *uint64, name, shorts string, defVal uint64, desc string)
Uint64Var(ptr *uint64, opt *CliOpt)
UintOpt(ptr *uint, name, shorts string, defValue uint, desc string)
UintVar(ptr *uint, opt *CliOpt)

Var(ptr flag.Value, opt *CliOpt)
VarOpt(v flag.Value, name, shorts, desc string)
Binding cli arguments
AddArg(name, desc string, requiredAndArrayed ...bool) *CliArg
AddArgByRule(name, rule string) *CliArg
AddArgument(arg *CliArg) *CliArg
BindArg(arg *CliArg) *CliArg

Documentation

Overview

Package gflag provide command line options and arguments binding, parse, management.

Index

Constants

View Source
const (
	// AlignLeft Align right, padding left
	AlignLeft = strutil.PosRight
	// AlignRight Align left, padding right
	AlignRight = strutil.PosLeft
)
View Source
const (
	// TagRuleNamed struct tag use named k-v rule.
	//
	// eg:
	// 	`flag:"name=int0;shorts=i;required=true;desc=int option message"`
	//	// name contains short name
	//	`flag:"name=int0,i;required=true;desc=int option message"`
	TagRuleNamed uint8 = iota

	// TagRuleSimple struct tag use simple rule.
	// format: "desc;required;default;shorts"
	//
	// eg: `flag:"int option message;required;;i"`
	TagRuleSimple

	// TagRuleField struct tag use field name as flag setting name. TODO
	//
	// eg: `flag:"name,n" desc:"int option message" required:"true" default:"0"`
	TagRuleField
)

Variables

View Source
var DefaultOptWidth = 20

DefaultOptWidth for render help

View Source
var FlagTagName = "flag"

FlagTagName default tag name on struct

Functions

func UnquoteUsage added in v3.2.4

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.

Note: from go flag.UnquoteUsage()

Types

type Argument

type Argument = CliArg

Argument alias of CliArg

type Arguments

type Arguments = CliArgs

Arguments alias of CliArgs

type Booleans

type Booleans = cflag.Booleans

Booleans The bool flag list, implemented flag.Value interface

type CliArg

type CliArg struct {
	*structs.Value

	// Name argument name. it's required
	Name string
	// Desc argument description message
	Desc string

	// ShowName is a name for display help. default is equals to Name.
	ShowName string
	// Required arg is required
	Required bool
	// Arrayed if is array, can allow to accept multi values, and must in last.
	Arrayed bool

	// Handler custom argument value handler on call GetValue()
	Handler func(val any) any
	// Validator you can add a validator, will call it on binding argument value
	Validator func(val any) (any, error)
	// AfterFn after bind value listen func
	AfterFn func(a *CliArg) error
	// contains filtered or unexported fields
}

CliArg a command argument definition

func NewArg

func NewArg(name, desc string, val any, requiredAndArrayed ...bool) *CliArg

NewArg quick create a new command argument

func NewArgument

func NewArgument(name, desc string, requiredAndArrayed ...bool) *CliArg

NewArgument quick create a new command argument

func (*CliArg) Array

func (a *CliArg) Array() (ss []string)

Array alias of the Strings()

func (*CliArg) GetValue

func (a *CliArg) GetValue() any

GetValue get value by custom handler func

func (*CliArg) HasValue

func (a *CliArg) HasValue() bool

HasValue value is empty

func (*CliArg) HelpName

func (a *CliArg) HelpName() string

HelpName for render help message

func (*CliArg) Index

func (a *CliArg) Index() int

Index get argument index in the command

func (*CliArg) Init

func (a *CliArg) Init() *CliArg

Init the argument

func (*CliArg) SetArrayed

func (a *CliArg) SetArrayed() *CliArg

SetArrayed for the argument

func (*CliArg) SetValue

func (a *CliArg) SetValue(val any) error

SetValue set an validated value

func (*CliArg) WithAfterFn added in v3.2.1

func (a *CliArg) WithAfterFn(fn func(a *CliArg) error) *CliArg

WithAfterFn a func to the argument

func (*CliArg) WithArrayed added in v3.2.2

func (a *CliArg) WithArrayed() *CliArg

WithArrayed for the argument

func (*CliArg) WithDefault added in v3.2.0

func (a *CliArg) WithDefault(val any) *CliArg

WithDefault value to the argument

func (*CliArg) WithFn

func (a *CliArg) WithFn(fn func(arg *CliArg)) *CliArg

WithFn a func for config the argument

func (*CliArg) WithValidator

func (a *CliArg) WithValidator(fn func(any) (any, error)) *CliArg

WithValidator set a value validator of the argument

func (*CliArg) WithValue

func (a *CliArg) WithValue(val any) *CliArg

WithValue to the argument

type CliArgs

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

CliArgs definition

func (*CliArgs) AddArg

func (ags *CliArgs) AddArg(name, desc string, requiredAndArrayed ...bool) *CliArg

AddArg binding a named argument for the command.

Notice:

  • Required argument cannot be defined after optional argument
  • Only one array parameter is allowed
  • The (array) argument of multiple values can only be defined at the end

Usage:

cmd.AddArg("name", "description")
cmd.AddArg("name", "description", true) // required
cmd.AddArg("names", "description", true, true) // required and is arrayed

func (*CliArgs) AddArgByRule

func (ags *CliArgs) AddArgByRule(name, rule string) *CliArg

AddArgByRule add an arg by simple string rule.

Format: desc;required;default

func (*CliArgs) AddArgument

func (ags *CliArgs) AddArgument(arg *CliArg) *CliArg

AddArgument binding a named argument for the command.

Notice:

  • Required argument cannot be defined after optional argument
  • Only one array parameter is allowed
  • The (array) argument of multiple values can only be defined at the end

func (*CliArgs) Arg

func (ags *CliArgs) Arg(name string) *CliArg

Arg get arg by defined name.

Usage:

intVal := ags.Arg("name").Int()
strVal := ags.Arg("name").String()
arrVal := ags.Arg("names").Array()

func (*CliArgs) ArgByIndex

func (ags *CliArgs) ArgByIndex(i int) *CliArg

ArgByIndex get named arg by index

func (*CliArgs) Args

func (ags *CliArgs) Args() []*CliArg

Args get all defined argument

func (*CliArgs) BindArg

func (ags *CliArgs) BindArg(arg *CliArg) *CliArg

BindArg alias of the AddArgument()

func (*CliArgs) BuildArgsHelp

func (ags *CliArgs) BuildArgsHelp() string

BuildArgsHelp string

func (*CliArgs) ExtraArgs added in v3.2.0

func (ags *CliArgs) ExtraArgs() []string

ExtraArgs remain extra args after collect parse.

func (*CliArgs) HasArg

func (ags *CliArgs) HasArg(name string) bool

HasArg check named argument is defined

func (*CliArgs) HasArgs

func (ags *CliArgs) HasArgs() bool

HasArgs defined. alias of the HasArguments()

func (*CliArgs) HasArguments

func (ags *CliArgs) HasArguments() bool

HasArguments defined

func (*CliArgs) ParseArgs

func (ags *CliArgs) ParseArgs(args []string) (err error)

ParseArgs parse and binding named arguments from input args

func (*CliArgs) SetName

func (ags *CliArgs) SetName(name string)

SetName for CliArgs

func (*CliArgs) SetValidateNum

func (ags *CliArgs) SetValidateNum(validateNum bool)

SetValidateNum check

func (*CliArgs) String

func (ags *CliArgs) String() string

String build args help string

type CliOpt

type CliOpt struct {

	// Name of flag and description
	Name, Desc string
	// default value for the flag option
	DefVal any

	// Shorts shorthand/alias names. eg: ["o", "a"]
	Shorts []string
	// EnvVar allow set flag value from ENV var
	EnvVar string

	// Hidden the option on help
	Hidden bool
	// Required the option is required
	Required bool
	// Validator support validate the option flag value
	Validator func(val string) error
	// TODO interactive question for collect value
	Question string
	// contains filtered or unexported fields
}

CliOpt define for a flag option

func NewOpt added in v3.2.0

func NewOpt(nameAndShorts, desc string, defVal any, setFns ...CliOptFn) *CliOpt

NewOpt quick create an CliOpt instance

func (*CliOpt) DValue

func (m *CliOpt) DValue() *structs.Value

DValue wrap the default value

func (*CliOpt) Flag

func (m *CliOpt) Flag() *Flag

Flag value

func (*CliOpt) HelpName

func (m *CliOpt) HelpName() string

HelpName for show help

func (*CliOpt) Shorts2String

func (m *CliOpt) Shorts2String(sep ...string) string

Shorts2String join shorts to a string

func (*CliOpt) ShortsString added in v3.2.0

func (m *CliOpt) ShortsString(sep ...string) string

ShortsString join shorts to a string

func (*CliOpt) Validate

func (m *CliOpt) Validate(val string) error

Validate the binding value

func (*CliOpt) WithOptFns added in v3.2.0

func (m *CliOpt) WithOptFns(fns ...CliOptFn) *CliOpt

WithOptFns set for current option

type CliOptFn added in v3.2.0

type CliOptFn func(opt *CliOpt)

CliOptFn opt config func type

func WithDefault added in v3.2.0

func WithDefault(defVal any) CliOptFn

WithDefault value setting for option

func WithRequired added in v3.2.0

func WithRequired() CliOptFn

WithRequired setting for option

func WithShortcut added in v3.2.0

func WithShortcut(shortcut string) CliOptFn

WithShortcut setting for option, multi shortcut use comma separated

func WithShorts added in v3.2.0

func WithShorts(shorts ...string) CliOptFn

WithShorts setting for option

func WithValidator added in v3.2.0

func WithValidator(fn func(val string) error) CliOptFn

WithValidator setting for option

type CliOpts

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

CliOpts cli options management

func (*CliOpts) Bool

func (co *CliOpts) Bool(name, shorts string, defVal bool, desc string) *bool

Bool binding a bool option flag, return pointer

func (*CliOpts) BoolOpt

func (co *CliOpts) BoolOpt(ptr *bool, name, shorts string, defVal bool, desc string)

BoolOpt binding a bool option

func (*CliOpts) BoolOpt2 added in v3.2.0

func (co *CliOpts) BoolOpt2(p *bool, nameAndShorts, desc string, setFns ...CliOptFn)

BoolOpt2 binding a bool option, and allow with CliOptFn for config option.

func (*CliOpts) BoolVar

func (co *CliOpts) BoolVar(ptr *bool, opt *CliOpt)

BoolVar binding a bool option flag

func (*CliOpts) FSet added in v3.2.4

func (co *CliOpts) FSet() *FlagSet

FSet get the raw *flag.FlagSet

func (*CliOpts) Float64Opt

func (co *CliOpts) Float64Opt(p *float64, name, shorts string, defVal float64, desc string)

Float64Opt binding a float64 option

func (*CliOpts) Float64Var

func (co *CliOpts) Float64Var(ptr *float64, opt *CliOpt)

Float64Var binding an float64 option flag

func (*CliOpts) FuncOpt added in v3.2.4

func (co *CliOpts) FuncOpt(nameAndShorts, desc string, fn FuncOptFn, setFns ...CliOptFn)

FuncOpt binding a func option flag

Usage:

cmd.FuncOpt("name", "description ...", func(s string) error {
	// do something ...
	return nil
})

func (*CliOpts) HasOption

func (co *CliOpts) HasOption(name string) bool

HasOption check it is an option name

func (*CliOpts) InitFlagSet

func (co *CliOpts) InitFlagSet()

InitFlagSet create and init flag.FlagSet

func (*CliOpts) Int

func (co *CliOpts) Int(name, shorts string, defVal int, desc string) *int

Int binding an int option flag, return pointer

func (*CliOpts) Int64

func (co *CliOpts) Int64(name, shorts string, defVal int64, desc string) *int64

Int64 binding an int64 option flag, return pointer

func (*CliOpts) Int64Opt

func (co *CliOpts) Int64Opt(ptr *int64, name, shorts string, defValue int64, desc string)

Int64Opt binding an int64 option

func (*CliOpts) Int64Var

func (co *CliOpts) Int64Var(ptr *int64, opt *CliOpt)

Int64Var binding an int64 option flag

func (*CliOpts) IntOpt

func (co *CliOpts) IntOpt(p *int, name, shorts string, defVal int, desc string)

IntOpt binding an int option

func (*CliOpts) IntOpt2 added in v3.2.0

func (co *CliOpts) IntOpt2(p *int, nameAndShorts, desc string, setFns ...CliOptFn)

IntOpt2 binding an int option and with config func.

func (*CliOpts) IntVar

func (co *CliOpts) IntVar(p *int, opt *CliOpt)

IntVar binding an int option flag

func (*CliOpts) IsOption

func (co *CliOpts) IsOption(name string) bool

IsOption check it is an option name

func (*CliOpts) IsShortName

func (co *CliOpts) IsShortName(short string) bool

IsShortName check it is a shortcut name

func (*CliOpts) IsShortOpt

func (co *CliOpts) IsShortOpt(short string) bool

IsShortOpt alias of the IsShortcut()

func (*CliOpts) IterAll

func (co *CliOpts) IterAll(fn func(f *flag.Flag, opt *CliOpt))

IterAll Iteration all flag options with metadata

func (*CliOpts) LookupFlag

func (co *CliOpts) LookupFlag(name string) *Flag

LookupFlag get Flag by name

func (*CliOpts) Opt

func (co *CliOpts) Opt(name string) *CliOpt

Opt get CliOpt by name

func (*CliOpts) Opts

func (co *CliOpts) Opts() map[string]*CliOpt

Opts get all flag options

func (*CliOpts) ParseOpts added in v3.2.4

func (co *CliOpts) ParseOpts(args []string) (err error)

ParseOpts parse options from input args

func (*CliOpts) SetFlagSet added in v3.2.4

func (co *CliOpts) SetFlagSet(fSet *FlagSet)

SetFlagSet set the raw *FlagSet

func (*CliOpts) SetName

func (co *CliOpts) SetName(name string)

SetName for CliArgs

func (*CliOpts) ShortNames

func (co *CliOpts) ShortNames(name string) (ss []string)

ShortNames get all short-names of the option

func (*CliOpts) Str

func (co *CliOpts) Str(name, shorts string, defVal, desc string) *string

Str binding an string option flag, return pointer

func (*CliOpts) StrOpt

func (co *CliOpts) StrOpt(p *string, name, shorts string, defValAndDesc ...string)

StrOpt binding a string option.

If defValAndDesc only one elem, will as desc message.

func (*CliOpts) StrOpt2 added in v3.2.0

func (co *CliOpts) StrOpt2(p *string, nameAndShorts, desc string, setFns ...CliOptFn)

StrOpt2 binding a string option, and allow with CliOptFn for config option.

func (*CliOpts) StrVar

func (co *CliOpts) StrVar(p *string, opt *CliOpt)

StrVar binding an string option flag

func (*CliOpts) Uint

func (co *CliOpts) Uint(name, shorts string, defVal uint, desc string) *uint

Uint binding an int option flag, return pointer

func (*CliOpts) Uint64

func (co *CliOpts) Uint64(name, shorts string, defVal uint64, desc string) *uint64

Uint64 binding an int option flag, return pointer

func (*CliOpts) Uint64Opt

func (co *CliOpts) Uint64Opt(ptr *uint64, name, shorts string, defVal uint64, desc string)

Uint64Opt binding an uint64 option

func (*CliOpts) Uint64Var

func (co *CliOpts) Uint64Var(ptr *uint64, opt *CliOpt)

Uint64Var binding an uint option flag

func (*CliOpts) UintOpt

func (co *CliOpts) UintOpt(ptr *uint, name, shorts string, defValue uint, desc string)

UintOpt binding an uint option

func (*CliOpts) UintVar

func (co *CliOpts) UintVar(ptr *uint, opt *CliOpt)

UintVar binding an uint option flag

func (*CliOpts) Var

func (co *CliOpts) Var(ptr flag.Value, opt *CliOpt)

Var binding an custom var option flag

func (*CliOpts) VarOpt

func (co *CliOpts) VarOpt(v flag.Value, name, shorts, desc string)

VarOpt binding a custom var option

Usage:

var names gcli.Strings
cmd.VarOpt(&names, "tables", "t", "description ...")

func (*CliOpts) VarOpt2 added in v3.2.2

func (co *CliOpts) VarOpt2(v flag.Value, nameAndShorts, desc string, setFns ...CliOptFn)

VarOpt2 binding an int option and with config func.

type ConfString added in v3.2.1

type ConfString = cflag.ConfString

ConfString The config-string flag, INI format, like nginx-config.

type Config

type Config struct {
	// WithoutType don't display flag data type on print help
	WithoutType bool
	// DescNewline flag desc at new line on print help
	DescNewline bool
	// Alignment flag name align left or right. default is: left
	Alignment strutil.PosFlag
	// TagName on struct. default is FlagTagName
	TagName string
	// TagRuleType for struct tag value. default is TagRuleNamed
	TagRuleType uint8
	// DisableArg disable binding arguments.
	DisableArg bool
	// IndentLongOpt indent long option name on print help
	IndentLongOpt bool
	// EnhanceShort enhance short option parse. TODO
	//
	// 	0 - none
	// 	1 - multi short bool options. eg: `-aux` = `-a -u -x`
	// 	2 - allow name with value as one node. eg: `-Ostdout` = `-O stdout`
	EnhanceShort uint8
}

Config for render help information

func (*Config) GetTagName added in v3.2.2

func (c *Config) GetTagName() string

GetTagName get tag name, default is FlagTagName

type ConfigFunc added in v3.2.2

type ConfigFunc func(cfg *Config)

ConfigFunc config func for parser

func WithIndentLongOpt added in v3.2.2

func WithIndentLongOpt(yes bool) ConfigFunc

WithIndentLongOpt on print help

type EnumString

type EnumString = cflag.EnumString

EnumString The string flag list, implemented flag.Value interface

type Flag added in v3.2.4

type Flag = flag.Flag

Flag type. alias of flag.Flag

type FlagSet added in v3.2.4

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

FlagSet custom implement flag set, like flag.FlagSet. But support short names for options.

func NewFlagSet added in v3.2.4

func NewFlagSet(name string, errorHandling flag.ErrorHandling) *FlagSet

NewFlagSet create a new FlagSet

func (*FlagSet) Arg added in v3.2.4

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 added in v3.2.4

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

Args returns the non-flag arguments.

func (*FlagSet) Bool added in v3.2.4

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

Bool defines a bool flag with specified name, default value, and usage string. from the go flag.Bool()

func (*FlagSet) BoolVar added in v3.2.4

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

BoolVar defines a bool flag with specified name, default value, and usage string. from the go flag.BoolVar()

func (*FlagSet) Duration added in v3.2.4

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. from the go flag.Duration()

func (*FlagSet) DurationVar added in v3.2.4

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

DurationVar defines a time.Duration flag with specified name, default value, and usage string. from the go flag.DurationVar()

func (*FlagSet) Float64 added in v3.2.4

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

Float64 defines a float64 flag with specified name, default value, and usage string. from the go flag.Float64()

func (*FlagSet) Float64Var added in v3.2.4

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

Float64Var defines a float64 flag with specified name, default value, and usage string. from the go flag.Float64Var()

func (*FlagSet) Func added in v3.2.4

func (f *FlagSet) Func(name, usage string, fn func(string) error) *Flag

Func defines a flag with the specified name and usage string. from the go flag.Func()

func (*FlagSet) Int added in v3.2.4

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

Int defines an int flag with specified name, default value, and usage string. from the go flag.Int()

func (*FlagSet) Int64 added in v3.2.4

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

Int64 defines an int64 flag with specified name, default value, and usage string. from the go flag.Int64()

func (*FlagSet) Int64Var added in v3.2.4

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

Int64Var defines an int64 flag with specified name, default value, and usage string. from the go flag.Int64Var()

func (*FlagSet) IntVar added in v3.2.4

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

IntVar defines an int flag with specified name, default value, and usage string. from the go flag.IntVar()

func (*FlagSet) Lookup added in v3.2.4

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

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

func (*FlagSet) NFlag added in v3.2.4

func (f *FlagSet) NFlag() int

NFlag returns the number of flags that have been set.

func (*FlagSet) Parse added in v3.2.4

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.

NOTE: refer from flag.FlagSet#Parse()

func (*FlagSet) Parsed added in v3.2.4

func (f *FlagSet) Parsed() bool

Parsed reports whether f.Parse has been called.

func (*FlagSet) Set added in v3.2.4

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

Set sets the value of the named flag.

func (*FlagSet) String added in v3.2.4

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

String defines a string flag with specified name, default value, and usage string. from the go flag.String()

func (*FlagSet) StringVar added in v3.2.4

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

StringVar defines a string flag with specified name, default value, and usage string. from the go flag.StringVar()

func (*FlagSet) TextVar added in v3.2.4

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

TextVar defines a text flag with specified name, default value, and usage string. from the go flag.TextVar()

func (*FlagSet) Uint added in v3.2.4

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

Uint defines a uint flag with specified name, default value, and usage string. from the go flag.Uint()

func (*FlagSet) Uint64 added in v3.2.4

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

Uint64 defines a uint64 flag with specified name, default value, and usage string. from the go flag.Uint64()

func (*FlagSet) Uint64Var added in v3.2.4

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

Uint64Var defines a uint64 flag with specified name, default value, and usage string. from the go flag.Uint64Var()

func (*FlagSet) UintVar added in v3.2.4

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

UintVar defines a uint flag with specified name, default value, and usage string. from the go flag.UintVar()

func (*FlagSet) Var added in v3.2.4

func (f *FlagSet) Var(value Value, name string, usage string) *Flag

Var defines a flag with the specified name and usage string. from the go flag.Var()

func (*FlagSet) VisitAll added in v3.2.4

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 struct {
	// --- cli options ---
	CliOpts
	// --- cli arguments ---
	CliArgs

	// Desc message
	Desc string
	// AfterParse options hook
	AfterParse func(fs *Flags) error

	// HandleFunc handle func, will call on Run()
	HandleFunc HandleFunc
	// contains filtered or unexported fields
}

Flags cli flag options and arguments management, parsing, and binding.

func New

func New(nameWithDesc ...string) *Flags

New create a new Parser and init it.

type FuncOptFn added in v3.2.4

type FuncOptFn func(string) error

FuncOptFn func option flag func type

type HandleFunc

type HandleFunc func(fs *Flags) error

HandleFunc type

type Ints

type Ints = cflag.Ints

Ints The int flag list, implemented flag.Value interface

type IntsString added in v3.2.2

type IntsString = cflag.IntsString

IntsString implemented flag.Value interface

type KVString added in v3.2.1

type KVString = cflag.KVString

KVString The key-value string flag, repeatable.

type OptCategory

type OptCategory struct {
	Name, Title string
	OptNames    []string
}

OptCategory struct

type Parser

type Parser = Flags

Parser type, alias of Flags type

func (*Parser) BuildHelp

func (p *Parser) BuildHelp() string

BuildHelp string for all flag options

func (*Parser) BuildOptsHelp

func (p *Parser) BuildOptsHelp() string

BuildOptsHelp string.

func (*Parser) FSetArgs

func (p *Parser) FSetArgs() []string

FSetArgs get all raw arguments. alias of the RawArgs() if have been called parse, the return is remaining args.

func (*Parser) FlagNames

func (p *Parser) FlagNames() map[string]int

FlagNames return all option names

func (*Parser) FromStruct

func (p *Parser) FromStruct(ptr any, ruleType ...uint8) (err error)

FromStruct from struct tag binding options

## Named rule(default)

// tag format: name=val0;shorts=i;required=true;desc=a message
type UserCmdOpts struct {
	Name string `flag:"name=name;shorts=n;required=true;desc=input username"`
	Age int `flag:"name=age;shorts=a;required=true;desc=input user age"`
}
opt := &UserCmdOpts{}
p.FromStruct(opt)

## Simple rule

// tag format1: name;desc;required;default;shorts
// tag format2: desc;required;default;shorts
type UserCmdOpts struct {
	Name string `flag:"input username;true;;n"`
	Age int `flag:"age;input user age;true;;o"`
}
opt := &UserCmdOpts{}
p.FromStruct(opt, gflag.TagRuleSimple)

func (*Parser) Init

func (p *Parser) Init(name string)

Init for parser

func (*Parser) Len

func (p *Parser) Len() int

Len of the Flags

func (*Parser) MustFromStruct added in v3.2.2

func (p *Parser) MustFromStruct(ptr any, ruleType ...uint8)

MustFromStruct from struct tag binding options, panic if error

more see FromStruct()

func (*Parser) Name

func (p *Parser) Name() string

Name of the Flags

func (*Parser) Parse

func (p *Parser) Parse(args []string) (err error)

Parse given arguments

Usage:

gf := gflag.New()
gf.BoolOpt(&debug, "debug", "", defDebug, "open debug mode")
gf.UintOpt(&port, "port", "p", 18081, "the http server port")

err := gf.Parse(os.Args[1:])

func (*Parser) ParserCfg added in v3.2.2

func (p *Parser) ParserCfg() *Config

ParserCfg for the parser.

func (*Parser) PrintHelpPanel

func (p *Parser) PrintHelpPanel()

PrintHelpPanel for all options to the gf.out

func (*Parser) RawArg

func (p *Parser) RawArg(i int) string

RawArg get an argument value by index

func (*Parser) RawArgs

func (p *Parser) RawArgs() []string

RawArgs get all raw arguments. if have been called parse, the return is remaining args.

func (*Parser) Required

func (p *Parser) Required(names ...string)

Required flag option name(s)

func (*Parser) Run

func (p *Parser) Run(args []string)

Run parse options and arguments, and HandleFunc help render

Usage:

	gf := gflag.New()
 ...
	// OR: gf.Run(nil)
	gf.Run(os.Args)

func (*Parser) SetConfig

func (p *Parser) SetConfig(opt *Config)

SetConfig for the object.

func (*Parser) SetHandle

func (p *Parser) SetHandle(fn HandleFunc) *Flags

SetHandle func

func (*Parser) SetHelpRender

func (p *Parser) SetHelpRender(fn func())

SetHelpRender set the raw *flag.FlagSet.Usage

func (*Parser) SetName

func (p *Parser) SetName(name string)

SetName for parser

func (*Parser) SetOutput

func (p *Parser) SetOutput(out io.Writer)

SetOutput for the Flags

func (*Parser) SetRuleType added in v3.2.2

func (p *Parser) SetRuleType(rt uint8) *Parser

SetRuleType for the parse tag value rule string.

func (*Parser) String

func (p *Parser) String() string

String for all flag options

func (*Parser) UseSimpleRule

func (p *Parser) UseSimpleRule() *Parser

UseSimpleRule for the parse tag value rule string. see TagRuleSimple

func (*Parser) WithConfigFn

func (p *Parser) WithConfigFn(fns ...ConfigFunc) *Parser

WithConfigFn for the object.

type String added in v3.2.2

type String = cflag.String

String The special string flag, implemented flag.Value interface

type Strings

type Strings = cflag.Strings

Strings The string flag list, implemented flag.Value interface

type ValidValue added in v3.2.4

type ValidValue struct {
	flag.Value
	Validator func(val string) error
}

ValidValue is a flag.Value with a validation function.

func (*ValidValue) Set added in v3.2.4

func (v *ValidValue) Set(s string) error

Set value and validate

type Value added in v3.2.4

type Value = flag.Value

Value is the interface to the dynamic value stored in a flag.

alias of flag.Value

Jump to

Keyboard shortcuts

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