All Projects → gookit → Gcli

gookit / Gcli

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

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Gcli

Pyinquirer
A Python module for common interactive command line user interfaces
Stars: ✭ 1,151 (+512.23%)
Mutual labels:  cli-app, cli, command-line
Tooling
Advancing Node.js as a framework for writing great tools
Stars: ✭ 98 (-47.87%)
Mutual labels:  cli, command-line, console
Window Size
Reliable way to to get the height and width of the terminal/console in a node.js environment.
Stars: ✭ 79 (-57.98%)
Mutual labels:  cli, command-line, console
Wonders
🌈 Declarative JavaScript framework to build command-line applications.
Stars: ✭ 34 (-81.91%)
Mutual labels:  cli, command-line, console
Nnn
n³ The unorthodox terminal file manager
Stars: ✭ 13,138 (+6888.3%)
Mutual labels:  cli, command-line, console
Crossline
A small, self-contained, zero-config, MIT licensed, cross-platform, readline and libedit replacement.
Stars: ✭ 53 (-71.81%)
Mutual labels:  cli, command-line, console
Terminal layout
The project help you to quickly build layouts in terminal,cross-platform(一个跨平台的命令行ui布局工具)
Stars: ✭ 98 (-47.87%)
Mutual labels:  cli-app, cli, command-line
Cobra
A Commander for modern Go CLI interactions
Stars: ✭ 24,437 (+12898.4%)
Mutual labels:  cli-app, cli, command-line
Clrcli
CLRCLI is an event-driven library for building line-art user interfaces in C#/.Net command-line applications.
Stars: ✭ 124 (-34.04%)
Mutual labels:  cli, command-line, console
Word Wrap
Wrap words to a specified length.
Stars: ✭ 107 (-43.09%)
Mutual labels:  cli, command-line, console
Sade
Smooth (CLI) Operator 🎶
Stars: ✭ 746 (+296.81%)
Mutual labels:  cli-app, cli, command-line
Mandown
man-page inspired Markdown viewer
Stars: ✭ 173 (-7.98%)
Mutual labels:  cli, command-line, console
Carbon Now Cli
🎨 Beautiful images of your code — from right inside your terminal.
Stars: ✭ 5,165 (+2647.34%)
Mutual labels:  cli-app, cli, command-line
Rang
A Minimal, Header only Modern c++ library for terminal goodies 💄✨
Stars: ✭ 1,080 (+474.47%)
Mutual labels:  cli, command-line, console
Ttyplot
a realtime plotting utility for terminal/console with data input from stdin
Stars: ✭ 532 (+182.98%)
Mutual labels:  cli-app, cli, console
Forge Node App
🛠📦🎉 Generate Node.js boilerplate with optional libraries & tools
Stars: ✭ 90 (-52.13%)
Mutual labels:  cli-app, cli, command-line
Caporal.js
A full-featured framework for building command line applications (cli) with node.js
Stars: ✭ 3,279 (+1644.15%)
Mutual labels:  cli-app, cli, command-line
Cocona
Micro-framework for .NET Core console application. Cocona makes it easy and fast to build console applications on .NET Core.
Stars: ✭ 398 (+111.7%)
Mutual labels:  cli, command-line, console
Simple Console
Add an elegant command-line interface to any page
Stars: ✭ 107 (-43.09%)
Mutual labels:  cli, command-line, console
Git Tidy
Tidy up stale git branches.
Stars: ✭ 137 (-27.13%)
Mutual labels:  cli-app, cli, command-line

GCli

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

A simple-to-use command line application, written using golang.

中文说明

中文说明请看 README.zh-CN

Screenshots

app-cmd-list

Features

  • Simple 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

GoDoc

Install

go get github.com/gookit/gcli/v3

Quick start

package main

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

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

    app.Add(cmd.ExampleCommand())
    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}", 
        Aliases: []string{"dm"},
        Func: func (cmd *gcli.Command, args []string) error {
            gcli.Print("hello, in the demo command\n")
            return 0
        },
    })

    // .... add more ...

    app.Run()
}

Usage

  • build a demo package
% go build ./_examples/cliapp.go                                                           

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

./cliapp COMMAND [--OPTION VALUE -S VALUE ...] [ARGUMENT0 ARGUMENT1 ...]
% ./cliapp example -c some.txt -d ./dir --id 34 -n tom -n john val0 val1 val2 arrVal0 arrVal1 arrVal2

you can see:

run-example

Display Command Help

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

cmd-help

Error Command Tips

command tips

Generate Auto Completion Scripts

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

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

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

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

will see:

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

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

OK, auto-complete file generate successful

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

Generated shell script file ref:

Preview:

auto-complete-tips

Write a command

Quick add

app.Add(&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
    },
})

Write go file

the source file at: example.go

package cmd

import (
	"fmt"

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

// 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) {
		// 绑定命令选项信息
		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")

		// 绑定命令参数信息,按参数位置绑定
		c.AddArg("arg0", "the first argument, is required", true)
		c.AddArg("arg1", "the second argument, is required", true)
		c.AddArg("arg2", "the optional argument, is optional")
		c.AddArg("arrArg", "the array argument, is array", false, 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 {
	fmt.Print("hello, in example command\n")

	magentaln := color.Magenta.Println

	magentaln("All options:")
	fmt.Printf("%+v\n", exampleOpts)
	magentaln("Raw args:")
	fmt.Printf("%v\n", args)

	magentaln("Get arg by name:")
	arr := c.Arg("arrArg")
	fmt.Printf("named array 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)
	}

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

cmd-help

Bind Option(flag)

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

Bind Argument

About arguments:

  • Required argument cannot be defined after optional argument
  • Only one array parameter is allowed
  • The (array)argument of multiple values ​​can only be defined at the end

Available methods:

Add(arg Argument) *Argument
AddArg(name, desc string, requiredAndIsArray ...bool) *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():

cmd.Arg("arg0", gcli.Argument{
	Name: "ag0",
	Desc: "the first argument, is required",
	Require: true,
})
cmd.BindArg("arg0", gcli.Argument{
	Name: "ag0",
	Desc: "the second argument, is required",
	Require: true,
})
cmd.Arg("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",
	IsArray: true,
})

Progress display

Package progress provide terminal progress bar display.

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

  • progress.Bar progress bar

Demo: ./cliapp prog bar

prog-bar

  • progress.Txt text progress bar

Demo: ./cliapp prog txt

prog-bar

  • progress.LoadBar pending/loading progress bar

prog-demo

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

prog-demo

  • progress.DynamicText dynamic text message

Examples:

package main

import (
	"time"

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

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

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

	p.Finish()
}

more demos please see progress_demo.go

run demos:

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

prog-other

Interactive methods

console interactive methods

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

Examples:

package main

import (
	"fmt"

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

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

Read Input

read user input message

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

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

interact-read

Select/Choice

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

interact-select

Multi Select/Checkbox

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

interact-select

Confirm Message

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

interact-confirm

Read Password

pwd := interact.ReadPassword()

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

interact-passwd

CLI Color

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

  • Color output display

colored-demo

Usage

package main

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

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

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

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

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

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

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

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

More usage

  • Basic color
color.Bold.Println("bold message")
color.Yellow.Println("yellow message")
  • Extra themes
color.Info.Println("Info message")
color.Danger.Println("Danger message")
color.Error.Println("Error message")
color.Success.Println("Success message")
  • Use like html tag

Support working on windows cmd.exe powerShell

// use style tag
color.Print("<suc>he</><comment>llo</>, <cyan>wel</><red>come</>")
color.Println("<suc>hello</>")
color.Println("<error>hello</>")
color.Println("<warning>hello</>")

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

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].