gflag

package
v3.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2022 License: MIT Imports: 19 Imported by: 0

README

Gflag

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

GoDoc

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

Install

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

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

	// TagRuleNamed struct tag use named k-v rule.
	//
	// eg: `flag:"name=int0;shorts=i;required=true;desc=int option message"`
	TagRuleNamed = 0

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

Variables

View Source
var FlagTagName = "flag"

FlagTagName default tag name on struct

Functions

func ParseSimpleRule

func ParseSimpleRule(name, rule string) (mp map[string]string)

ParseSimpleRule struct tag value use simple rule. each item split by ';'

  • format: "name;desc;required;default;shorts"
  • format: "desc;required;default;shorts"

eg:

"int option message;required;i"
"opt-name;int option message;;a,b"
"int option message;;a,b;23"

returns field name:

name
desc
shorts
required
default

TODO use structs.ParseTagValueDefine() and support name.

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)
	// 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 the argument

func (*CliArg) SetValue

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

SetValue set an validated value

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

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) 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 for CliArgs

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

	// short 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 (*CliOpt) DValue

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

DValue wrap the default value

func (*CliOpt) Flag

func (m *CliOpt) Flag() *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) Validate

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

Validate the binding value

type CliOpts

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

CliOpts cli options management

func (*CliOpts) Bool

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

Bool binding a bool option flag, return pointer

func (*CliOpts) BoolOpt

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

BoolOpt binding a bool option

func (*CliOpts) BoolVar

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

BoolVar binding a bool option flag

func (*CliOpts) Float64Opt

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

Float64Opt binding a float64 option

func (*CliOpts) Float64Var

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

Float64Var binding an float64 option flag

func (*CliOpts) HasOption

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

HasOption check it is an option name

func (*CliOpts) InitFlagSet

func (ops *CliOpts) InitFlagSet(name string)

InitFlagSet create and init flag.FlagSet

func (*CliOpts) Int

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

Int binding an int option flag, return pointer

func (*CliOpts) Int64

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

Int64 binding an int64 option flag, return pointer

func (*CliOpts) Int64Opt

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

Int64Opt binding an int64 option

func (*CliOpts) Int64Var

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

Int64Var binding an int64 option flag

func (*CliOpts) IntOpt

func (ops *CliOpts) IntOpt(ptr *int, name, shorts string, defVal int, desc string)

IntOpt binding an int option

func (*CliOpts) IntVar

func (ops *CliOpts) IntVar(ptr *int, opt *CliOpt)

IntVar binding an int option flag

func (*CliOpts) IsOption

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

IsOption check it is an option name

func (*CliOpts) IsShortName

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

IsShortName check it is a shortcut name

func (*CliOpts) IsShortOpt

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

IsShortOpt alias of the IsShortcut()

func (*CliOpts) IterAll

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

IterAll Iteration all flag options with metadata

func (*CliOpts) LookupFlag

func (ops *CliOpts) LookupFlag(name string) *flag.Flag

LookupFlag get flag.Flag by name

func (*CliOpts) Opt

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

Opt get CliOpt by name

func (*CliOpts) Opts

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

Opts get all flag options

func (*CliOpts) SetName

func (ops *CliOpts) SetName(name string)

SetName for CliArgs

func (*CliOpts) ShortNames

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

ShortNames get all short-names of the option

func (*CliOpts) Str

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

Str binding an string option flag, return pointer

func (*CliOpts) StrOpt

func (ops *CliOpts) StrOpt(p *string, name, shorts string, defValWithDesc ...string)

StrOpt binding an string option

func (*CliOpts) StrVar

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

StrVar binding an string option flag

func (*CliOpts) Uint

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

Uint binding an int option flag, return pointer

func (*CliOpts) Uint64

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

Uint64 binding an int option flag, return pointer

func (*CliOpts) Uint64Opt

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

Uint64Opt binding an uint64 option

func (*CliOpts) Uint64Var

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

Uint64Var binding an uint option flag

func (*CliOpts) UintOpt

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

UintOpt binding an uint option

func (*CliOpts) UintVar

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

UintVar binding an uint option flag

func (*CliOpts) Var

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

Var binding an custom var option flag

func (*CliOpts) VarOpt

func (ops *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 ...")

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 uint8
	// TagName on struct
	TagName string
	// TagRuleType for struct tag value. default is TagRuleNamed
	TagRuleType uint8
	// DisableArg disable binding arguments.
	DisableArg bool
}

Config for render help information

type EnumString

type EnumString = cflag.EnumString

EnumString The string flag list, implemented flag.Value interface

type Flags

type Flags = Parser

Flags type

type HandleFunc

type HandleFunc func(p *Parser) error

HandleFunc type

type Ints

type Ints = cflag.Ints

Ints The int flag list, implemented flag.Value interface

type OptCategory

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

OptCategory struct

type Parser

type Parser struct {
	// --- cli options ---
	CliOpts

	// --- cli arguments ---
	CliArgs

	// Desc message
	Desc string
	// AfterParse options hook
	AfterParse func(fs *Parser) error
	// contains filtered or unexported fields
}

Parser cli flag options and arguments binding management and parsing.

func New

func New(nameWithDesc ...string) *Parser

New create a new Parser

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

func (p *Parser) FSet() *flag.FlagSet

FSet get the raw *flag.FlagSet

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

FromStruct from struct tag binding options

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) 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) 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 flags parse and handle 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) SetFlagSet

func (p *Parser) SetFlagSet(fSet *flag.FlagSet)

SetFlagSet set the raw *flag.FlagSet

func (*Parser) SetHandle

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

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) 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 ...func(cfg *Config)) *Parser

WithConfigFn for the object.

type Strings

type Strings = cflag.Strings

Strings The string flag list, implemented flag.Value interface

Jump to

Keyboard shortcuts

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