gcli

package module
v3.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2022 License: MIT Imports: 27 Imported by: 19

README

GCli

GitHub go.mod Go version Actions Status GitHub tag (latest SemVer) Codacy Badge GoDoc Go Report Card Coverage Status

A simple and easy-to-use command-line application and tool library written in Golang. Including running commands, color styles, data display, progress display, interactive methods, etc.

中文说明

中文说明请看 README.zh-CN

Screenshots

app-cmd-list

Features

  • Rich in functions and easy to use
  • Support for adding multiple commands and supporting command aliases
  • Support binding command options from structure
    • example flag:"name=int0;shorts=i;required=true;desc=int option message"
  • Support for adding multi-level commands, each level of command supports binding its own options
  • option/flag - support option binding --long, support for adding short options(-s)
    • POSIX-style short flag combining (-a -b = -ab)
    • Support setting Required, indicating a required option parameter
    • Support setting Validator, which can customize the validation input parameters
  • argument - support binding argument to specify name
    • Support required, optional, array settings
    • It will be automatically detected and collected when the command is run.
  • colorable - supports rich color output. provide by gookit/color
    • Supports html tab-style color rendering, compatible with Windows
    • Built-in info, error, success, danger and other styles, can be used directly
  • interact Built-in user interaction methods: ReadLine, Confirm, Select, MultiSelect ...
  • progress Built-in progress display methods: Txt, Bar, Loading, RoundTrip, DynamicText ...
  • Automatically generate command help information and support color display
  • When the command entered is incorrect, a similar command will be prompted(including an alias prompt)
  • Supports generation of zsh and bash command completion script files
  • Supports a single command as a stand-alone application

Flag Options:

  • Options start with - or --, and the first character must be a letter
  • 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 arguemnt
  • Support define array argument

GoDoc

Install

go get github.com/gookit/gcli/v3

Quick start

an example for quick start:

package main

import (
    "github.com/gookit/gcli/v3"
    "github.com/gookit/gcli/v3/_examples/cmd"
)

// for test run: go build ./_examples/cliapp.go && ./cliapp
func main() {
    app := gcli.NewApp()
    app.Version = "1.0.3"
    app.Desc = "this is my cli application"
    // app.SetVerbose(gcli.VerbDebug)

    app.Add(cmd.Example)
    app.Add(&gcli.Command{
        Name: "demo",
        // allow color tag and {$cmd} will be replace to 'demo'
        Desc: "this is a description <info>message</> for {$cmd}", 
        Subs: []*gcli.Command {
            // ... allow add subcommands
        },
        Aliases: []string{"dm"},
        Func: func (cmd *gcli.Command, args []string) error {
            gcli.Print("hello, in the demo command\n")
            return nil
        },
    })

    // .... add more ...

    app.Run(nil)
}

Binding flags

flags binding and manage by builtin gflag.go, allow binding flag options and arguments.

Bind options

gcli support multi method to binding flag options.

Use flag methods

Available methods:

BoolOpt(p *bool, name, shorts string, defValue bool, desc string)
BoolVar(p *bool, meta FlagMeta)
Float64Opt(p *float64, name, shorts string, defValue float64, desc string)
Float64Var(p *float64, meta FlagMeta)
Int64Opt(p *int64, name, shorts string, defValue int64, desc string)
Int64Var(p *int64, meta FlagMeta)
IntOpt(p *int, name, shorts string, defValue int, desc string)
IntVar(p *int, meta FlagMeta)
StrOpt(p *string, name, shorts, defValue, desc string)
StrVar(p *string, meta FlagMeta)
Uint64Opt(p *uint64, name, shorts string, defValue uint64, desc string)
Uint64Var(p *uint64, meta FlagMeta)
UintOpt(p *uint, name, shorts string, defValue uint, desc string)
UintVar(p *uint, meta FlagMeta)
Var(p flag.Value, meta FlagMeta)
VarOpt(p flag.Value, name, shorts, desc string)

Usage examples:

var id int
var b bool
var opt, dir string
var f1 float64
var names gcli.Strings

// bind options
cmd.IntOpt(&id, "id", "", 2, "the id option")
cmd.BoolOpt(&b, "bl", "b", false, "the bool option")
// notice `DIRECTORY` will replace to option value type
cmd.StrOpt(&dir, "dir", "d", "", "the `DIRECTORY` option")
// setting option name and short-option name
cmd.StrOpt(&opt, "opt", "o", "", "the option message")
// setting a special option var, it must implement the flag.Value interface
cmd.VarOpt(&names, "names", "n", "the option message")
Use struct tags
package main

import (
	"fmt"

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

type userOpts struct {
	Int  int    `flag:"name=int0;shorts=i;required=true;desc=int option message"`
	Bol  bool   `flag:"name=bol;shorts=b;desc=bool option message"`
	Str1 string `flag:"name=str1;shorts=o,h;required=true;desc=str1 message"`
	// use ptr
	Str2 *string `flag:"name=str2;required=true;desc=str2 message"`
	// custom type and implement flag.Value
	Verb0 gcli.VerbLevel `flag:"name=verb0;shorts=V;desc=verb0 message"`
	// use ptr
	Verb1 *gcli.VerbLevel `flag:"name=verb1;desc=verb1 message"`
}

func main() {
	astr := "xyz"
	verb := gcli.VerbWarn

	cmd := gcli.NewCommand("test", "desc")
	// fs := gcli.NewFlags("test")
	// err := fs.FromStruct(&userOpts{
	err := cmd.FromStruct(&userOpts{
		Str2:  &astr,
		Verb1: &verb,
	})
	fmt.Println(err)
}
Bind arguments

About arguments:

  • Required argument cannot be defined after optional argument
  • Support binding array argument
  • The (array)argument of multiple values can only be defined at the end

Available methods:

Add(arg Argument) *Argument
AddArg(name, desc string, requiredAndArrayed ...bool) *Argument
AddArgByRule(name, rule string) *Argument
AddArgument(arg *Argument) *Argument
BindArg(arg Argument) *Argument

Usage examples:

cmd.AddArg("arg0", "the first argument, is required", true)
cmd.AddArg("arg1", "the second argument, is required", true)
cmd.AddArg("arg2", "the optional argument, is optional")
cmd.AddArg("arrArg", "the array argument, is array", false, true)

can also use Arg()/BindArg() add a gcli.Argument object:

cmd.Arg("arg0", gcli.Argument{
	Name: "ag0",
	Desc: "the first argument, is required",
	Require: true,
})
cmd.BindArg("arg2", gcli.Argument{
	Name: "ag0",
	Desc: "the third argument, is is optional",
})
cmd.BindArg("arrArg", gcli.Argument{
	Name: "arrArg",
	Desc: "the third argument, is is array",
	Arrayed: true,
})

use AddArgByRule:

cmd.AddArgByRule("arg2", "add an arg by string rule;required;23")

New application

app := gcli.NewApp()
app.Version = "1.0.3"
app.Desc = "this is my cli application"
// app.SetVerbose(gcli.VerbDebug)

Add commands

app.Add(cmd.Example)
app.Add(&gcli.Command{
    Name: "demo",
    // allow color tag and {$cmd} will be replace to 'demo'
    Desc: "this is a description <info>message</> for {$cmd}", 
    Subs: []*gcli.Command {
        // level1: sub commands...
    	{
            Name:    "remote",
            Desc:    "remote command for git",
            Aliases: []string{"rmt"},
            Func: func(c *gcli.Command, args []string) error {
                dump.Println(c.Path())
                return nil
            },
            Subs: []*gcli.Command{
                // level2: sub commands...
                // {}
            }
        },
        // ... allow add subcommands
    },
    Aliases: []string{"dm"},
    Func: func (cmd *gcli.Command, args []string) error {
        gcli.Print("hello, in the demo command\n")
        return nil
    },
})

Run application

Build the example application as demo

$ go build ./_examples/cliapp                                                         

Display version

$ ./cliapp --version      
# or use -V                                                 
$ ./cliapp -V                                                     

app-version

Display app help

by ./cliapp or ./cliapp -h or ./cliapp --help

Examples:

./cliapp
./cliapp -h # can also
./cliapp --help # can also

cmd-list

Run command

Format:

./cliapp COMMAND [--OPTION VALUE -S VALUE ...] [ARGUMENT0 ARGUMENT1 ...]
./cliapp COMMAND [--OPTION VALUE -S VALUE ...] SUBCOMMAND [--OPTION ...] [ARGUMENT0 ARGUMENT1 ...]

Run example:

$ ./cliapp example -c some.txt -d ./dir --id 34 -n tom -n john val0 val1 val2 arrVal0 arrVal1 arrVal2

You can see:

run-example

Display command help

by ./cliapp example -h or ./cliapp example --help

cmd-help

Error command tips

command tips

Generate Auto Completion Scripts

import  "github.com/gookit/gcli/v3/builtin"

    // ...
    // add gen command(gen successful you can remove it)
    app.Add(builtin.GenAutoComplete())

Build and run command(This command can be deleted after success.):

$ go build ./_examples/cliapp.go && ./cliapp genac -h // display help
$ go build ./_examples/cliapp.go && ./cliapp genac // run gen command

will see:

INFO: 
  {shell:zsh binName:cliapp output:auto-completion.zsh}

Now, will write content to file auto-completion.zsh
Continue? [yes|no](default yes): y

OK, auto-complete file generate successful

After running, it will generate an auto-completion.{zsh|bash} file in the current directory, and the shell environment name is automatically obtained. Of course, you can specify it manually at runtime

Generated shell script file ref:

Preview:

auto-complete-tips

Write a command

command allow setting fields:

  • Name the command name.
  • Desc the command description.
  • Aliases the command alias names.
  • Config the command config func, will call it on init.
  • Subs add subcommands, allow multi level subcommands
  • Func the command handle callback func
  • More, please see godoc
Quick create
var MyCmd = &gcli.Command{
    Name: "demo",
    // allow color tag and {$cmd} will be replace to 'demo'
    Desc: "this is a description <info>message</> for command {$cmd}", 
    Aliases: []string{"dm"},
    Func: func (cmd *gcli.Command, args []string) error {
        gcli.Print("hello, in the demo command\n")
        return nil
    },
    // allow add multi level subcommands
    Subs: []*gcli.Command{},
}
Write go file

the source file at: example.go

package main

import (
	"fmt"

	"github.com/gookit/color"
	"github.com/gookit/gcli/v3"
	"github.com/gookit/goutil/dump"
)

// options for the command
var exampleOpts = struct {
	id  int
	c   string
	dir string
	opt string
	names gcli.Strings
}{}

// ExampleCommand command definition
var ExampleCommand = &gcli.Command{
	Name: "example",
	Desc: "this is a description message",
	Aliases: []string{"exp", "ex"}, // 命令别名
	// {$binName} {$cmd} is help vars. '{$cmd}' will replace to 'example'
	Examples: `{$binName} {$cmd} --id 12 -c val ag0 ag1
<cyan>{$fullCmd} --names tom --names john -n c</> test use special option`,
	Config: func(c *gcli.Command) {
	    // binding options
        // ...
        c.IntOpt(&exampleOpts.id, "id", "", 2, "the id option")
		c.StrOpt(&exampleOpts.c, "config", "c", "value", "the config option")
		// notice `DIRECTORY` will replace to option value type
		c.StrOpt(&exampleOpts.dir, "dir", "d", "", "the `DIRECTORY` option")
		// 支持设置选项短名称
		c.StrOpt(&exampleOpts.opt, "opt", "o", "", "the option message")
		// 支持绑定自定义变量, 但必须实现 flag.Value 接口
		c.VarOpt(&exampleOpts.names, "names", "n", "the option message")

      // binding arguments
		c.AddArg("arg0", "the first argument, is required", true)
		// ...
	},
	Func:  exampleExecute,
}

// 命令执行主逻辑代码
// example run:
// 	go run ./_examples/cliapp.go ex -c some.txt -d ./dir --id 34 -n tom -n john val0 val1 val2 arrVal0 arrVal1 arrVal2
func exampleExecute(c *gcli.Command, args []string) error {
	color.Infoln("hello, in example command")

	if exampleOpts.showErr {
		return c.Errorf("OO, An error has occurred!!")
	}

	magentaln := color.Magenta.Println

	color.Cyanln("All Aptions:")
	// fmt.Printf("%+v\n", exampleOpts)
	dump.V(exampleOpts)

	color.Cyanln("Remain Args:")
	// fmt.Printf("%v\n", args)
	dump.P(args)

	magentaln("Get arg by name:")
	arr := c.Arg("arg0")
	fmt.Printf("named arg '%s', value: %#v\n", arr.Name, arr.Value)

	magentaln("All named args:")
	for _, arg := range c.Args() {
		fmt.Printf("- named arg '%s': %+v\n", arg.Name, arg.Value)
	}

	return nil
}
  • display the command help:
go build ./_examples/cliapp.go && ./cliapp example -h

cmd-help

Progress display

Package progress provide terminal progress bar display.

Such as: Txt, Bar, Loading, RoundTrip, DynamicText ...

  • progress.Bar progress bar

Demo: ./cliapp prog bar

prog-bar

  • progress.Txt text progress bar

Demo: ./cliapp prog txt

prog-bar

  • progress.LoadBar pending/loading progress bar

prog-demo

  • progress.Counter counter
  • progress.RoundTrip round trip progress bar
[===     ] -> [    === ] -> [ ===    ]

prog-demo

  • progress.DynamicText dynamic text message

Examples:

package main

import (
	"time"

	"github.com/gookit/gcli/v3/progress"
)

func main()  {
	speed := 100
	maxSteps := 110
	p := progress.Bar(maxSteps)
	p.Start()

	for i := 0; i < maxSteps; i++ {
		time.Sleep(time.Duration(speed) * time.Millisecond)
		p.Advance()
	}

	p.Finish()
}

more demos please see progress_demo.go

run demos:

go run ./_examples/cliapp.go prog txt
go run ./_examples/cliapp.go prog bar
go run ./_examples/cliapp.go prog roundTrip

prog-other

Interactive methods

console interactive methods

  • interact.ReadInput
  • interact.ReadLine
  • interact.ReadFirst
  • interact.Confirm
  • interact.Select/Choice
  • interact.MultiSelect/Checkbox
  • interact.Question/Ask
  • interact.ReadPassword

Examples:

package main

import (
	"fmt"

	"github.com/gookit/gcli/v3/interact"
)

func main() {
	username, _ := interact.ReadLine("Your name?")
	password := interact.ReadPassword("Your password?")
	
	ok := interact.Confirm("ensure continue?")
	if !ok {
		// do something...
	}
    
	fmt.Printf("username: %s, password: %s\n", username, password)
}
Read Input

read user input message

ans, _ := interact.ReadLine("Your name? ")

if ans != "" {
    color.Println("Your input: ", ans)
} else {
    color.Cyan.Println("No input!")
}

interact-read

Select/Choice
ans := interact.SelectOne(
    "Your city name(use array)?",
    []string{"chengdu", "beijing", "shanghai"},
    "",
)
color.Comment.Println("your select is: ", ans)

interact-select

Multi Select/Checkbox
ans := interact.MultiSelect(
    "Your city name(use array)?",
    []string{"chengdu", "beijing", "shanghai"},
    nil,
)
color.Comment.Println("your select is: ", ans)

interact-select

Confirm Message
if interact.Confirm("Ensure continue") {
    fmt.Println(emoji.Render(":smile: Confirmed"))
} else {
    color.Warn.Println("Unconfirmed")
}

interact-confirm

Read Password
pwd := interact.ReadPassword()

color.Comment.Println("your input password is: ", pwd)

interact-passwd

CLI Color

Terminal color use gookit/color Support windows cmd.exe powerShell

  • Color output display

colored-demo

Color usage
package main

import (
    "github.com/gookit/color"
)

func main() {
	// simple usage
	color.Cyan.Printf("Simple to use %s\n", "color")

	// internal theme/style:
	color.Info.Tips("message")
	color.Info.Prompt("message")
	color.Warn.Println("message")
	color.Error.Println("message")
	
	// custom color
	color.New(color.FgWhite, color.BgBlack).Println("custom color style")

	// can also:
	color.Style{color.FgCyan, color.OpBold}.Println("custom color style")
	
	// use defined color tag
	color.Print("use color tag: <suc>he</><comment>llo</>, <cyan>wel</><red>come</>\n")

	// use custom color tag
	color.Print("custom color tag: <fg=yellow;bg=black;op=underscore;>hello, welcome</>\n")

	// set a style tag
	color.Tag("info").Println("info style text")

	// prompt message
	color.Info.Prompt("prompt style message")
	color.Warn.Prompt("prompt style message")

	// tips message
	color.Info.Tips("tips style message")
	color.Warn.Tips("tips style message")
}

For more information on the use of color libraries, please visit gookit/color

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More please see https://github.com/gookit

See also

License

MIT

Documentation

Overview

Package gcli is a simple-to-use command line application and tool library.

Contains: cli app, flags parse, interact, progress, data show tools.

Source code and other details for the project are available at GitHub:

https://github.com/gookit/gcli

Usage please refer examples and see README

Index

Constants

View Source
const (
	// OK success exit code
	OK = 0
	// ERR error exit code
	ERR = 2
	// GOON prepare run successful, goon run command
	GOON = -1
	// CommandSep char
	CommandSep = ":"
	// HelpCommand name
	HelpCommand = "help"
	// VerbEnvName for set gcli debug level
	VerbEnvName = "GCLI_VERBOSE"
)
View Source
const (
	EvtAppInit = "app.init"

	EvtAppPrepareAfter = "app.prepare.after"

	EvtAppRunBefore = "app.run.before"
	EvtAppRunAfter  = "app.run.after"
	EvtAppRunError  = "app.run.error"

	EvtCmdInit = "cmd.init"

	// EvtCmdNotFound app or sub command not found
	EvtCmdNotFound = "cmd.not.found"
	// EvtAppCmdNotFound app command not found
	EvtAppCmdNotFound = "app.cmd.not.found"
	// EvtCmdSubNotFound sub command not found
	EvtCmdSubNotFound = "cmd.sub.not.found"

	EvtCmdOptParsed = "cmd.opts.parsed"

	// EvtCmdRunBefore cmd run
	EvtCmdRunBefore = "cmd.run.before"
	EvtCmdRunAfter  = "cmd.run.after"
	EvtCmdRunError  = "cmd.run.error"

	// EvtCmdExecBefore cmd exec
	EvtCmdExecBefore = "cmd.exec.before"
	EvtCmdExecAfter  = "cmd.exec.after"
	EvtCmdExecError  = "cmd.exec.error"

	EvtGOptionsParsed = "gcli.gopts.parsed"
)

constants for hooks event, there are default allowed event names

View Source
const (
	AlignLeft  = strutil.PosRight
	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
)

The options text alignment type - Align right, padding left - Align left, padding right

View Source
const HelpVarFormat = "{$%s}"

HelpVarFormat allow var replace on render help info.

Default support:

"{$binName}" "{$cmd}" "{$fullCmd}" "{$workDir}"

Variables

View Source
var (
	// CLI create an default instance
	CLI = newCmdLine()
	// DefaultVerb the default verbose level
	DefaultVerb = VerbError
)
View Source
var AppHelpTemplate = `` /* 652-byte string literal not displayed */

AppHelpTemplate help template for app(all commands) TODO {{if .HasSubcommands }} {$binName} [global options...] <info>COMMAND</> [--options ...] <info>SUBCOMMAND</> [--options ...] [arguments ...] {{end}}

View Source
var CmdHelpTemplate = `` /* 1052-byte string literal not displayed */

CmdHelpTemplate help template for a command

View Source
var FlagTagName = "flag"

FlagTagName default tag name on struct

Functions

func CommitID

func CommitID() string

CommitID of the gcli

func Debugf

func Debugf(format string, v ...interface{})

Debugf print log message

func IsDebugMode added in v3.0.1

func IsDebugMode() bool

IsDebugMode get is debug mode

func IsGteVerbose

func IsGteVerbose(verb VerbLevel) bool

IsGteVerbose get is strict mode

func Logf

func Logf(level VerbLevel, format string, v ...interface{})

Logf print log message

func NotExitOnEnd

func NotExitOnEnd() func(*App)

NotExitOnEnd for app

func Print

func Print(args ...interface{})

Print messages

func Printf

func Printf(format string, args ...interface{})

Printf messages

func Println

func Println(args ...interface{})

Println messages

func ResetGOpts

func ResetGOpts()

ResetGOpts instance

func ResetVerbose

func ResetVerbose()

ResetVerbose level

func SetCrazyMode

func SetCrazyMode()

SetCrazyMode level

func SetDebugMode

func SetDebugMode()

SetDebugMode level

func SetQuietMode

func SetQuietMode()

SetQuietMode level

func SetStrictMode

func SetStrictMode(strict bool)

SetStrictMode for parse flags

func SetVerbose

func SetVerbose(verbose VerbLevel)

SetVerbose level

func StrictMode

func StrictMode() bool

StrictMode get is strict mode

func Version

func Version() string

Version of the gcli

Types

type App

type App struct {

	// Name app name
	Name string
	// Desc app description
	Desc string
	// Func on run app, if is empty will display help.
	Func func(app *App, args []string) error
	// contains filtered or unexported fields
}

App the cli app definition

func New

func New(fns ...func(app *App)) *App

New alias of the NewApp()

func NewApp

func NewApp(fns ...func(app *App)) *App

NewApp create new app instance.

Usage:

NewApp()
// Or with a config func
NewApp(func(a *App) {
	// do something before init ....
	a.Hooks[gcli.EvtInit] = func () {}
})

func (*App) Add

func (app *App) Add(c *Command, more ...*Command)

Add one or multi command(s)

func (*App) AddAliases

func (app *App) AddAliases(name string, aliases ...string)

AddAliases add alias names for a command

func (*App) AddCommand

func (app *App) AddCommand(c *Command)

AddCommand add a new command to the app

func (*App) AddError

func (b *App) AddError(err error)

AddError to the application

func (*App) AddHandler

func (app *App) AddHandler(h Handler)

AddHandler to the application

func (*App) AliasesMapping

func (b *App) AliasesMapping() map[string]string

AliasesMapping get cmd aliases mapping

func (*App) CmdAliases

func (b *App) CmdAliases() *structs.Aliases

CmdAliases get cmd aliases

func (*App) CmdNameMap

func (b *App) CmdNameMap() map[string]int

CmdNameMap get all command names

func (*App) CmdNames

func (b *App) CmdNames() []string

CmdNames get all command names

func (*App) Command

func (b *App) Command(name string) (c *Command, exist bool)

Command get a command by name

func (*App) CommandName

func (app *App) CommandName() string

CommandName get current command name

func (*App) CommandNames

func (b *App) CommandNames() []string

CommandNames get all command names

func (*App) Commands

func (b *App) Commands() map[string]*Command

Commands get all commands

func (*App) Config

func (app *App) Config(fn func(a *App))

Config the application. Notice: must be called before adding a command

func (*App) Exec

func (app *App) Exec(path string, args []string) error

Exec direct exec other command in current command

name can be: - top command name in the app. 'top' - command path in the app. 'top sub'

Usage:

app.Exec("top")
app.Exec("top:sub")
app.Exec("top sub")
app.Exec("top sub", []string{"-a", "val0", "arg0"})

func (*App) Exit

func (app *App) Exit(code int)

Exit get the app GlobalFlags

func (*App) FindByPath

func (b *App) FindByPath(path string) *Command

FindByPath command by path. eg. "top:sub" or "top sub"

func (*App) FindCommand

func (b *App) FindCommand(path string) *Command

FindCommand command by path. eg. "top:sub" or "top sub"

func (*App) Fire

func (app *App) Fire(event string, data interface{}) bool

Fire hook on the app

func (*App) GetCommand

func (b *App) GetCommand(name string) *Command

GetCommand get a command by name

func (App) GlobalFlags

func (c App) GlobalFlags() *Flags

GlobalFlags get the app GlobalFlags

func (*App) HasCommand

func (b *App) HasCommand(name string) bool

HasCommand name check

func (*App) HasCommands

func (b *App) HasCommands() bool

HasCommands on the cmd/app

func (*App) HasSubcommands

func (app *App) HasSubcommands() bool

HasSubcommands on the app

func (*App) IsAlias

func (b *App) IsAlias(alias string) bool

IsAlias name check

func (*App) IsCommand

func (b *App) IsCommand(name string) bool

IsCommand name check. alias of the HasCommand()

func (*App) Match

func (b *App) Match(names []string) *Command

Match command by path names. eg. ["top", "sub"]

func (*App) MatchByPath

func (b *App) MatchByPath(path string) *Command

MatchByPath command by path. eg. "top:sub" or "top sub"

func (*App) On

func (app *App) On(name string, handler HookFunc)

On add hook handler for a hook event

func (App) RawOsArgs

func (c App) RawOsArgs() []string

RawOsArgs get the raw os.Args

func (*App) ResolveAlias

func (b *App) ResolveAlias(alias string) string

ResolveAlias get real command name by alias

func (*App) Run

func (app *App) Run(args []string) (code int)

Run running application

Usage:

// run with os.Args
app.Run(nil)
app.Run(os.Args[1:])
// custom args
app.Run([]string{"cmd", "--name", "inhere"})

func (*App) RunCmd added in v3.0.1

func (app *App) RunCmd(name string, args []string) int

RunCmd running an top command with custom args

Usage:

app.Exec("top")
app.Exec("top", []string{"-a", "val0", "arg0"})
// can add sub command on args
app.Exec("top", []string{"sub", "-o", "abc"})

func (*App) RunLine

func (app *App) RunLine(argsLine string) int

RunLine manual run an command by command line string.

eg: app.RunLine("top --top-opt val0 sub --sub-opt val1 arg0")

func (*App) SetDefaultCommand

func (app *App) SetDefaultCommand(name string)

SetDefaultCommand set default command name

func (b *App) SetLogo(logo string, style ...string)

SetLogo text and color style

type Argument

type Argument 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
}

Argument a command argument definition

func NewArg added in v3.0.3

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

NewArg quick create a new command argument

func NewArgument

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

NewArgument quick create a new command argument

func (*Argument) Array

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

Array alias of the Strings()

func (*Argument) GetValue

func (a *Argument) GetValue() interface{}

GetValue get value by custom handler func

func (*Argument) HasValue

func (a *Argument) HasValue() bool

HasValue value is empty

func (*Argument) HelpName

func (a *Argument) HelpName() string

HelpName for render help message

func (*Argument) Index

func (a *Argument) Index() int

Index get argument index in the command

func (*Argument) Init

func (a *Argument) Init() *Argument

Init the argument

func (*Argument) SetArrayed added in v3.0.1

func (a *Argument) SetArrayed() *Argument

SetArrayed the argument

func (*Argument) SetValue

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

SetValue set an validated value

func (*Argument) WithFn added in v3.0.3

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

WithFn a func for config the argument

func (*Argument) WithValidator

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

WithValidator set a value validator of the argument

func (*Argument) WithValue added in v3.0.3

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

WithValue to the argument

type Arguments

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

Arguments definition

func (*Arguments) AddArg

func (ags *Arguments) AddArg(name, desc string, requiredAndArrayed ...bool) *Argument

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 (*Arguments) AddArgByRule added in v3.0.1

func (ags *Arguments) AddArgByRule(name, rule string) *Argument

AddArgByRule add an arg by simple string rule

func (*Arguments) AddArgument

func (ags *Arguments) AddArgument(arg *Argument) *Argument

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 (*Arguments) Arg

func (ags *Arguments) Arg(name string) *Argument

Arg get arg by defined name.

Usage:

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

func (*Arguments) ArgByIndex

func (ags *Arguments) ArgByIndex(i int) *Argument

ArgByIndex get named arg by index

func (*Arguments) Args

func (ags *Arguments) Args() []*Argument

Args get all defined argument

func (*Arguments) BindArg

func (ags *Arguments) BindArg(arg *Argument) *Argument

BindArg alias of the AddArgument()

func (*Arguments) HasArg

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

HasArg check named argument is defined

func (*Arguments) HasArgs

func (ags *Arguments) HasArgs() bool

HasArgs defined. alias of the HasArguments()

func (*Arguments) HasArguments

func (ags *Arguments) HasArguments() bool

HasArguments defined

func (*Arguments) ParseArgs

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

ParseArgs for Arguments

func (*Arguments) SetName

func (ags *Arguments) SetName(name string)

SetName for Arguments

func (*Arguments) SetValidateNum

func (ags *Arguments) SetValidateNum(validateNum bool)

SetValidateNum check

type Booleans

type Booleans []bool

Booleans The bool flag list, implemented flag.Value interface

func (*Booleans) Set

func (s *Booleans) Set(value string) error

Set new value

func (*Booleans) String

func (s *Booleans) String() string

String to string

type Command

type Command struct {

	// Flags options for the command
	Flags
	// Arguments for the command
	Arguments

	// Name is the full command name.
	Name string
	// Desc is the command description message.
	Desc string

	// Aliases is the command name's alias names
	Aliases []string
	// Category for the command
	Category string
	// Config func, will call on `initialize`.
	// - you can config options and other init works
	Config func(c *Command)
	// Hidden the command on render help
	Hidden bool

	// Subs sub commands of the Command
	// NOTICE: if command has been initialized, adding through this field is invalid
	Subs []*Command

	// module is the name for grouped commands
	// subName is the name for grouped commands
	// eg: "sys:info" -> module: "sys", subName: "info"
	// module, subName string
	// Examples some usage example display
	Examples string
	// Func is the command handler func. Func Runner
	Func RunnerFunc
	// Help is the long help message text
	Help string
	// HelpRender custom render cmd help message
	HelpRender func(c *Command)
	// contains filtered or unexported fields
}

Command a CLI command structure

func NewCommand

func NewCommand(name, desc string, fn ...func(c *Command)) *Command

NewCommand create a new command instance. Usage:

cmd := NewCommand("my-cmd", "description")
// OR with an config func
cmd := NewCommand("my-cmd", "description", func(c *Command) { ... })
app.Add(cmd) // OR cmd.AttachTo(app)

func (*Command) Add

func (c *Command) Add(sub *Command, more ...*Command)

Add one or multi sub-command(s). alias of the AddSubs

func (*Command) AddCommand

func (c *Command) AddCommand(sub *Command)

AddCommand add a sub command

func (*Command) AddError

func (b *Command) AddError(err error)

AddError to the application

func (*Command) AddSubs

func (c *Command) AddSubs(sub *Command, more ...*Command)

AddSubs add one or multi sub-command(s)

func (*Command) AliasesMapping

func (b *Command) AliasesMapping() map[string]string

AliasesMapping get cmd aliases mapping

func (*Command) AliasesString

func (c *Command) AliasesString(sep ...string) string

AliasesString returns aliases string

func (*Command) App

func (c *Command) App() *App

App returns the CLI application

func (*Command) AttachTo

func (c *Command) AttachTo(app *App)

AttachTo attach the command to CLI application

func (*Command) CmdAliases

func (b *Command) CmdAliases() *structs.Aliases

CmdAliases get cmd aliases

func (*Command) CmdNameMap

func (b *Command) CmdNameMap() map[string]int

CmdNameMap get all command names

func (*Command) CmdNames

func (b *Command) CmdNames() []string

CmdNames get all command names

func (*Command) Command

func (b *Command) Command(name string) (c *Command, exist bool)

Command get a command by name

func (*Command) CommandNames

func (b *Command) CommandNames() []string

CommandNames get all command names

func (*Command) Commands

func (b *Command) Commands() map[string]*Command

Commands get all commands

func (*Command) Copy

func (c *Command) Copy() *Command

Copy a new command for current

func (*Command) Disable

func (c *Command) Disable()

Disable set cmd is disabled

func (*Command) Errorf

func (c *Command) Errorf(format string, v ...interface{}) error

Errorf format message and add error to the command

func (*Command) FindByPath

func (b *Command) FindByPath(path string) *Command

FindByPath command by path. eg. "top:sub" or "top sub"

func (*Command) FindCommand

func (b *Command) FindCommand(path string) *Command

FindCommand command by path. eg. "top:sub" or "top sub"

func (*Command) Fire

func (c *Command) Fire(event string, data interface{}) (stop bool)

Fire event handler by name

func (*Command) GFlags

func (c *Command) GFlags() *Flags

GFlags get global flags

func (*Command) GetCommand

func (b *Command) GetCommand(name string) *Command

GetCommand get a command by name

func (Command) GlobalFlags

func (c Command) GlobalFlags() *Flags

GlobalFlags get the app GlobalFlags

func (*Command) HasCommand

func (b *Command) HasCommand(name string) bool

HasCommand name check

func (*Command) HasCommands

func (b *Command) HasCommands() bool

HasCommands on the cmd/app

func (*Command) HelpDesc

func (c *Command) HelpDesc() (desc string)

HelpDesc format desc string for render help

func (*Command) ID

func (c *Command) ID() string

ID get command ID string

func (*Command) Init

func (c *Command) Init()

Init command. only use for tests

func (*Command) IsAlias

func (b *Command) IsAlias(alias string) bool

IsAlias name check

func (*Command) IsCommand

func (b *Command) IsCommand(name string) bool

IsCommand name check. alias of the HasCommand()

func (*Command) IsDisabled

func (c *Command) IsDisabled() bool

IsDisabled get cmd is disabled

func (*Command) IsRoot

func (c *Command) IsRoot() bool

IsRoot command

func (*Command) IsStandalone

func (c *Command) IsStandalone() bool

IsStandalone running

func (*Command) IsSubCommand

func (c *Command) IsSubCommand(name string) bool

IsSubCommand name check. alias of the HasCommand()

func (*Command) Match

func (c *Command) Match(names []string) *Command

Match sub command by input names

func (*Command) MatchByPath

func (c *Command) MatchByPath(path string) *Command

MatchByPath command by path. eg. "top:sub"

func (*Command) MustRun

func (c *Command) MustRun(args []string)

MustRun Alone the current command, will panic on error

Usage:

// run with os.Args
cmd.MustRun(nil)
cmd.MustRun(os.Args[1:])
// custom args
cmd.MustRun([]string{"-a", ...})

func (*Command) NewErr added in v3.0.1

func (c *Command) NewErr(msg string) error

NewErr format message and add error to the command

func (*Command) NewErrf added in v3.0.1

func (c *Command) NewErrf(format string, v ...interface{}) error

NewErrf format message and add error to the command

func (*Command) Next

func (c *Command) Next()

Next TODO processing, run all middleware handlers

func (*Command) NotStandalone

func (c *Command) NotStandalone() bool

NotStandalone running

func (*Command) On

func (c *Command) On(name string, handler HookFunc)

On add hook handler for a hook event

func (*Command) Parent

func (c *Command) Parent() *Command

Parent get parent

func (*Command) ParentName

func (c *Command) ParentName() string

Module name of the grouped command

func (*Command) Path

func (c *Command) Path() string

Path get command full path

func (*Command) PathNames

func (c *Command) PathNames() []string

PathNames get command path names

func (Command) RawOsArgs

func (c Command) RawOsArgs() []string

RawOsArgs get the raw os.Args

func (*Command) ResolveAlias

func (b *Command) ResolveAlias(alias string) string

ResolveAlias get real command name by alias

func (*Command) Root

func (c *Command) Root() *Command

Root get root command

func (*Command) Run

func (c *Command) Run(args []string) (err error)

Run standalone running the command

Usage:

// run with os.Args
cmd.Run(nil)
cmd.Run(os.Args[1:])
// custom args
cmd.Run([]string{"-a", ...})

func (*Command) Runnable

func (c *Command) Runnable() bool

Runnable reports whether the command can be run; otherwise it is a documentation pseudo-command such as import path.

func (*Command) SetFunc

func (c *Command) SetFunc(fn RunnerFunc)

SetFunc Settings command handler func

func (b *Command) SetLogo(logo string, style ...string)

SetLogo text and color style

func (*Command) SetParent

func (c *Command) SetParent(parent *Command)

SetParent set parent

func (*Command) ShowHelp

func (c *Command) ShowHelp()

ShowHelp show command help info

func (*Command) Sub

func (c *Command) Sub(name string) *Command

Sub get sub command by name. eg "sub"

func (*Command) SubCommand

func (c *Command) SubCommand(name string) *Command

SubCommand get sub command by name. eg "sub"

func (*Command) Visible added in v3.0.1

func (c *Command) Visible() bool

Visible return cmd is visible

func (*Command) WithFunc

func (c *Command) WithFunc(fn RunnerFunc) *Command

WithFunc Settings command handler func

func (*Command) WithHidden added in v3.0.1

func (c *Command) WithHidden() *Command

WithHidden Settings command is hidden

type Commander

type Commander interface {
	Value(string) (interface{}, bool)
	SetValue(string, interface{})
}

Commander interface

type EnumString

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

EnumString The string flag list, implemented flag.Value interface

func (*EnumString) Set

func (s *EnumString) Set(value string) error

Set new value, will check value is right

func (*EnumString) SetEnum added in v3.0.1

func (s *EnumString) SetEnum(enum []string)

SetEnum values

func (*EnumString) String

func (s *EnumString) String() string

String to string

type FlagMeta

type FlagMeta 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
	// contains filtered or unexported fields
}

FlagMeta for an flag(option/argument)

func (*FlagMeta) DValue

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

DValue wrap the default value

func (*FlagMeta) Flag added in v3.0.3

func (m *FlagMeta) Flag() *flag.Flag

Flag value

func (*FlagMeta) HelpName added in v3.0.3

func (m *FlagMeta) HelpName() string

HelpName for show help

func (*FlagMeta) Shorts2String

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

Shorts2String join shorts to a string

func (*FlagMeta) Validate

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

Validate the binding value

type Flags

type Flags struct {
	// Desc message
	Desc string
	// ExitFunc for handle exit
	ExitFunc func(code int)
	// contains filtered or unexported fields
}

Flags struct definition

func NewFlags

func NewFlags(nameWithDesc ...string) *Flags

NewFlags create a new Flags

func (*Flags) Bool

func (fs *Flags) Bool(name, shorts string, defVal bool, desc string) *bool

Bool binding a bool option flag, return pointer

func (*Flags) BoolOpt

func (fs *Flags) BoolOpt(p *bool, name, shorts string, defVal bool, desc string)

BoolOpt binding a bool option

func (*Flags) BoolVar

func (fs *Flags) BoolVar(p *bool, meta *FlagMeta)

BoolVar binding a bool option flag

func (*Flags) BuildHelp added in v3.0.3

func (fs *Flags) BuildHelp() string

BuildHelp string for all flag options

func (*Flags) FSet

func (fs *Flags) FSet() *flag.FlagSet

FSet get the raw *flag.FlagSet

func (*Flags) FSetArgs

func (fs *Flags) FSetArgs() []string

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

func (*Flags) FlagMeta

func (fs *Flags) FlagMeta(name string) *FlagMeta

FlagMeta get FlagMeta by name

func (*Flags) FlagNames

func (fs *Flags) FlagNames() map[string]int

FlagNames return all option names

func (*Flags) Float64Opt

func (fs *Flags) Float64Opt(p *float64, name, shorts string, defVal float64, desc string)

Float64Opt binding a float64 option

func (*Flags) Float64Var

func (fs *Flags) Float64Var(p *float64, meta *FlagMeta)

Float64Var binding an float64 option flag

func (*Flags) FromStruct

func (fs *Flags) FromStruct(ptr any) error

FromStruct from struct tag binding options

func (*Flags) HasFlag

func (fs *Flags) HasFlag(name string) bool

HasFlag check it is a option name. alias of HasOption()

func (*Flags) HasFlagMeta

func (fs *Flags) HasFlagMeta(name string) bool

HasFlagMeta check it is has FlagMeta

func (*Flags) HasOption

func (fs *Flags) HasOption(name string) bool

HasOption check it is a option name

func (*Flags) InitFlagSet

func (fs *Flags) InitFlagSet(name string)

InitFlagSet create and init flag.FlagSet

func (*Flags) Int

func (fs *Flags) Int(name, shorts string, defValue int, desc string) *int

Int binding an int option flag, return pointer

func (*Flags) Int64

func (fs *Flags) Int64(name, shorts string, defValue int64, desc string) *int64

Int64 binding an int64 option flag, return pointer

func (*Flags) Int64Opt

func (fs *Flags) Int64Opt(p *int64, name, shorts string, defValue int64, desc string)

Int64Opt binding an int64 option

func (*Flags) Int64Var

func (fs *Flags) Int64Var(p *int64, meta *FlagMeta)

Int64Var binding an int64 option flag

func (*Flags) IntOpt

func (fs *Flags) IntOpt(p *int, name, shorts string, defValue int, desc string)

IntOpt binding an int option

func (*Flags) IntVar

func (fs *Flags) IntVar(p *int, meta *FlagMeta)

IntVar binding an int option flag

func (*Flags) IsOption

func (fs *Flags) IsOption(name string) bool

IsOption check it is a option name

func (*Flags) IsShortName

func (fs *Flags) IsShortName(short string) bool

IsShortName check it is a shortcut name

func (*Flags) IsShortOpt

func (fs *Flags) IsShortOpt(short string) bool

IsShortOpt alias of the IsShortcut()

func (*Flags) IterAll

func (fs *Flags) IterAll(fn func(f *flag.Flag, meta *FlagMeta))

IterAll Iteration all flag options with metadata

func (*Flags) Len

func (fs *Flags) Len() int

Len of the Flags

func (*Flags) LookupFlag

func (fs *Flags) LookupFlag(name string) *flag.Flag

LookupFlag get flag.Flag by name

func (*Flags) Metas

func (fs *Flags) Metas() map[string]*FlagMeta

Metas get all flag metas

func (*Flags) Name

func (fs *Flags) Name() string

Name of the Flags

func (*Flags) Parse

func (fs *Flags) Parse(args []string) (err error)

Parse given arguments

Usage:

gf := gcli.NewFlags()
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 (*Flags) PrintHelpPanel

func (fs *Flags) PrintHelpPanel()

PrintHelpPanel for all options to the gf.out

func (*Flags) RawArg

func (fs *Flags) RawArg(i int) string

RawArg get an argument value by index

func (*Flags) RawArgs

func (fs *Flags) RawArgs() []string

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

func (*Flags) Required

func (fs *Flags) Required(names ...string)

Required flag option name(s)

func (*Flags) Run

func (fs *Flags) Run(args []string)

Run flags parse and handle help render

Usage:

	gf := gcli.NewFlags()
 ...
	gf.Run(os.Args)

func (*Flags) SetConfig added in v3.0.3

func (fs *Flags) SetConfig(opt *FlagsConfig)

SetConfig for the object.

func (*Flags) SetFlagSet

func (fs *Flags) SetFlagSet(fSet *flag.FlagSet)

SetFlagSet set the raw *flag.FlagSet

func (*Flags) SetHelpRender

func (fs *Flags) SetHelpRender(fn func())

SetHelpRender set the raw *flag.FlagSet.Usage

func (*Flags) SetOutput

func (fs *Flags) SetOutput(out io.Writer)

SetOutput for the Flags

func (*Flags) ShortNames

func (fs *Flags) ShortNames(name string) (ss []string)

ShortNames get all short-names of the option

func (*Flags) Str

func (fs *Flags) Str(name, shorts string, defValue, desc string) *string

Str binding an string option flag, return pointer

func (*Flags) StrOpt

func (fs *Flags) StrOpt(p *string, name, shorts, defValue, desc string)

StrOpt binding an string option

func (*Flags) StrVar

func (fs *Flags) StrVar(p *string, meta *FlagMeta)

StrVar binding an string option flag

func (*Flags) String

func (fs *Flags) String() string

String for all flag options

func (*Flags) Uint

func (fs *Flags) Uint(name, shorts string, defVal uint, desc string) *uint

Uint binding an int option flag, return pointer

func (*Flags) Uint64

func (fs *Flags) Uint64(name, shorts string, defVal uint64, desc string) *uint64

Uint64 binding an int option flag, return pointer

func (*Flags) Uint64Opt

func (fs *Flags) Uint64Opt(p *uint64, name, shorts string, defVal uint64, desc string)

Uint64Opt binding an uint64 option

func (*Flags) Uint64Var

func (fs *Flags) Uint64Var(p *uint64, meta *FlagMeta)

Uint64Var binding an uint option flag

func (*Flags) UintOpt

func (fs *Flags) UintOpt(p *uint, name, shorts string, defValue uint, desc string)

UintOpt binding an uint option

func (*Flags) UintVar

func (fs *Flags) UintVar(p *uint, meta *FlagMeta)

UintVar binding an uint option flag

func (*Flags) UseSimpleRule added in v3.0.2

func (fs *Flags) UseSimpleRule() *Flags

UseSimpleRule for the parse tag value rule string. see TagRuleSimple

func (*Flags) Var

func (fs *Flags) Var(p flag.Value, meta *FlagMeta)

Var binding an custom var option flag

func (*Flags) VarOpt

func (fs *Flags) VarOpt(p flag.Value, name, shorts, desc string)

VarOpt binding a custom var option

Usage:

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

func (*Flags) WithConfigFn added in v3.0.3

func (fs *Flags) WithConfigFn(fns ...func(cfg *FlagsConfig)) *Flags

WithConfigFn for the object.

type FlagsConfig added in v3.0.3

type FlagsConfig 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
}

FlagsConfig for render help information

type GOptions

type GOptions struct {
	Disable bool
	NoColor bool
	// contains filtered or unexported fields
}

GOptions global flag options

func GOpts

func GOpts() *GOptions

GOpts get the global options

func (*GOptions) NoInteractive

func (g *GOptions) NoInteractive() bool

NoInteractive value

func (*GOptions) NoProgress

func (g *GOptions) NoProgress() bool

NoProgress value

func (*GOptions) SetDisable added in v3.0.5

func (g *GOptions) SetDisable()

SetDisable global options

func (*GOptions) SetStrictMode

func (g *GOptions) SetStrictMode(strictMode bool)

SetStrictMode option

func (*GOptions) SetVerbose

func (g *GOptions) SetVerbose(verbose VerbLevel)

SetVerbose value

func (*GOptions) Verbose

func (g *GOptions) Verbose() VerbLevel

Verbose value

type Handler

type Handler interface {
	// Creator for create new command
	Creator() *Command
	// Config bind Flags or Arguments for the command
	Config(c *Command)
	// Execute the command
	Execute(c *Command, args []string) error
}

Handler interface definition

type HandlersChain

type HandlersChain []RunnerFunc

HandlersChain middleware handlers chain definition

func (HandlersChain) Last

func (c HandlersChain) Last() RunnerFunc

Last returns the last handler in the chain. ie. the last handler is the main own.

type HelpVars

type HelpVars struct {
	// varLeft, varRight string
	// varFormat string
	// Vars you can add some vars map for render help info
	Vars map[string]string
}

HelpVars struct. provide string var function for render help template.

func (*HelpVars) AddVar

func (hv *HelpVars) AddVar(name, value string)

AddVar get command name

func (*HelpVars) AddVars

func (hv *HelpVars) AddVars(vars map[string]string)

AddVars add multi tpl vars

func (*HelpVars) GetVar

func (hv *HelpVars) GetVar(name string) string

GetVar get a help var by name

func (*HelpVars) GetVars

func (hv *HelpVars) GetVars() map[string]string

GetVars get all tpl vars

func (*HelpVars) ReplaceVars

func (hv *HelpVars) ReplaceVars(input string) string

ReplaceVars replace vars in the input string.

type HookCtx

type HookCtx struct {
	App *App
	Cmd *Command
	// contains filtered or unexported fields
}

HookCtx struct

func (*HookCtx) ClearData

func (md *HookCtx) ClearData()

ClearData all data

func (*HookCtx) Data

func (md *HookCtx) Data() map[string]interface{}

Data get all

func (*HookCtx) GetVal added in v3.0.2

func (md *HookCtx) GetVal(key string) interface{}

GetVal get from data

func (*HookCtx) IntValue

func (md *HookCtx) IntValue(key string) int

IntValue get from data

func (*HookCtx) Name

func (hc *HookCtx) Name() string

Name of event

func (*HookCtx) SetData

func (md *HookCtx) SetData(data map[string]interface{})

SetData set all data

func (*HookCtx) SetValue

func (md *HookCtx) SetValue(key string, val interface{})

SetValue to data

func (*HookCtx) StrValue

func (md *HookCtx) StrValue(key string) string

StrValue get from data

func (*HookCtx) Value

func (md *HookCtx) Value(key string) interface{}

Value get from data

type HookFunc

type HookFunc func(data ...interface{}) (stop bool)

HookFunc definition.

func arguments:

in app, like: func(app *App, data ...interface{})
in cmd, like: func(cmd *Command, data ...interface{})

type HookFunc func(obj interface{}, data interface{})

return: - True go on handle. default is True - False stop goon handle.

type Hooks

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

Hooks struct. hookManager

func (*Hooks) AddOn

func (h *Hooks) AddOn(name string, handler HookFunc)

AddOn register on not exists hook.

func (*Hooks) ClearHooks

func (h *Hooks) ClearHooks()

ClearHooks clear hooks data

func (*Hooks) Fire

func (h *Hooks) Fire(event string, data ...interface{}) (stop bool)

Fire event by name, allow with event data

func (*Hooks) HasHook

func (h *Hooks) HasHook(event string) bool

HasHook register

func (*Hooks) On

func (h *Hooks) On(name string, handler HookFunc)

On register event hook by name

type Ints

type Ints []int

Ints The int flag list, implemented flag.Value interface

func (*Ints) Set

func (s *Ints) Set(value string) error

Set new value

func (*Ints) String

func (s *Ints) String() string

String to string

type Logo struct {
	Text  string // ASCII logo string
	Style string // eg "info"
}

Logo app logo, ASCII logo

type OptCategory added in v3.0.3

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

OptCategory struct

type Runner

type Runner interface {
	// Run Config(c *Command)
	Run(c *Command, args []string) error
}

Runner /Executor interface

type RunnerFunc

type RunnerFunc func(c *Command, args []string) error

RunnerFunc definition

func (RunnerFunc) Run

func (f RunnerFunc) Run(c *Command, args []string) error

Run implement the Runner interface

type String added in v3.0.1

type String string

String type, a special string

Usage:

// case 1:
var names gcli.String
c.VarOpt(&names, "names", "", "multi name by comma split")

--names "tom,john,joy"
 names.Split(",") -> []string{"tom","john","joy"}

// case 2:
var ids gcli.String
c.VarOpt(&ids, "ids", "", "multi id by comma split")

--names "23,34,56"
 names.Ints(",") -> []int{23,34,56}

func (*String) Ints added in v3.0.1

func (s *String) Ints(sep string) []int

Ints value to []int

func (*String) Set added in v3.0.1

func (s *String) Set(val string) error

Set value

func (*String) Split added in v3.0.1

func (s *String) Split(sep string) []string

Split value to []string

func (*String) String added in v3.0.1

func (s *String) String() string

String to string

type Strings

type Strings []string

Strings The string flag list, implemented flag.Value interface

func (*Strings) Set

func (s *Strings) Set(value string) error

Set new value

func (*Strings) String

func (s *Strings) String() string

String to string

type VerbLevel

type VerbLevel uint

VerbLevel type.

const (
	VerbQuiet VerbLevel = iota // don't report anything
	VerbError                  // reporting on error, default level.
	VerbWarn
	VerbInfo
	VerbDebug
	VerbCrazy
)

constants for error level (quiet 0 - 5 crazy)

func Verbose

func Verbose() VerbLevel

Verbose returns verbose level

func (*VerbLevel) Int

func (vl *VerbLevel) Int() int

Int verbose level to int.

func (*VerbLevel) Name

func (vl *VerbLevel) Name() string

Name verbose level to string.

func (*VerbLevel) Set

func (vl *VerbLevel) Set(value string) error

Set value from option binding.

func (*VerbLevel) String

func (vl *VerbLevel) String() string

String verbose level to string.

func (*VerbLevel) Upper

func (vl *VerbLevel) Upper() string

Upper verbose level to string.

Directories

Path Synopsis
cmd
sflag
Package sflag is an simple cli flag parse tool
Package sflag is an simple cli flag parse tool
Package interact collect some interactive methods for CLI
Package interact collect some interactive methods for CLI
Package progress provide terminal progress bar display.
Package progress provide terminal progress bar display.
Package show provides some formatter tools for display data.
Package show provides some formatter tools for display data.

Jump to

Keyboard shortcuts

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