flagly

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2021 License: MIT Imports: 10 Imported by: 18

README

flagly

Software License Build Status GoDoc codebeat badge

The easier way to parsing command-line flag in Golang, also building a command line app.

It can also provides shell-like interactives by using readline (demo: flagly-shell)

Usage

go get github.com/chzyer/flagly

binding

type Config struct {
	Verbose bool   `name:"v" desc:"be more verbose"`
	Name    string `type:"[0]"`
}

func NewConfig() *Config {
	var cfg Config
	flagly.Bind(&cfg)
	return &cfg
}

func main() {
	cfg := NewConfig()
	fmt.Printf("config: %+v\n", cfg)
}

source file: flagly-binding

$ go install github.com/chzyer/flagly/demo/flagly-binding
$ flagly-binding -v name
config: &{Verbose:true Name:name}

routing

type Git struct {
	Version bool `name:"v" desc:"show version"`
	
	// sub handlers
	Clone *GitClone `flagly:"handler"`
	Init  *GitInit  `flagly:"handler"`
}

type GitClone struct {
	Parent *Git `flagly:"parent"`

	Verbose  bool   `name:"v" desc:"be more verbose"`
	Quiet    bool   `name:"q" desc:"be more quiet"`
	Progress bool   `name:"progress" desc:"force progress reporting"`
	Template string `arg:"template-directory"`

	Repo string `name:"[0]"`
	Dir  string `name:"[1]" default:""`
}

func (g *GitClone) FlaglyHandle() error {
	if g.Repo == "" {
		return flagly.ErrShowUsage
	}
	fmt.Printf("git clone %+v %+v\n", g.Parent, g)
	return nil
}

func (g *GitClone) FlaglyDesc() string {
	return "Create an empty Git repository or reinitialize an existing one"
}

type GitInit struct {
	Quiet bool `name:"q" desc:"be quiet"`
}

func (g *GitInit) FlaglyDesc() string {
	return "Clone a repository into a new directory"
}

func main() {
	var git Git
	flagly.Run(&git)
}

source file: flagly-git

$ go install github.com/chzyer/flagly/demo/flagly-git
$ flagly-git

usage: flagly-git [option] <command>

options:
    -v                  show version
    -h                  show help

commands:
    clone               Create an empty Git repository or reinitialize an existing one
    init                Clone a repository into a new directory
	
$ flagly-get -v clone -h

usage: flagly-git [flagly-git option] clone [option] [--] <repo> [<dir>]

options:
    -v                  be more verbose
    -q                  be more quiet
    -progress           force progress reporting
    -template <template-directory>
                        directory from which templates will be used
    -h                  show help

flagly-git options:
    -v                  show version
    -h                  show help
	
$ flagly-git -v clone repoName

git clone
    &{Version:true Clone:<nil> Init:<nil> Add:<nil>}
    &{Parent:0xc20801e220 Verbose:false Quiet:false Progress:false Template: Repo:repoName Dir:}

Feedback

If you have any questions, please submit a github issue and any pull requests is welcomed :)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMustAFunc         = errors.New("argument must be a func")
	ErrFuncOutMustAError = errors.New("FlaglyHandle(Context).out must be a error or nothing: %v")

	ErrMustAPtrToStruct = errors.New("must a pointer to struct")
	ErrMustAStruct      = errors.New("must a struct")
)
View Source
var (
	EmptyError  error
	EmptyType   reflect.Type
	EmptyValue  reflect.Value
	IfaceError  = reflect.TypeOf(&EmptyError).Elem()
	HandlerType = reflect.TypeOf(new(Handler))
)
View Source
var (
	ErrShowUsage error = showUsageError{}
)
View Source
var (
	FlaglyIniterName = "FlaglyInit"
)
View Source
var (
	NilValue reflect.Value
)

Functions

func Bind

func Bind(target interface{})

func BindByArgs

func BindByArgs(target interface{}, args []string) error

func Error

func Error(info string) error

func Errorf

func Errorf(format string, obj ...interface{}) error

func Exit

func Exit(info interface{})

func GetIdxInArray

func GetIdxInArray(s string) int

func GetMethod

func GetMethod(s reflect.Value, name string) reflect.Value

func IsImplementDescer

func IsImplementDescer(t reflect.Type) bool

func IsImplementIniter

func IsImplementIniter(t reflect.Type) bool

func IsImplementVerifier

func IsImplementVerifier(t reflect.Type) bool

func IsImplemented

func IsImplemented(t, target reflect.Type) bool

func IsShowUsage

func IsShowUsage(err error) *showUsageError

func IsWrapBy

func IsWrapBy(s, ch2 string) bool

func Register

func Register(objs ...Typer)

func RegisterAll

func RegisterAll(objs ...BaseTyperParser)

func Run

func Run(target interface{}, context ...interface{})

func RunByArgs

func RunByArgs(target interface{}, args []string, context ...interface{}) error

func SetDesc

func SetDesc(target interface{}, desc string)

func SetToSource

func SetToSource(source, val reflect.Value)

func ShowUsage

func ShowUsage(hs []*Handler) string

Types

type BaseTypeArgNamer

type BaseTypeArgNamer interface {
	ArgName() string
}

type BaseTypeCanBeValuer

type BaseTypeCanBeValuer interface {
	CanBeValue(arg string) bool
}

type BaseTypeNumArgs

type BaseTypeNumArgs interface {
	NumArgs() (int, int)
}

type BaseTyper

type BaseTyper interface {
	Type() reflect.Type
}

type BaseTyperParser

type BaseTyperParser interface {
	BaseTyper
	ParseArgs(args []string) (reflect.Value, error)
}

type Bool

type Bool struct{}

func (Bool) CanBeValue

func (Bool) CanBeValue(arg string) bool

func (Bool) NumArgs

func (Bool) NumArgs() (int, int)

func (Bool) ParseArgs

func (Bool) ParseArgs(args []string) (reflect.Value, error)

func (Bool) Type

func (Bool) Type() reflect.Type

type CmdHelp

type CmdHelp struct{}

func (CmdHelp) FlaglyDesc

func (CmdHelp) FlaglyDesc() string

func (CmdHelp) FlaglyHandle

func (CmdHelp) FlaglyHandle(h *Handler) error

type Duration

type Duration struct{}

func (Duration) CanBeValue

func (Duration) CanBeValue(string) bool

func (Duration) NumArgs

func (Duration) NumArgs() (int, int)

func (Duration) ParseArgs

func (Duration) ParseArgs(args []string) (reflect.Value, error)

func (Duration) Type

func (Duration) Type() reflect.Type

type FlaglyDescer

type FlaglyDescer interface {
	FlaglyDesc() string
}

type FlaglyIniter

type FlaglyIniter interface {
	FlaglyInit()
}

type FlaglySet

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

func Compile

func Compile(name string, target interface{}) (*FlaglySet, error)

func New

func New(name string) *FlaglySet

func (*FlaglySet) Add

func (f *FlaglySet) Add(h *Handler)

func (*FlaglySet) AddSubHandler

func (f *FlaglySet) AddSubHandler(command string, hf interface{}) *Handler

func (*FlaglySet) Bind

func (f *FlaglySet) Bind(value reflect.Value, args []string) error

func (*FlaglySet) Close

func (f *FlaglySet) Close()

func (*FlaglySet) Compile

func (f *FlaglySet) Compile(target interface{}) error

func (*FlaglySet) Completer

func (f *FlaglySet) Completer() *HandlerCompleter

func (*FlaglySet) Context

func (f *FlaglySet) Context(obj ...interface{})

func (*FlaglySet) GetHandler

func (f *FlaglySet) GetHandler(name string) *Handler

func (*FlaglySet) Lambda

func (f *FlaglySet) Lambda(name string, fn func() []string)

func (*FlaglySet) Run

func (f *FlaglySet) Run(args []string) (err error)

func (*FlaglySet) SetHandleFunc

func (f *FlaglySet) SetHandleFunc(hf interface{})

func (*FlaglySet) Usage

func (f *FlaglySet) Usage() string

type FlaglyVerifier

type FlaglyVerifier interface {
	FlaglyVerify() error
}

type Handler

type Handler struct {
	Parent   *Handler
	Name     string
	Desc     string
	Children []*Handler

	Options    []*Option
	OptionType reflect.Type
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(name string) *Handler

func NewHandlerHelp

func NewHandlerHelp() *Handler

func (*Handler) AddHandler

func (h *Handler) AddHandler(child *Handler)

func (*Handler) AddSubHandler

func (h *Handler) AddSubHandler(name string, function interface{}) *Handler

combine NewHander(name).SetHanderFunc()/AddHandler(subHandler)

func (*Handler) Bind

func (h *Handler) Bind(ptr reflect.Value, args []string) (err error)

func (*Handler) Call

func (h *Handler) Call(stack []reflect.Value, args []string) error

func (*Handler) Close

func (h *Handler) Close()

func (*Handler) Compile

func (h *Handler) Compile(t reflect.Type) error

func (*Handler) CompileIface

func (h *Handler) CompileIface(obj interface{}) error

func (*Handler) Context

func (h *Handler) Context(obj interface{})

func (*Handler) EnsureHelpOption

func (h *Handler) EnsureHelpOption()

func (*Handler) GetChildren

func (h *Handler) GetChildren() []*Handler

func (*Handler) GetCommands

func (h *Handler) GetCommands() []string

func (*Handler) GetHandler

func (h *Handler) GetHandler(name string) *Handler

func (*Handler) GetName

func (h *Handler) GetName() string

func (*Handler) GetOptionNames

func (h *Handler) GetOptionNames() []string

func (*Handler) GetRoot

func (h *Handler) GetRoot() *Handler

func (*Handler) GetTreeChildren

func (h *Handler) GetTreeChildren() []Tree

func (*Handler) HasArgOptions

func (h *Handler) HasArgOptions() bool

func (*Handler) HasDesc

func (h *Handler) HasDesc() bool

func (*Handler) HasFlagOptions

func (h *Handler) HasFlagOptions() bool

func (*Handler) Lambda

func (h *Handler) Lambda(name string, fn func() []string)

func (*Handler) ResetHandler

func (h *Handler) ResetHandler()

func (*Handler) Run

func (h *Handler) Run(stack *[]reflect.Value, args []string) (err error)

func (*Handler) SetGetChildren

func (h *Handler) SetGetChildren(f func(*Handler) []*Handler)

func (*Handler) SetHandleFunc

func (h *Handler) SetHandleFunc(obj interface{})

only func is accepted 1. func() error 2. func(*struct) error 3. func(*struct, *flagly.Handler) error 4. func(*flagly.Handler) error 5. func(Handler, Context) error

func (*Handler) SetOnExit

func (h *Handler) SetOnExit(f func())

func (*Handler) SetOptionType

func (h *Handler) SetOptionType(option reflect.Type) error

func (*Handler) String

func (h *Handler) String() string

func (*Handler) Usage

func (h *Handler) Usage(prefix string) string

func (*Handler) UsagePrefix

func (h *Handler) UsagePrefix() string

type HandlerCompleter

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

func (*HandlerCompleter) DoSegment

func (hc *HandlerCompleter) DoSegment(seg [][]rune, n int) [][]rune

type IPNet

type IPNet struct{}

func (IPNet) CanBeValue

func (IPNet) CanBeValue(string) bool

func (IPNet) NumArgs

func (IPNet) NumArgs() (int, int)

func (IPNet) ParseArgs

func (IPNet) ParseArgs(args []string) (reflect.Value, error)

func (IPNet) Type

func (IPNet) Type() reflect.Type

type Int

type Int struct{}

func (Int) ArgName

func (Int) ArgName() string

func (Int) ParseArgs

func (Int) ParseArgs(args []string) (reflect.Value, error)

func (Int) Type

func (Int) Type() reflect.Type

type Int64

type Int64 struct{}

func (Int64) ArgName

func (Int64) ArgName() string

func (Int64) ParseArgs

func (Int64) ParseArgs(args []string) (reflect.Value, error)

func (Int64) Type

func (Int64) Type() reflect.Type

type MapStringString

type MapStringString struct{}

func (MapStringString) ArgName

func (MapStringString) ArgName() string

func (MapStringString) CanBeValue

func (MapStringString) CanBeValue(string) bool

func (MapStringString) NumArgs

func (MapStringString) NumArgs() (int, int)

func (MapStringString) Set

func (MapStringString) Set(source reflect.Value, args []string) error

func (MapStringString) Type

func (MapStringString) Type() reflect.Type

type Option

type Option struct {
	Index     int
	Name      string
	LongName  string
	Type      OptionType
	BindType  reflect.Type
	Typer     Typer
	Desc      string
	Default   *string
	ArgName   *string
	ArgIdx    int
	ShowUsage bool
	Tag       StructTag
}

func NewArg

func NewArg(name string, idx int, bind reflect.Type) (*Option, error)

func NewFlag

func NewFlag(name string, bind reflect.Type) (*Option, error)

func NewHelpFlag

func NewHelpFlag() *Option

func ParseStructToOptions

func ParseStructToOptions(h *Handler, t reflect.Type) (ret []*Option, err error)

func (*Option) BindTo

func (o *Option) BindTo(value reflect.Value, args []string) error

func (*Option) GetTree

func (o *Option) GetTree(lambdaMap map[string]func() []string) []Tree

func (*Option) HasArgName

func (o *Option) HasArgName() bool

func (*Option) HasDefault

func (o *Option) HasDefault() bool

func (*Option) HasDesc

func (o *Option) HasDesc() bool

func (*Option) IsArg

func (o *Option) IsArg() bool

func (*Option) IsFlag

func (o *Option) IsFlag() bool

func (*Option) String

func (o *Option) String() string

type OptionType

type OptionType int
const (
	FlagOption OptionType = iota
	ArgOption
)

func (OptionType) String

func (t OptionType) String() string

type SliceWrap

type SliceWrap struct {
	BaseTyperParser
}

func (SliceWrap) CanBeValue

func (s SliceWrap) CanBeValue(arg string) bool

func (SliceWrap) NumArgs

func (s SliceWrap) NumArgs() (int, int)

func (SliceWrap) Set

func (s SliceWrap) Set(source reflect.Value, args []string) error

func (SliceWrap) Type

func (s SliceWrap) Type() reflect.Type

type String

type String struct{}

func (String) CanBeValue

func (String) CanBeValue(string) bool

func (String) NumArgs

func (String) NumArgs() (int, int)

func (String) ParseArgs

func (String) ParseArgs(args []string) (reflect.Value, error)

func (String) Type

func (String) Type() reflect.Type

type StructTag

type StructTag string

func (StructTag) Flagly

func (st StructTag) Flagly() []string

func (StructTag) FlaglyHas

func (st StructTag) FlaglyHas(name string) bool

func (StructTag) Get

func (st StructTag) Get(name string) string

func (StructTag) GetName

func (st StructTag) GetName() string

func (StructTag) GetPtr

func (st StructTag) GetPtr(name string) *string

func (StructTag) Has

func (st StructTag) Has(name string) bool

type Tree

type Tree interface {
	GetName() string
	GetTreeChildren() []Tree
}

func StringTree

func StringTree(name string) Tree

type Typer

type Typer interface {
	BaseTyper
	BaseTypeNumArgs
	BaseTypeCanBeValuer
	Set(source reflect.Value, args []string) error
}

func GetTyper

func GetTyper(t reflect.Type) (Typer, error)

type ValueWrap

type ValueWrap struct{ BaseTyperParser }

func (ValueWrap) ArgName

func (b ValueWrap) ArgName() string

func (ValueWrap) CanBeValue

func (b ValueWrap) CanBeValue(arg string) bool

func (ValueWrap) NumArgs

func (b ValueWrap) NumArgs() (int, int)

func (ValueWrap) Set

func (b ValueWrap) Set(source reflect.Value, args []string) error

Directories

Path Synopsis
demo
flagly-shell
usage: $ go install github.com/chzyer/flagly/demo/flagly-shell $ flagly-shell > help commands: help time base64 > time 2016-02-11 12:12:43 > time -h usage: time [option] [--] [<layout>] options: -h show help > base64 missing content usage: base64 [option] [--] <content> options: -d decode string -h show help > base64 hello aGVsbG8=
usage: $ go install github.com/chzyer/flagly/demo/flagly-shell $ flagly-shell > help commands: help time base64 > time 2016-02-11 12:12:43 > time -h usage: time [option] [--] [<layout>] options: -h show help > base64 missing content usage: base64 [option] [--] <content> options: -d decode string -h show help > base64 hello aGVsbG8=

Jump to

Keyboard shortcuts

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