go>> gcli>> 返回
项目作者: gookit

项目描述 :
? Go CLI application, tool library, running CLI commands, support console color, user interaction, progress display, data formatting display, generate bash/zsh completion add more features. Go的命令行应用,工具库,运行CLI命令,支持命令行色彩,用户交互,进度显示,数据格式化显示,生成bash/zsh命令补全脚本
高级语言: Go
项目地址: git://github.com/gookit/gcli.git


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.

中文说明

中文说明请看 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 argument
  • Support define array argument

GoDoc

Install

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

Quick start

an example for quick start:

  1. package main
  2. import (
  3. "github.com/gookit/gcli/v3"
  4. "github.com/gookit/gcli/v3/_examples/cmd"
  5. )
  6. // for test run: go build ./_examples/cliapp.go && ./cliapp
  7. func main() {
  8. app := gcli.NewApp()
  9. app.Version = "1.0.3"
  10. app.Desc = "this is my cli application"
  11. // app.SetVerbose(gcli.VerbDebug)
  12. app.Add(cmd.Example)
  13. app.Add(&gcli.Command{
  14. Name: "demo",
  15. // allow color tag and {$cmd} will be replace to 'demo'
  16. Desc: "this is a description <info>message</> for {$cmd}",
  17. Subs: []*gcli.Command {
  18. // ... allow add subcommands
  19. },
  20. Aliases: []string{"dm"},
  21. Func: func (cmd *gcli.Command, args []string) error {
  22. gcli.Print("hello, in the demo command\n")
  23. return nil
  24. },
  25. })
  26. // .... add more ...
  27. app.Run(nil)
  28. }

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:

  1. BoolOpt(p *bool, name, shorts string, defValue bool, desc string)
  2. BoolVar(p *bool, meta FlagMeta)
  3. Float64Opt(p *float64, name, shorts string, defValue float64, desc string)
  4. Float64Var(p *float64, meta FlagMeta)
  5. Int64Opt(p *int64, name, shorts string, defValue int64, desc string)
  6. Int64Var(p *int64, meta FlagMeta)
  7. IntOpt(p *int, name, shorts string, defValue int, desc string)
  8. IntVar(p *int, meta FlagMeta)
  9. StrOpt(p *string, name, shorts, defValue, desc string)
  10. StrVar(p *string, meta FlagMeta)
  11. Uint64Opt(p *uint64, name, shorts string, defValue uint64, desc string)
  12. Uint64Var(p *uint64, meta FlagMeta)
  13. UintOpt(p *uint, name, shorts string, defValue uint, desc string)
  14. UintVar(p *uint, meta FlagMeta)
  15. Var(p flag.Value, meta FlagMeta)
  16. VarOpt(p flag.Value, name, shorts, desc string)

Usage examples:

  1. var id int
  2. var b bool
  3. var opt, dir string
  4. var f1 float64
  5. var names gcli.Strings
  6. // bind options
  7. cmd.IntOpt(&id, "id", "", 2, "the id option")
  8. cmd.BoolOpt(&b, "bl", "b", false, "the bool option")
  9. // notice `DIRECTORY` will replace to option value type
  10. cmd.StrOpt(&dir, "dir", "d", "", "the `DIRECTORY` option")
  11. // setting option name and short-option name
  12. cmd.StrOpt(&opt, "opt", "o", "", "the option message")
  13. // setting a special option var, it must implement the flag.Value interface
  14. cmd.VarOpt(&names, "names", "n", "the option message")

Use struct tags

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gookit/gcli/v3"
  5. )
  6. type userOpts struct {
  7. Int int `flag:"name=int0;shorts=i;required=true;desc=int option message"`
  8. Bol bool `flag:"name=bol;shorts=b;desc=bool option message"`
  9. Str1 string `flag:"name=str1;shorts=o,h;required=true;desc=str1 message"`
  10. // use ptr
  11. Str2 *string `flag:"name=str2;required=true;desc=str2 message"`
  12. // custom type and implement flag.Value
  13. Verb0 gcli.VerbLevel `flag:"name=verb0;shorts=V;desc=verb0 message"`
  14. // use ptr
  15. Verb1 *gcli.VerbLevel `flag:"name=verb1;desc=verb1 message"`
  16. }
  17. func main() {
  18. astr := "xyz"
  19. verb := gcli.VerbWarn
  20. cmd := gcli.NewCommand("test", "desc")
  21. // fs := gcli.NewFlags("test")
  22. // err := fs.FromStruct(&userOpts{
  23. err := cmd.FromStruct(&userOpts{
  24. Str2: &astr,
  25. Verb1: &verb,
  26. })
  27. fmt.Println(err)
  28. }

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:

  1. Add(arg Argument) *Argument
  2. AddArg(name, desc string, requiredAndArrayed ...bool) *Argument
  3. AddArgByRule(name, rule string) *Argument
  4. AddArgument(arg *Argument) *Argument
  5. BindArg(arg Argument) *Argument

Usage examples:

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

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

  1. cmd.Arg("arg0", gcli.Argument{
  2. Name: "ag0",
  3. Desc: "the first argument, is required",
  4. Require: true,
  5. })
  6. cmd.BindArg("arg2", gcli.Argument{
  7. Name: "ag0",
  8. Desc: "the third argument, is is optional",
  9. })
  10. cmd.BindArg("arrArg", gcli.Argument{
  11. Name: "arrArg",
  12. Desc: "the third argument, is is array",
  13. Arrayed: true,
  14. })

use AddArgByRule:

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

New application

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

Add commands

  1. app.Add(cmd.Example)
  2. app.Add(&gcli.Command{
  3. Name: "demo",
  4. // allow color tag and {$cmd} will be replace to 'demo'
  5. Desc: "this is a description <info>message</> for {$cmd}",
  6. Subs: []*gcli.Command {
  7. // level1: sub commands...
  8. {
  9. Name: "remote",
  10. Desc: "remote command for git",
  11. Aliases: []string{"rmt"},
  12. Func: func(c *gcli.Command, args []string) error {
  13. dump.Println(c.Path())
  14. return nil
  15. },
  16. Subs: []*gcli.Command{
  17. // level2: sub commands...
  18. // {}
  19. }
  20. },
  21. // ... allow add subcommands
  22. },
  23. Aliases: []string{"dm"},
  24. Func: func (cmd *gcli.Command, args []string) error {
  25. gcli.Print("hello, in the demo command\n")
  26. return nil
  27. },
  28. })

Run application

Build the example application as demo

  1. $ go build ./_examples/cliapp

Display version

  1. $ ./cliapp --version
  2. # or use -V
  3. $ ./cliapp -V

app-version

Display app help

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

Examples:

  1. ./cliapp
  2. ./cliapp -h # can also
  3. ./cliapp --help # can also

cmd-list

Run command

Format:

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

Run example:

  1. $ ./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

  1. import "github.com/gookit/gcli/v3/builtin"
  2. // ...
  3. // add gen command(gen successful you can remove it)
  4. app.Add(builtin.GenAutoComplete())

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

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

will see:

  1. INFO:
  2. {shell:zsh binName:cliapp output:auto-completion.zsh}
  3. Now, will write content to file auto-completion.zsh
  4. Continue? [yes|no](default yes): y
  5. 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

  1. var MyCmd = &gcli.Command{
  2. Name: "demo",
  3. // allow color tag and {$cmd} will be replace to 'demo'
  4. Desc: "this is a description <info>message</> for command {$cmd}",
  5. Aliases: []string{"dm"},
  6. Func: func (cmd *gcli.Command, args []string) error {
  7. gcli.Print("hello, in the demo command\n")
  8. return nil
  9. },
  10. // allow add multi level subcommands
  11. Subs: []*gcli.Command{},
  12. }

Write go file

the source file at: example.go

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gookit/color"
  5. "github.com/gookit/gcli/v3"
  6. "github.com/gookit/goutil/dump"
  7. )
  8. // options for the command
  9. var exampleOpts = struct {
  10. id int
  11. c string
  12. dir string
  13. opt string
  14. names gcli.Strings
  15. }{}
  16. // ExampleCommand command definition
  17. var ExampleCommand = &gcli.Command{
  18. Name: "example",
  19. Desc: "this is a description message",
  20. Aliases: []string{"exp", "ex"}, // 命令别名
  21. // {$binName} {$cmd} is help vars. '{$cmd}' will replace to 'example'
  22. Examples: `{$binName} {$cmd} --id 12 -c val ag0 ag1
  23. <cyan>{$fullCmd} --names tom --names john -n c</> test use special option`,
  24. Config: func(c *gcli.Command) {
  25. // binding options
  26. // ...
  27. c.IntOpt(&exampleOpts.id, "id", "", 2, "the id option")
  28. c.StrOpt(&exampleOpts.c, "config", "c", "value", "the config option")
  29. // notice `DIRECTORY` will replace to option value type
  30. c.StrOpt(&exampleOpts.dir, "dir", "d", "", "the `DIRECTORY` option")
  31. // 支持设置选项短名称
  32. c.StrOpt(&exampleOpts.opt, "opt", "o", "", "the option message")
  33. // 支持绑定自定义变量, 但必须实现 flag.Value 接口
  34. c.VarOpt(&exampleOpts.names, "names", "n", "the option message")
  35. // binding arguments
  36. c.AddArg("arg0", "the first argument, is required", true)
  37. // ...
  38. },
  39. Func: exampleExecute,
  40. }
  41. // 命令执行主逻辑代码
  42. // example run:
  43. // go run ./_examples/cliapp.go ex -c some.txt -d ./dir --id 34 -n tom -n john val0 val1 val2 arrVal0 arrVal1 arrVal2
  44. func exampleExecute(c *gcli.Command, args []string) error {
  45. color.Infoln("hello, in example command")
  46. if exampleOpts.showErr {
  47. return c.NewErrf("OO, An error has occurred!!")
  48. }
  49. magentaln := color.Magenta.Println
  50. color.Cyanln("All Aptions:")
  51. // fmt.Printf("%+v\n", exampleOpts)
  52. dump.V(exampleOpts)
  53. color.Cyanln("Remain Args:")
  54. // fmt.Printf("%v\n", args)
  55. dump.P(args)
  56. magentaln("Get arg by name:")
  57. arr := c.Arg("arg0")
  58. fmt.Printf("named arg '%s', value: %#v\n", arr.Name, arr.Value)
  59. magentaln("All named args:")
  60. for _, arg := range c.Args() {
  61. fmt.Printf("- named arg '%s': %+v\n", arg.Name, arg.Value)
  62. }
  63. return nil
  64. }
  • display the command help:
  1. 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
  1. [=== ] -> [ === ] -> [ === ]

prog-demo

  • progress.DynamicText dynamic text message

Examples:

  1. package main
  2. import (
  3. "time"
  4. "github.com/gookit/gcli/v3/progress"
  5. )
  6. func main() {
  7. speed := 100
  8. maxSteps := 110
  9. p := progress.Bar(maxSteps)
  10. p.Start()
  11. for i := 0; i < maxSteps; i++ {
  12. time.Sleep(time.Duration(speed) * time.Millisecond)
  13. p.Advance()
  14. }
  15. p.Finish()
  16. }

more demos please see progress_demo.go

run demos:

  1. go run ./_examples/cliapp.go prog txt
  2. go run ./_examples/cliapp.go prog bar
  3. 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:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gookit/gcli/v3/interact"
  5. )
  6. func main() {
  7. username, _ := interact.ReadLine("Your name?")
  8. password := interact.ReadPassword("Your password?")
  9. ok := interact.Confirm("ensure continue?")
  10. if !ok {
  11. // do something...
  12. }
  13. fmt.Printf("username: %s, password: %s\n", username, password)
  14. }

Read Input

read user input message

  1. ans, _ := interact.ReadLine("Your name? ")
  2. if ans != "" {
  3. color.Println("Your input: ", ans)
  4. } else {
  5. color.Cyan.Println("No input!")
  6. }

interact-read

Select/Choice

  1. ans := interact.SelectOne(
  2. "Your city name(use array)?",
  3. []string{"chengdu", "beijing", "shanghai"},
  4. "",
  5. )
  6. color.Comment.Println("your select is: ", ans)

interact-select

Multi Select/Checkbox

  1. ans := interact.MultiSelect(
  2. "Your city name(use array)?",
  3. []string{"chengdu", "beijing", "shanghai"},
  4. nil,
  5. )
  6. color.Comment.Println("your select is: ", ans)

interact-select

Confirm Message

  1. if interact.Confirm("Ensure continue") {
  2. fmt.Println(emoji.Render(":smile: Confirmed"))
  3. } else {
  4. color.Warn.Println("Unconfirmed")
  5. }

interact-confirm

Read Password

  1. pwd := interact.ReadPassword()
  2. 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

  1. package main
  2. import (
  3. "github.com/gookit/color"
  4. )
  5. func main() {
  6. // simple usage
  7. color.Cyan.Printf("Simple to use %s\n", "color")
  8. // internal theme/style:
  9. color.Info.Tips("message")
  10. color.Info.Prompt("message")
  11. color.Warn.Println("message")
  12. color.Error.Println("message")
  13. // custom color
  14. color.New(color.FgWhite, color.BgBlack).Println("custom color style")
  15. // can also:
  16. color.Style{color.FgCyan, color.OpBold}.Println("custom color style")
  17. // use defined color tag
  18. color.Print("use color tag: <suc>he</><comment>llo</>, <cyan>wel</><red>come</>\n")
  19. // use custom color tag
  20. color.Print("custom color tag: <fg=yellow;bg=black;op=underscore;>hello, welcome</>\n")
  21. // set a style tag
  22. color.Tag("info").Println("info style text")
  23. // prompt message
  24. color.Info.Prompt("prompt style message")
  25. color.Warn.Prompt("prompt style message")
  26. // tips message
  27. color.Info.Tips("tips style message")
  28. color.Warn.Tips("tips style message")
  29. }

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