gcli

package module
v3.2.3 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2023 License: MIT Imports: 26 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.

中文说明

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

GoDoc

Install

go get github.com/gookit/gcli/v3

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)

    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 struct tags
package main

import (
	"fmt"

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

func main() {
	astr := "xyz"
	verb := gcli.VerbWarn

	cmd := 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(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

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

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

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(":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 use gookit/color Support windows cmd.exe powerShell

  • Color output display

colored-demo

Color 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.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")
}

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

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 (
	EvtAppInit = events.OnAppInitAfter

	EvtAppPrepareAfter = events.OnAppPrepared

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

	EvtCmdInit = events.OnCmdInitAfter

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

	EvtCmdOptParsed = events.OnCmdOptParsed

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

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

	EvtGOptionsParsed = events.OnGlobalOptsParsed
)

constants for hooks event, there are default allowed event names

View Source
const (
	// OK success exit code
	OK = 0
	// ERR error exit code
	ERR = 2
	// GOON prepare run successful, goon run command
	GOON = -1
	// CommandSep char
	CommandSep = ":"
	// HelpCommand name
	HelpCommand = "help"
	// VerbEnvName for set gcli debug level
	VerbEnvName = "GCLI_VERBOSE"
)
View Source
const HelpVarFormat = "{$%s}"

HelpVarFormat allow string replace on render help info.

Default support:

"{$binName}" "{$cmd}" "{$fullCmd}" "{$workDir}"

Variables

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

AppHelpTemplate help template for app(all commands)

View Source
var CmdHelpTemplate = `` /* 934-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 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 SetQuietMode

func SetQuietMode()

SetQuietMode level

func SetStrictMode

func SetStrictMode(strict bool)

SetStrictMode for parse flags

func SetVerbose

func SetVerbose(verbose VerbLevel)

SetVerbose 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[events.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) 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)

ChWorkDir 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 get a command by name

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

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

Config the application.

Notice: must be called before add command

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

func (*App) GetCommand

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

GetCommand get a command by name

func (*App) HasCommand

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

HasCommand 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 name check. alias of the HasCommand()

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 app GlobalOpts

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

func (b *App) WorkDir() string

WorkDir get work dirname

type AppConfig added in v3.1.0

type AppConfig struct {
	BeforeRun     func() bool
	AfterRun      func() bool
	BeforeAddOpts func(opts *Flags)
	AfterAddOpts  func(app *App) bool
}

AppConfig struct

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 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 the command
	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

	// Examples some usage example display
	Examples string

	// Func is the command handler func. Func Runner
	//
	// TIP:
	// 	func `args` is the remain arguments after parse flags(options and arguments).
	Func RunnerFunc
	// Help is the long help message text
	// Can use string-var in contents, eg: {$cmd}
	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 an 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)

ChWorkDir 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 get a command by name

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) 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) 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 command by name

func (*Command) HasCommand

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

HasCommand 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 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) 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 panic 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

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) 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) 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) 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) ChWorkDir added in v3.2.2

func (ctx *Context) ChWorkDir(dir string)

ChWorkDir work dir path

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

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

type GlobalOpts struct {
	Disable  bool
	NoColor  bool
	Verbose  VerbLevel // message report level
	ShowHelp bool
	// ShowVersion show version information
	ShowVersion bool
	// NoProgress dont display progress
	NoProgress bool
	// NoInteractive close interactive confirm
	NoInteractive bool
	// contains filtered or unexported fields
}

GlobalOpts global flag options

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

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

Runner /Executor interface

type RunnerFunc

type RunnerFunc func(c *Command, args []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, args []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 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
cmd
sflag
Package sflag is an simple cli flag parse tool
Package sflag is an simple cli flag parse tool
Package gflag provide command line options and arguments binding, parse, management.
Package gflag provide command line options and arguments binding, parse, management.
Package interact collect some interactive methods for CLI
Package interact collect some interactive methods for CLI
Package progress provide terminal progress bar display.
Package progress provide terminal progress bar display.
Package show provides some formatter tools for display data.
Package show provides some formatter tools for display data.

Jump to

Keyboard shortcuts

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