Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🖥 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命令补全脚本

License

NotificationsYou must be signed in to change notification settings

gookit/gcli

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GitHub go.mod Go versionActions StatusGitHub tag (latest SemVer)Codacy BadgeGo ReferenceGo Report CardCoverage 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 commandaliases
  • Support binding command options from structure
    • exampleflag:"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 settingRequired, indicating a required option parameter
    • Support settingValidator, which can customize the validation input parameters
  • argument - support binding argument to specify name
    • Supportrequired, optional,array settings
    • It will be automatically detected and collected when the command is run.
  • colorable - supports rich color output. provide bygookit/color
    • Supports html tab-style color rendering, compatible with Windows
    • Built-ininfo, 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 ofzsh andbash 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 gettag: [php, go]

Flag Arguments:

  • Support binding named argument
  • Support define array argument

GoDoc

Install

go get github.com/gookit/gcli/v3

Quick start

an example for quick start:

package mainimport ("github.com/gookit/gcli/v3""github.com/gookit/gcli/v3/_examples/cmd")// for test run: go build ./_examples/cliapp.go && ./cliappfuncmain() {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")returnnil        },    })// .... add more ...app.Run(nil)}

Binding flags

flags binding and manage by builtingflag.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,shortsstring,defValuebool,descstring)BoolVar(p*bool,metaFlagMeta)Float64Opt(p*float64,name,shortsstring,defValuefloat64,descstring)Float64Var(p*float64,metaFlagMeta)Int64Opt(p*int64,name,shortsstring,defValueint64,descstring)Int64Var(p*int64,metaFlagMeta)IntOpt(p*int,name,shortsstring,defValueint,descstring)IntVar(p*int,metaFlagMeta)StrOpt(p*string,name,shorts,defValue,descstring)StrVar(p*string,metaFlagMeta)Uint64Opt(p*uint64,name,shortsstring,defValueuint64,descstring)Uint64Var(p*uint64,metaFlagMeta)UintOpt(p*uint,name,shortsstring,defValueuint,descstring)UintVar(p*uint,metaFlagMeta)Var(pflag.Value,metaFlagMeta)VarOpt(pflag.Value,name,shorts,descstring)

Usage examples:

varidintvarbboolvaropt,dirstringvarf1float64varnames gcli.Strings// bind optionscmd.IntOpt(&id,"id","",2,"the id option")cmd.BoolOpt(&b,"bl","b",false,"the bool option")// notice `DIRECTORY` will replace to option value typecmd.StrOpt(&dir,"dir","d","","the `DIRECTORY` option")// setting option name and short-option namecmd.StrOpt(&opt,"opt","o","","the option message")// setting a special option var, it must implement the flag.Value interfacecmd.VarOpt(&names,"names","n","the option message")

Use struct tags

package mainimport ("fmt""github.com/gookit/gcli/v3")typeuserOptsstruct {Intint`flag:"name=int0;shorts=i;required=true;desc=int option message"`Bolbool`flag:"name=bol;shorts=b;desc=bool option message"`Str1string`flag:"name=str1;shorts=o,h;required=true;desc=str1 message"`// use ptrStr2*string`flag:"name=str2;required=true;desc=str2 message"`// custom type and implement flag.ValueVerb0 gcli.VerbLevel`flag:"name=verb0;shorts=V;desc=verb0 message"`// use ptrVerb1*gcli.VerbLevel`flag:"name=verb1;desc=verb1 message"`}funcmain() {astr:="xyz"verb:=gcli.VerbWarncmd:=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(argArgument)*ArgumentAddArg(name,descstring,requiredAndArrayed...bool)*ArgumentAddArgByRule(name,rulestring)*ArgumentAddArgument(arg*Argument)*ArgumentBindArg(argArgument)*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 useArg()/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,})

useAddArgByRule:

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())returnnil            },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")returnnil    },})

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 // displayhelp$ go build ./_examples/cliapp.go&& ./cliapp genac // run gencommand

will see:

INFO:   {shell:zsh binName:cliapp output:auto-completion.zsh}Now, will write content to file auto-completion.zshContinue? [yes|no](default yes): yOK, auto-complete file generate successful

After running, it will generate anauto-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 seegodoc

Quick create

varMyCmd=&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")returnnil    },// allow add multi level subcommandsSubs: []*gcli.Command{},}

Write go file

the source file at:example.go

package mainimport ("fmt""github.com/gookit/color""github.com/gookit/gcli/v3""github.com/gookit/goutil/dump")// options for the commandvarexampleOpts=struct {idintcstringdirstringoptstringnames gcli.Strings}{}// ExampleCommand command definitionvarExampleCommand=&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 typec.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 argumentsc.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 arrVal2funcexampleExecute(c*gcli.Command,args []string)error {color.Infoln("hello, in example command")ifexampleOpts.showErr {returnc.NewErrf("OO, An error has occurred!!")}magentaln:=color.Magenta.Printlncolor.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:=rangec.Args() {fmt.Printf("- named arg '%s': %+v\n",arg.Name,arg.Value)}returnnil}
  • 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 mainimport ("time""github.com/gookit/gcli/v3/progress")funcmain()  {speed:=100maxSteps:=110p:=progress.Bar(maxSteps)p.Start()fori:=0;i<maxSteps;i++ {time.Sleep(time.Duration(speed)*time.Millisecond)p.Advance()}p.Finish()}

more demos please seeprogress_demo.go

run demos:

go run ./_examples/cliapp.go prog txtgo run ./_examples/cliapp.go prog bargo 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 mainimport ("fmt""github.com/gookit/gcli/v3/interact")funcmain() {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? ")ifans!="" {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

ifinteract.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 usegookit/color Support windowscmd.exepowerShell

  • Color output display

colored-demo

Color usage

package mainimport ("github.com/gookit/color")funcmain() {// simple usagecolor.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 colorcolor.New(color.FgWhite,color.BgBlack).Println("custom color style")// can also:color.Style{color.FgCyan,color.OpBold}.Println("custom color style")// use defined color tagcolor.Print("use color tag: <suc>he</><comment>llo</>, <cyan>wel</><red>come</>\n")// use custom color tagcolor.Print("custom color tag: <fg=yellow;bg=black;op=underscore;>hello, welcome</>\n")// set a style tagcolor.Tag("info").Println("info style text")// prompt messagecolor.Info.Prompt("prompt style message")color.Warn.Prompt("prompt style message")// tips messagecolor.Info.Tips("tips style message")color.Warn.Tips("tips style message")}

For more information on the use of color libraries, please visitgookit/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 seehttps://github.com/gookit

See also

License

MIT

About

🖥 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命令补全脚本

Topics

Resources

License

Stars

Watchers

Forks

Languages


[8]ページ先頭

©2009-2025 Movatter.jp