Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

gcli

> 开发工具
Open source

Go CLI application, tool library, running CLI commands, support console color, user interaction, progress display, data formatting display, generate bash/zsh

380 stars0 likes1 views
WebsiteGitHub

About

Go CLI application, tool library, running CLI commands, support console color, user interaction, progress display, data formatting display, generate bash/zsh

GCli

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.

中文说明

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

  • Color output, interactive input and progress/data display, provided by gookit/color and gookit/cliui

GoDoc

  • godoc

Install

bash
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:

…

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:

…

Usage examples:

go
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:

go
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

…

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

go
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.

go
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:

go
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:

go
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:).

go
// 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:

go
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:

go
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:

go
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:

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

New application

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

Add commands

…

Run application

Build the example application as demo

bash
$ go build ./_examples/cliapp                                                         

Display version

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

Display app help

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

Examples:

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

Run command

Format:

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

Run example:

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

You can see:

Display command help

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

Error 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
go
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.):

bash
$ 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:

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.

go
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

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Goclicli-appcli-applicationcli-commands

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具