gcli

package module
v3.8.3 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 28 Imported by: 19

README

GCli

GitHub go.mod Go version Actions Status GitHub tag (latest SemVer) Codacy Badge Go Reference 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.

中文说明

app-cmd-list

Features

Rich in functions and easy to use. Highlights grouped by area:

Commands

  • Multi-level (nested) commands, each level binds its own options
  • Command aliases and similar-command tips on typo (alias-aware)
  • Command/App middleware via Use(handlers ...RunnerFunc)
  • A single command can run as a stand-alone application

Option binding

  • Code-style binders: BoolOpt / IntOpt / StrOpt / Float64Opt / VarOpt ...
  • Generic, type-safe binders: gflag.Opt[T] / gflag.BindVar[T] — one call covers bool/int/uint/float/string, time.Duration, []string/[]int/[]bool, map[string]string
  • Struct-tag binding via FromStruct:
    • three tag rules: named(default) / simple / field(field name as option name); anonymous embedded structs auto-expand under any rule
    • field types: bool/int/uint/float/string, native []string/[]int/[]bool (repeatable), time.Duration, map[string]string (repeatable --meta k=v)
    • enum:"a,b,c" tag for value candidates(completion) + membership validation
  • Required / Validator / Choices per option; option Category for grouped help display

Three-level option model

  • Global (App-level) options
  • Shared (inherited) options via Command.SharedOpts() (≈ cobra PersistentFlags): inherited by the command and all its sub-commands (sharing the same variable), grouped under Inherited Options in help
  • Local (per-command) options

Parse enhancements

  • Options written after arguments are auto-reordered: cmd arg --name tom == cmd --name tom arg (on by default; disable via gflag.WithReorderArgs(false))
  • POSIX short-flag combining (-ab = -a -b) via opt-in EnhanceShort; EnhanceShort=2 also supports attached-value form -Ostdout = -O stdout. Only all-bool groups are split, off by default for compatibility
  • Declarative interactive collect by Question when the option value is empty

Arguments

  • Bind named argument, with required / optional / array settings
  • Auto-detected and collected when the command is run

Tooling

  • Generate zsh / bash / pwsh command completion scripts (incl. dynamic completion)
  • Generate markdown / man page command documentation (docgen package + builtin GenDoc command)
  • Auto-generated, color-rendered command help information
  • Event hook system (gevent, with gcli.Evt* aliases)

Extras

GoDoc

Install

go get github.com/gookit/gcli/v3

Upgrade note: the event package gcli/v3/events was renamed to gcli/v3/gevent. Update your imports, or reference event names directly via the gcli.Evt* aliases (e.g. gcli.EvtCmdRunBefore) to avoid the import entirely. See CHANGELOG for details.

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)

    // TIP: Add binding app-level option settings (same level as the built-in -h/--help)
    app.Flags().BoolOpt(...)
    app.Flags().StrOpt(...)

    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 generic binders

gflag.Opt[T] / gflag.BindVar[T] bind a typed pointer in one type-safe call, covering scalars, time.Duration, slices and map[string]string:

var name string
var tags []string

gflag.Opt(cmd.Flags(), &name, "name", "n", "tom", "the user name")
// slice option, repeatable: --tag php --tag go
gflag.Opt(cmd.Flags(), &tags, "tag", "t", nil, "the tags, repeatable")
Use struct tags
package main

import (
	"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;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=v0;desc=verb0 message"`
	// use ptr
	Verb1 *gcli.VerbLevel `flag:"name=verb1;desc=verb1 message"`
}

// run: go run ./_examples/issues/iss157.go
func main() {
	astr := "xyz"
	verb := gcli.VerbWarn

	cmd := gcli.NewCommand("test", "desc")
	cmd.Config = func(c *gcli.Command) {
		c.MustFromStruct(&userOpts{
			Str2:  &astr,
			Verb1: &verb,
		})
	}

	// disable auto bind global options: verbose,version, progress...
	gcli.GOpts().SetDisable()

	// direct run
	if err := cmd.Run(nil); err != nil {
		colorp.Errorln( err)
	}
}
Struct tag rules

FromStruct supports three tag rules, selected by c.FromStruct(ptr, ruleType):

  • gcli.TagRuleNamed (default): flag:"name=int0;shorts=i;required=true;desc=message"
  • gcli.TagRuleSimple: flag:"desc;required;default;shorts"
  • gcli.TagRuleField: use the field name (SnakeCase) as the option name, read meta from independent tag keys.

Anonymous embedded structs are expanded automatically under all three rules — each inner field is read using whichever rule is active. This also works for embedded unexported types (e.g. commonOpts below).

type commonOpts struct {
	Verbose bool `flag:"v" desc:"enable verbose output"`
}
type demoOpts struct {
	commonOpts        // anonymous: expands to a --verbose/-v option
	UserName string `flag:"u" desc:"the user name" required:"true"`
	Age      int    `desc:"the user age" default:"18"`
}

c.MustFromStruct(&demoOpts{}, gcli.TagRuleField)
// => options: --user-name/-u (required), --age (default 18), --verbose/-v
Interactive collect by Question

When an option value is empty, you can auto-collect it via an interactive question (a built-in default collector). Collector has higher priority than Question.

c.StrOpt2(&token, "token", "the access token",
	gflag.WithQuestion("Please input your access token: "))
// run without --token will prompt: "Please input your access token: "
POSIX short option enhance

Combined short options are disabled by default. Enable via Config.EnhanceShort:

c.ParserCfg().EnhanceShort = gcli.EnhanceShortMerge  // 1: -aux => -a -u -x (all bool)
c.ParserCfg().EnhanceShort = gcli.EnhanceShortAttach // 2: also -Ostdout => -O stdout

Or enable it globally for all commands with one call — a command's own setting (if any) still takes priority:

gcli.SetEnhanceShort(gcli.EnhanceShortMerge) // applies to every command

Only groups where all members are bool short options are split; mixed forms are kept as-is to avoid mis-parsing value-taking short options.

Runnable demos in _examples/cmd: struct-flag (B6), short-merge (B4+B5), ask-demo (B7).

Command/Option category

Both commands and options support a Category for grouped display in the help message. When no category is set, the output is the same as before (commands go to Available Commands, options are listed directly under Options:).

// command category
app.Add(&gcli.Command{Name: "migrate", Desc: "run db migrate", Category: "database"})
app.Add(&gcli.Command{Name: "serve", Desc: "start http server"}) // default group

// option category
cmd.StrVar(&dsn, &gcli.CliOpt{Name: "db-dsn", Desc: "database dsn", Category: "database"})
cmd.StrOpt2(&port, "port", "bind port", gflag.WithCategory("network"))

Groups keep the order of first appearance; commands inside a group are sorted by name.

NOTE: the log level is no longer controlled by a global --verbose option. Use the env GCLI_VERBOSE (eg GCLI_VERBOSE=debug) or gcli.SetVerbose() instead, so it won't pollute the option list of the host application.

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

There are two ways to generate command completion scripts:

  • Directly use the global option ./cliapp --gen-completion bash|zsh > ~/.cliapp-completion.sh to generate
  • Register the built-in GenAutoComplete command and then generate it using ./cliapp genac -o ~/.cliapp-completion.sh
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

Preview:

auto-complete-tips

Shared (inherited) options

Command.SharedOpts() (≈ cobra PersistentFlags) binds options that are inherited by the command and all of its sub-commands, sharing the same variable. They can be written at any position in the sub-command segment and are grouped under Inherited Options in the help output.

var gitDir string

top := &gcli.Command{Name: "git", Desc: "git tools"}
// bind on SharedOpts: inherited by every sub-command
top.SharedOpts().StrOpt(&gitDir, "git-dir", "", ".git", "the git dir path")

top.Add(&gcli.Command{
    Name: "status",
    Func: func(c *gcli.Command, _ []string) error {
        // --git-dir is usable here even though it is declared on the parent
        gcli.Printf("git dir: %s\n", gitDir)
        return nil
    },
})

// usage: ./app git status --git-dir /path/to/.git

Generate command docs

Add the builtin GenDoc command, then export markdown / man documentation for all commands:

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

app.Add(builtin.GenDoc())
// ./cliapp gendoc -f md  -o ./docs   # export markdown (default)
// ./cliapp gendoc -f man -o ./docs   # export man pages

You can also call it programmatically:

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

docgen.MarkdownTree(app, "./docs") // one .md per command + index.md
docgen.ManTree(app, "./docs")      // man pages

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.NewErrf("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

Extras: color, interactive & progress

gcli ships with color output, interactive input (Confirm / Select / ReadLine ...), progress display (Bar / Spinner / Loading ...) and data display (table / list / tree), provided by gookit/color and gookit/cliui.

color.Info.Tips("processing...")              // colored output

ok := interact.Confirm("ensure continue?")    // interactive confirm
if !ok {
    return nil
}

p := progress.Bar(100)                        // progress bar
p.Start();
/* p.Advance() in loop */
p.Finish()

For more usage see gookit/color and gookit/cliui.

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/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 (
	ZshShell  = "zsh"
	BashShell = "bash"
	PwshShell = "pwsh" // PowerShell
)

current supported shell for completion script generate

View Source
const (
	// EvtAppInitBefore on app init before
	EvtAppInitBefore = gevent.OnAppInitBefore
	// EvtAppInit on app init after
	EvtAppInit = gevent.OnAppInitAfter
	// EvtAppExit on app exit
	EvtAppExit = gevent.OnAppExit

	// EvtAppBindOptsBefore before bind app options
	EvtAppBindOptsBefore = gevent.OnAppBindOptsBefore
	// EvtAppBindOptsAfter after bind app options
	EvtAppBindOptsAfter = gevent.OnAppBindOptsAfter

	// EvtAppCmdAdd on app cmd add before
	EvtAppCmdAdd = gevent.OnAppCmdAdd
	// EvtAppCmdAdded on app cmd added
	EvtAppCmdAdded = gevent.OnAppCmdAdded

	// EvtAppOptsParsed on app options parsed
	EvtAppOptsParsed = gevent.OnAppOptsParsed

	// EvtAppHelpBefore before render app help
	EvtAppHelpBefore = gevent.OnAppHelpBefore
	// EvtAppHelpAfter after render app help
	EvtAppHelpAfter = gevent.OnAppHelpAfter

	// EvtAppPrepareAfter prepare for run, after the EvtAppOptsParsed
	EvtAppPrepareAfter = gevent.OnAppPrepared

	EvtAppRunBefore = gevent.OnAppRunBefore
	EvtAppRunAfter  = gevent.OnAppRunAfter
	EvtAppRunError  = gevent.OnAppRunError

	// EvtCmdInitBefore on cmd init before
	EvtCmdInitBefore = gevent.OnCmdInitBefore
	// EvtCmdInit on cmd init after
	EvtCmdInit = gevent.OnCmdInitAfter

	// EvtCmdNotFound app or sub command not found
	EvtCmdNotFound = gevent.OnCmdNotFound
	// EvtAppCmdNotFound app command not found
	EvtAppCmdNotFound = gevent.OnAppCmdNotFound
	// EvtCmdSubNotFound sub command not found
	EvtCmdSubNotFound = gevent.OnCmdSubNotFound

	EvtCmdOptParsed = gevent.OnCmdOptParsed

	// EvtCmdRunBefore cmd run
	EvtCmdRunBefore = gevent.OnCmdRunBefore
	EvtCmdRunAfter  = gevent.OnCmdRunAfter
	EvtCmdRunError  = gevent.OnCmdRunError

	// EvtCmdExecBefore cmd exec
	EvtCmdExecBefore = gevent.OnCmdExecBefore
	EvtCmdExecAfter  = gevent.OnCmdExecAfter
	EvtCmdExecError  = gevent.OnCmdExecError

	EvtGOptionsParsed = gevent.OnGlobalOptsParsed
)

constants for hooks event, there are default allowed event names.

These are aliases for the gevent.* event names. So user code can reference them directly from gcli without importing the gevent package.

View Source
const (
	// CommandSep char
	CommandSep = ":"
	// HelpCommand name
	HelpCommand = "help"
	// VerbEnvName for set gcli debug level
	VerbEnvName = "GCLI_VERBOSE"
)
View Source
const (
	// TagRuleNamed struct tag use named k-v rule. eg: `flag:"name=int0;shorts=i;required=true;desc=message"`
	TagRuleNamed = gflag.TagRuleNamed
	// TagRuleSimple struct tag use simple rule. eg: `flag:"name;desc;required;default;shorts"`
	TagRuleSimple = gflag.TagRuleSimple
	// TagRuleField struct tag use field name as option name, read meta from independent tag keys.
	// eg: `flag:"shorts" desc:"message" default:"val" required:"true"`
	TagRuleField = gflag.TagRuleField
)

TagRule* alias of the gflag struct-tag rule type consts. see Flags.FromStruct

View Source
const (
	// EnhanceShortNone do not enhance short option parse. (default)
	EnhanceShortNone = gflag.EnhanceShortNone
	// EnhanceShortMerge merge bool short option group. eg: `-aux` = `-a -u -x`
	EnhanceShortMerge = gflag.EnhanceShortMerge
	// EnhanceShortAttach also support value-attached short. eg: `-Ostdout` = `-O stdout`
	EnhanceShortAttach = gflag.EnhanceShortAttach
)

EnhanceShort* alias of the gflag short-option enhance level consts. see Flags Config.EnhanceShort

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

HelpVarFormat allow string replace on render help info.

Default support:

"{$binName}" "{$cmd}" "{$fullCmd}" "{$workDir}"
View Source
const InheritedOptsCategory = "Inherited Options"

InheritedOptsCategory 是继承(共享)选项在命令 help 中的分组标题。

Variables

View Source
var AppHelpTemplate = `` /* 715-byte string literal not displayed */

AppHelpTemplate help template for app(all commands)

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

CmdHelpTemplate help template for a command

Functions

func CommitID

func CommitID() string

CommitID of the gcli

func Config added in v3.1.0

func Config(fn func(opts *GlobalOpts))

Config global options

func Debugf

func Debugf(format string, v ...any)

Debugf print log message

func EnhanceShort added in v3.5.0

func EnhanceShort() uint8

EnhanceShort get the global POSIX short-option enhance level.

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 ...any)

Logf print log message

func NewFlags

func NewFlags(nameWithDesc ...string) *gflag.Flags

NewFlags create new gflag.Flags

func NotExitOnEnd

func NotExitOnEnd() func(*App)

NotExitOnEnd for app

func Print

func Print(args ...any)

Print messages

func Printf

func Printf(format string, args ...any)

Printf messages

func Println

func Println(args ...any)

Println messages

func ResetGOpts

func ResetGOpts()

ResetGOpts instance

func ResetVerbose

func ResetVerbose()

ResetVerbose level

func SetDebugMode

func SetDebugMode()

SetDebugMode level

func SetEnhanceShort added in v3.5.0

func SetEnhanceShort(level uint8)

SetEnhanceShort set the global POSIX short-option enhance level for all commands.

level: EnhanceShortNone(0) / EnhanceShortMerge(1) / EnhanceShortAttach(2).

NOTE: a command's own Config.EnhanceShort (if set non-zero) takes priority over this.

func SetQuietMode

func SetQuietMode()

SetQuietMode level

func SetStrictMode

func SetStrictMode(strict bool)

SetStrictMode for parse flags

func SetVerbose

func SetVerbose[T VerbLevel | string](verbose T)

SetVerbose level by name or 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[gevent.OnAppInitAfter] = 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) AddHelpVar added in v3.1.1

func (b *App) AddHelpVar(key string, val any)

AddHelpVar to instance.

func (*App) AliasesMapping

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

AliasesMapping get cmd aliases mapping

func (*App) AppOpts added in v3.8.0

func (app *App) AppOpts() *AppOptions

AppOpts get the app's own parse/run state (help/version/completion).

func (*App) BinDir added in v3.1.1

func (b *App) BinDir() string

BinDir get bin script dirname

func (*App) BinName added in v3.1.1

func (b *App) BinName() string

BinName get bin script name

func (*App) ChWorkDir added in v3.2.2

func (b *App) ChWorkDir(dir string) error

ChWorkDir change the work dir path

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 gets a direct children command by name, not support alias.

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) CommandsByGroup added in v3.4.0

func (b *App) CommandsByGroup(defaultTitle string) []*CmdGroup

CommandsByGroup group all visible commands by their Category field.

- groups keep the category insertion order(see base.cmdCategories). - the default group(empty Category) uses defaultTitle as its title. - returns nil when there is no visible command.

func (*App) Config

func (app *App) Config(fns ...func(a *App))

Config the application.

Notice: must be called before add command

func (*App) Errors added in v3.8.2

func (b *App) Errors() error

Errors fetch, will clear after fetch.

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 map[string]any) bool

Fire hook on the app. returns True for stop continue run.

func (*App) Flags added in v3.1.0

func (app *App) Flags() *Flags

Flags get. TIP: you can custom binding applicaton options

Usage:

app.Flags().BoolOpt(...)
app.Flags().StrOpt(...)

func (*App) GenCompletionHelp added in v3.6.0

func (app *App) GenCompletionHelp(binName ...string) string

GenCompletionHelp 生成 --gen-completion 的使用与 shell profile 配置说明。

func (*App) GenCompletionScript added in v3.4.1

func (app *App) GenCompletionScript(shell string, binName ...string) (string, error)

GenCompletionScript 生成指定 shell 的**动态(瘦)**补全脚本文本(默认方式)。

瘦脚本不硬编码命令/选项, 而是回调 `bin --in-completion <已输入词...>` 动态取候选, 命令/选项变化后无需重新生成脚本, 零维护。

  • shell: 目标 shell, 取值 bash|zsh, 其它返回 error。
  • binName: 可选, 覆盖脚本中使用的 bin 名(如 genac 的 --bin-name); 不传则使用当前应用的 bin 名。

func (*App) GenStaticCompletionScript added in v3.4.1

func (app *App) GenStaticCompletionScript(shell string, binName ...string) (string, error)

GenStaticCompletionScript 生成指定 shell 的**静态(嵌入式)**补全脚本文本。

静态脚本把当前已注册的命令名/描述/选项硬编码进脚本; 命令/选项变化后需重新生成。 一般推荐使用 GenCompletionScript(瘦/动态); 仅在无法回调二进制等场景下用此 opt-in 方式。

  • shell: 目标 shell, 取值 bash|zsh, 其它返回 error。
  • binName: 可选, 覆盖脚本中使用的 bin 名(如 genac 的 --bin-name); 不传则使用当前应用的 bin 名。

生成所需的数据(BinName、命令名/描述、各命令选项等)均从 app 当前已注册的命令中取得。

func (*App) GetCommand

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

GetCommand get a direct children command by name, not support alias.

func (*App) HasCommand

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

HasCommand top command name check

func (*App) HasCommands

func (b *App) HasCommands() bool

HasCommands on the cmd/app

func (*App) HasSubcommands

func (b *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 top command name check. alias of the HasCommand()

func (*App) LastError added in v3.8.2

func (b *App) LastError() error

LastError fetch, will clear after fetch.

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) Opts added in v3.1.0

func (app *App) Opts() *GlobalOpts

Opts get the process-level GlobalOpts (verbose/strict/enhanceShort, shared). for the app's own parse state (help/version/completion) use AppOpts().

func (*App) QuickRun added in v3.1.0

func (app *App) QuickRun() int

QuickRun the application with os.Args

func (*App) ResetData added in v3.1.0

func (b *App) ResetData()

ResetData from ctx

func (*App) ResolveAlias

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

ResolveAlias get real command name by alias

func (*App) ResolveCommand added in v3.8.1

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

ResolveCommand gets a direct children command by name or alias.

func (*App) Run

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

Run the application with input args

Usage:

// run with os.Args
app.Run(nil)
app.Run(os.Args[1:])

// custom args
app.Run([]string{"cmd", "--name", "inhere"})

func (*App) RunArgs added in v3.2.4

func (app *App) RunArgs(args ...string) int

RunArgs running a command with custom args

func (*App) RunCmd added in v3.0.1

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

RunCmd running a 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 a 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

func (*App) Use added in v3.4.1

func (app *App) Use(handlers ...RunnerFunc) *App

Use 注册应用级中间件, 对所有命令在其自身中间件与主函数之前执行; 返回 app 以便链式调用。

func (*App) WorkDir added in v3.1.1

func (b *App) WorkDir() string

WorkDir get work dirname

type AppOptions added in v3.8.0

type AppOptions struct {
	// ShowHelp show help information, then exit.
	ShowHelp bool
	// ShowVersion show version information, then exit.
	ShowVersion bool
	// contains filtered or unexported fields
}

AppOptions per-app(or standalone command) parse & run state. Each App owns its own instance, so concurrent App instances in one process don't share these.

type Argument

type Argument = gflag.CliArg

Argument alias of the gflag.CliArg

func NewArgument

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

NewArgument quick create a new command argument

type Arguments

type Arguments = gflag.CliArgs

Arguments alias of the gflag.CliArgs

type Booleans

type Booleans = cflag.Booleans

Booleans The bool flag list, implemented flag.Value interface

type CliArg added in v3.1.0

type CliArg = gflag.CliArg

CliArg alias of the gflag.CliArg

type CliArgs added in v3.1.0

type CliArgs = gflag.CliArgs

CliArgs alias of the gflag.CliArgs

type CliOpt added in v3.1.0

type CliOpt = gflag.CliOpt

CliOpt alias of the gflag.CliOpt

type CmdGroup added in v3.4.0

type CmdGroup struct {
	// Name is the category name. "" means the default group.
	Name string
	// Title is the display title for help. eg: "Available Commands"
	Title string
	// Cmds are the visible commands of this group, sorted by name.
	Cmds []*Command
}

CmdGroup is a group of commands by category. used for render help.

type Command

type Command struct {

	// Flags cli (options+arguments) parse and manage for the command
	gflag.Flags

	// Name is the command name.
	Name string
	// Desc is the command description message.
	// Can use string-var in contents, eg: {$cmd}
	Desc string

	// Aliases is the command name's alias names
	Aliases arrutil.Strings
	// Category for grouped command display on help
	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

	// Func is the command handler func. Func Runner
	//
	// TIP:
	// 	params: `args` is the remain arguments after parse flags(options and arguments).
	Func RunnerFunc

	// Examples some usage example display.
	//
	// Can use string-var in contents, eg:
	//   {$cmd}, {$binName}, {$binDir}, {$workDir}, {$binWithCmd}, {$binWithPath}, {$fullCmd}
	Examples string
	// Help is the long help message text
	//
	// Can use string-var in contents, eg:
	//   {$cmd}, {$binName}, {$binDir}, {$workDir}, {$binWithCmd}, {$binWithPath}, {$fullCmd}
	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, setFn ...func(c *Command)) *Command

NewCommand create a new command instance.

Usage:

cmd := NewCommand("my-cmd", "description")
// OR with a 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) AddHelpVar added in v3.1.1

func (b *Command) AddHelpVar(key string, val any)

AddHelpVar to instance.

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) 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) BinDir added in v3.1.1

func (b *Command) BinDir() string

BinDir get bin script dirname

func (*Command) BinName added in v3.1.1

func (b *Command) BinName() string

BinName get bin script name

func (*Command) ChWorkDir added in v3.2.2

func (b *Command) ChWorkDir(dir string) error

ChWorkDir change the work dir path

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 gets a direct children command by name, not support alias.

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) CommandsByGroup added in v3.4.0

func (b *Command) CommandsByGroup(defaultTitle string) []*CmdGroup

CommandsByGroup group all visible commands by their Category field.

- groups keep the category insertion order(see base.cmdCategories). - the default group(empty Category) uses defaultTitle as its title. - returns nil when there is no visible command.

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) Errors added in v3.8.2

func (b *Command) Errors() error

Errors fetch, will clear after fetch.

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 map[string]any) (stop bool)

Fire event handler by name

func (*Command) GetCommand

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

GetCommand get a direct children command by name, not support alias.

func (*Command) HasCommand

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

HasCommand top command name check

func (*Command) HasCommands

func (b *Command) HasCommands() bool

HasCommands on the cmd/app

func (*Command) HasSubcommands added in v3.1.0

func (b *Command) HasSubcommands() bool

HasSubcommands on the 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. return like "git:branch:create"

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 top command 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) IsRunnable added in v3.1.1

func (c *Command) IsRunnable() bool

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

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) LastError added in v3.8.2

func (b *Command) LastError() error

LastError fetch, will clear after fetch.

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 output message 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 ...any) 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

ParentName name of the parent command

func (*Command) Path

func (c *Command) Path() string

Path get command full path, joined by space. eg: "git branch create"

func (*Command) PathNames

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

PathNames get command path names

func (*Command) ResetData added in v3.1.0

func (b *Command) ResetData()

ResetData from ctx

func (*Command) ResolveAlias

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

ResolveAlias get real command name by alias

func (*Command) ResolveCommand added in v3.8.1

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

ResolveCommand gets a direct children command by name or 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) 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) SharedOpts added in v3.8.0

func (c *Command) SharedOpts() *gflag.Flags

SharedOpts 返回命令专属的共享选项持有器(惰性创建), 对标 cobra 的 PersistentFlags()。

在它上面像普通选项一样绑定(BoolOpt/StrOpt/Opt[T]/FromStruct/...), 这些选项会被本命令 及其所有子孙命令继承: 父命令定义、子命令也能解析, 且父子读写同一个变量(共享 flag.Value)。

注意: sharedFs 仅作为「定义来源」, 自身永不单独 Parse; 分发时由 parseOptions 合并进 c.Flags。

func (*Command) ShowHelp

func (c *Command) ShowHelp() (err error)

ShowHelp show command help information

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) Use added in v3.4.1

func (c *Command) Use(handlers ...RunnerFunc) *Command

Use 注册一个或多个中间件, 按注册顺序在命令主函数前依次执行; 返回 c 以便链式调用。

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

func (*Command) WorkDir added in v3.1.1

func (b *Command) WorkDir() string

WorkDir get work dirname

type Context added in v3.1.0

type Context struct {
	maputil.Data
	context.Context
	// contains filtered or unexported fields
}

Context struct

func GCtx added in v3.1.0

func GCtx() *Context

GCtx get the global ctx

func NewCtx added in v3.1.0

func NewCtx() *Context

NewCtx instance

func (*Context) ArgLine added in v3.1.0

func (ctx *Context) ArgLine() string

ArgLine os.Args to string, but no binName.

func (*Context) BinDir added in v3.1.0

func (ctx *Context) BinDir() string

BinDir get bin script dirname

func (*Context) BinFile added in v3.1.0

func (ctx *Context) BinFile() string

BinFile get bin script file

func (*Context) BinName added in v3.1.0

func (ctx *Context) BinName() string

BinName get bin script name

func (*Context) InitCtx added in v3.1.0

func (ctx *Context) InitCtx() *Context

InitCtx some common info

func (*Context) OsArgs added in v3.1.0

func (ctx *Context) OsArgs() []string

OsArgs is equals to `os.Args`

func (*Context) OsName added in v3.1.0

func (ctx *Context) OsName() string

OsName is equals to `runtime.GOOS`

func (*Context) PID added in v3.1.0

func (ctx *Context) PID() int

PID get pid

func (*Context) PIDString added in v3.1.0

func (ctx *Context) PIDString() string

PIDString get pid as string

func (*Context) ResetData added in v3.1.0

func (ctx *Context) ResetData()

ResetData from ctx

func (*Context) UpWorkDir added in v3.3.0

func (ctx *Context) UpWorkDir(dir string)

UpWorkDir update work dir path

func (*Context) Value added in v3.1.0

func (ctx *Context) Value(key any) any

Value get by key

func (*Context) WorkDir added in v3.1.0

func (ctx *Context) WorkDir() string

WorkDir get work dirname

type EnumString

type EnumString = cflag.EnumString

EnumString The string flag list, implemented flag.Value interface

type FlagMeta

type FlagMeta = gflag.CliOpt

FlagMeta alias of the gflag.CliOpt. Deprecated: use CliOpt instead

type Flags

type Flags = gflag.Parser

Flags alias of the gflag.Parser

type FlagsConfig added in v3.0.3

type FlagsConfig = gflag.Config

FlagsConfig alias of the gflag.Config

type FoundState added in v3.3.0

type FoundState int8

FoundState for match command name. 0=not found, 1=found

const (
	// NotFound not found command by input
	NotFound FoundState = iota
	Founded
)

type GlobalOpts added in v3.1.0

type GlobalOpts struct {
	// Disable auto binding global options
	Disable bool
	NoColor bool
	// set the message report level.
	//
	// can set by env: GCLI_VERBOSE=debug. see VerbEnvName
	Verbose VerbLevel
	// NoProgress dont display progress. env: NO_PROGRESS
	NoProgress bool
	// NoInteractive close interactive confirm. env: NO_INTERACTIVE
	NoInteractive bool
	// contains filtered or unexported fields
}

GlobalOpts process-level config options. shared across all App instances via the package singleton gOpts; set by gcli.SetVerbose / SetStrictMode / SetEnhanceShort.

NOTE: per-app parse/run state (help/version/completion) lives in AppOptions, so multiple App instances in one process don't share it. see App.AppOpts().

func GOpts

func GOpts() *GlobalOpts

GOpts get the global options

func (*GlobalOpts) SetDisable added in v3.1.0

func (g *GlobalOpts) SetDisable()

SetDisable global options

func (*GlobalOpts) SetEnhanceShort added in v3.5.0

func (g *GlobalOpts) SetEnhanceShort(level uint8)

SetEnhanceShort global level. see EnhanceShortNone/Merge/Attach

func (*GlobalOpts) SetStrictMode added in v3.1.0

func (g *GlobalOpts) SetStrictMode(strictMode bool)

SetStrictMode option

func (*GlobalOpts) SetVerbose added in v3.1.0

func (g *GlobalOpts) SetVerbose(verbose VerbLevel)

SetVerbose 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. tip: the last handler is the main own.

type HelpConfig added in v3.3.0

type HelpConfig struct {
	// AfterCmdText add text after commands list
	AfterCmdText string
	// FooterText add help footer text on help end
	FooterText string
}

HelpConfig struct

type HelpReplacer added in v3.1.1

type HelpReplacer struct {
	VarOpen, VarClose string
	// contains filtered or unexported fields
}

HelpReplacer provide string var replace for render help template.

func (*HelpReplacer) AddReplace added in v3.1.1

func (hv *HelpReplacer) AddReplace(name, value string)

AddReplace get command name. AddReplace

func (*HelpReplacer) AddReplaces added in v3.1.1

func (hv *HelpReplacer) AddReplaces(vars map[string]string)

AddReplaces add multi tpl vars.

func (*HelpReplacer) GetReplace added in v3.1.1

func (hv *HelpReplacer) GetReplace(name string) string

GetReplace get a help var by name

func (*HelpReplacer) ReplacePairs added in v3.1.1

func (hv *HelpReplacer) ReplacePairs(input string) string

ReplacePairs replace string vars in the input text.

func (*HelpReplacer) Replaces added in v3.1.1

func (hv *HelpReplacer) Replaces() map[string]string

Replaces get all tpl vars.

type HookCtx

type HookCtx struct {
	context.Context
	maputil.Data
	App *App
	Cmd *Command
	// contains filtered or unexported fields
}

HookCtx struct

func (*HookCtx) Err added in v3.1.0

func (hc *HookCtx) Err() error

Err of event

func (*HookCtx) Name

func (hc *HookCtx) Name() string

Name of event

func (*HookCtx) SetStop added in v3.1.0

func (hc *HookCtx) SetStop(stop bool) bool

SetStop value

func (*HookCtx) Stopped added in v3.1.0

func (hc *HookCtx) Stopped() bool

Stopped value

func (*HookCtx) WithApp added in v3.1.0

func (hc *HookCtx) WithApp(a *App) *HookCtx

WithApp to ctx

func (*HookCtx) WithData added in v3.1.0

func (hc *HookCtx) WithData(data map[string]any) *HookCtx

WithData to ctx

func (*HookCtx) WithErr added in v3.1.0

func (hc *HookCtx) WithErr(err error) *HookCtx

WithErr value

type HookFunc

type HookFunc func(ctx *HookCtx) (stop bool)

HookFunc definition.

Returns:

  • True for stop continue run.
  • False continue handle next logic.

type Hooks

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

Hooks struct. hookManager

func (*Hooks) AddHook added in v3.1.0

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

AddHook register on not exists hook.

func (*Hooks) Fire

func (h *Hooks) Fire(event string, ctx *HookCtx) (stop bool)

Fire event by name, allow with event data. returns True for stop continue run.

func (*Hooks) HasHook

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

HasHook registered check.

func (*Hooks) On

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

On register event hook by name

func (*Hooks) ResetHooks added in v3.1.0

func (h *Hooks) ResetHooks()

ResetHooks clear all hooks

type Ints

type Ints = cflag.Ints

Ints The int flag list, implemented flag.Value interface

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

Logo app logo, ASCII logo

type PrepareState added in v3.3.0

type PrepareState int8

PrepareState value. 0=ok, 2=error, -1=goon

const (
	// OK success exit code. eg: help command, fired event
	OK PrepareState = 0
	// ERR error exit code
	ERR PrepareState = 2
	// GOON prepare run successful, goon run command
	GOON PrepareState = -1
)

func (PrepareState) ToInt added in v3.3.0

func (ps PrepareState) ToInt() int

ToInt value

type Runner

type Runner interface {
	// Run the command
	//
	// TIP:
	// 	args is the remain arguments after parse flags(options and arguments).
	Run(c *Command, remainArgs []string) error
}

Runner /Executor interface

type RunnerFunc

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

RunnerFunc definition

TIP:

args is the remain arguments after parse flags(options and arguments).

func (RunnerFunc) Run

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

Run implement the Runner interface

type String added in v3.0.1

type String = cflag.String

String type, a special string

type Strings

type Strings = cflag.Strings

Strings The string flag list, implemented flag.Value interface

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

func VerbLevelFrom(name string) VerbLevel

VerbLevelFrom level name string.

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
_examples
bannerdemo command
cliapp command
cmd
emojitest command
ggit command
issues command
multilevel command
rawflag command
serveman command
sflag
Package sflag is an simple cli flag parse tool
Package sflag is an simple cli flag parse tool
simpleone command
testterm command
Package docgen 提供把 gcli 命令/应用导出为 markdown 与 man page(roff) 文档的能力。
Package docgen 提供把 gcli 命令/应用导出为 markdown 与 man page(roff) 文档的能力。
Package gflag provide command line options and arguments binding, parse, management.
Package gflag provide command line options and arguments binding, parse, management.
internal

Jump to

Keyboard shortcuts

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