gcli

package module
v2.3.1 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2020 License: MIT Imports: 19 Imported by: 14

README

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.

Since v2.3.0, option binding and argument binding have been reconstructed, which may be incompatible with the previous ones.

中文说明

中文说明请看 README.zh-CN

Screenshots

app-cmd-list

Features

  • Simple to use
  • Support for adding multiple commands and supporting command aliases
  • When the command entered is incorrect, a similar command will be prompted(including an alias prompt)
  • Support option binding --long, support for adding short options(-s)
  • POSIX-style short flag combining (-a -b = -ab).
  • Support binding argument to specified name, support required, optional, array three settings
    • It will be automatically detected and collected when the command is run.
  • Supports rich color output. powered 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
  • Built-in user interaction methods: ReadLine, Confirm, Select, MultiSelect ...
  • Built-in progress display methods: Txt, Bar, Loading, RoundTrip, DynamicText ...
  • Automatically generate command help information and support color display
  • 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/v2

Quick start

package main

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

// for test run: go build ./_examples/cliapp.go && ./cliapp
func main() {
    app := gcli.NewApp()
    app.Version = "1.0.3"
    app.Description = "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'
        UseFor: "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/v2/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

About argument definition
  • 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
Simple use
app.Add(&gcli.Command{
    Name: "demo",
    // allow color tag and {$cmd} will be replace to 'demo'
    UseFor: "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/v2"
)

// options for the command
var exampleOpts = struct {
	id  int
	c   string
	dir string
	opt string
	names gcli.Strings
}{}

// ExampleCommand command definition
func ExampleCommand() *gcli.Command {
	cmd := &gcli.Command{
		Name:        "example",
		UseFor: "this is a description message",
		Aliases:     []string{"exp", "ex"},
		Func:          exampleExecute,
		// {$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`,
	}

	// bind options
	cmd.IntOpt(&exampleOpts.id, "id", "", 2, "the id option")
	cmd.StrOpt(&exampleOpts.c, "config", "c", "value", "the config option")
	// notice `DIRECTORY` will replace to option value type
	cmd.StrOpt(&exampleOpts.dir, "dir", "d", "", "the `DIRECTORY` option")
	// setting option name and short-option name
	cmd.StrOpt(&exampleOpts.opt, "opt", "o", "", "the option message")
	// setting a special option var, it must implement the flag.Value interface
	cmd.VarOpt(&exampleOpts.names, "names", "n", "the option message")

	// bind args with names
	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)

	return cmd
}

// command running
// 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

Progress display

Package progress provide terminal progress bar display. Such as: Txt, Bar, Loading, RoundTrip, DynamicText ...

  • progress.Bar progress bar

prog-demo

  • progress.Txt text progress bar
Data handling ... ... 50% (25/50)
  • 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/v2/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"
import "github.com/gookit/gcli/v2/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
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

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

support on windows cmd.exe

  • color.Bold
  • color.Black
  • color.White
  • color.Gray
  • color.Red
  • color.Green
  • color.Yellow
  • color.Blue
  • color.Magenta
  • color.Cyan
color.Bold.Println("bold message")
color.Yellow.Println("yellow message")
Extra themes

support on windows cmd.exe

  • color.Info
  • color.Note
  • color.Light
  • color.Error
  • color.Danger
  • color.Notice
  • color.Success
  • color.Comment
  • color.Primary
  • color.Warning
  • color.Question
  • color.Secondary
color.Info.Println("Info 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

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 (
	VerbQuiet uint = iota // don't report anything
	VerbError             // reporting on error
	VerbWarn
	VerbInfo
	VerbDebug
	VerbCrazy
)

constants for error level 0 - 4

View Source
const (
	EvtAppInit   = "app.init"
	EvtAppBefore = "app.run.before"
	EvtAppAfter  = "app.run.after"
	EvtAppError  = "app.run.error"

	EvtCmdInit   = "cmd.init"
	EvtCmdBefore = "cmd.run.before"
	EvtCmdAfter  = "cmd.run.after"
	EvtCmdError  = "cmd.run.error"

	EvtAppPrepareAfter = "app.prepare.after"
)

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
	// HelpCommand name
	HelpCommand = "help"
)
View Source
const (
	AlignLeft  = strutil.PosRight
	AlignRight = strutil.PosLeft
)

The options alignment type - Align right, padding left - Align left, padding right

View Source
const HelpVarFormat = "{$%s}"

HelpVarFormat allow var replace on render help info. Default support:

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

Variables

View Source
var (

	// CLI create an default instance
	CLI = &cmdLine{
		pid: os.Getpid(),

		osName:  runtime.GOOS,
		binName: os.Args[0],
		argLine: strings.Join(os.Args[1:], " "),
	}
)
View Source
var Version = "2.2.1"

Version the gCli version

Functions

func Exit

func Exit(code int)

Exit program

func Logf

func Logf(level uint, format string, v ...interface{})

Logf print log message

func Print

func Print(args ...interface{})

Print messages

func Printf

func Printf(format string, args ...interface{})

Printf messages

func Println

func Println(args ...interface{})

Println messages

func SetDebugMode

func SetDebugMode()

SetDebugMode level

func SetQuietMode

func SetQuietMode()

SetQuietMode level

func SetStrictMode added in v2.0.9

func SetStrictMode(strict bool)

SetStrictMode for parse flags

func SetVerbose

func SetVerbose(verbose uint)

SetVerbose level

func StrictMode added in v2.0.10

func StrictMode() bool

StrictMode get is strict mode

func Verbose

func Verbose() uint

Verbose returns verbose level

Types

type App

type App struct {

	// Name app name
	Name string
	// Version app version. like "1.0.1"
	Version string
	// Description app description
	Description string
	Logo Logo
	// Args default is equals to os.args
	Args []string
	// ExitOnEnd call os.Exit on running end
	ExitOnEnd bool
	// ExitFunc default is os.Exit
	ExitFunc func(int)
	// contains filtered or unexported fields
}

App the cli app definition

func InitStdApp added in v2.0.9

func InitStdApp(fn ...func(a *App)) *App

InitStdApp create the default cli app.

func NewApp

func NewApp(fn ...func(a *App)) *App

NewApp create new app instance. Usage:

NewApp()
// Or with a config func
NewApp(func(a *App) {
	// do something before init ....
	a.Hooks[gcli.EvtInit] = func () {}
})

func StdApp added in v2.0.9

func StdApp() *App

StdApp get the default std app

func (*App) Add

func (app *App) Add(c *Command, more ...*Command)

Add add one or multi command(s)

func (*App) AddAliases

func (app *App) AddAliases(command string, aliases ...string)

AddAliases add alias names for a command

func (*App) AddCommand

func (app *App) AddCommand(c *Command) *Command

AddCommand add a new command

func (*App) AddCommander added in v2.3.0

func (app *App) AddCommander(cmder Commander) *Command

AddCommander to the application

func (*App) AddError

func (app *App) AddError(err error)

AddError to the application

func (*App) CleanArgs

func (app *App) CleanArgs() []string

CleanArgs get clean args

func (*App) CommandName

func (app *App) CommandName() string

CommandName get current command name

func (*App) CommandNames

func (app *App) CommandNames() []string

CommandNames get all command names

func (*App) Commands

func (app *App) Commands() map[string]*Command

Commands get all commands

func (*App) Config

func (app *App) Config(fn func(a *App))

Config the application. Notice: must be called before adding a command

func (*App) DefaultCommand

func (app *App) DefaultCommand(name string)

DefaultCommand set default command name

func (*App) Exec

func (app *App) Exec(name string, args []string) (err error)

Exec running other command in current command

func (*App) Exit added in v2.3.0

func (app *App) Exit(code int)

Exit get the app GlobalFlags

func (App) GlobalFlags added in v2.3.0

func (c App) GlobalFlags() *Flags

GlobalFlags get the app GlobalFlags

func (*App) HasCommand added in v2.3.0

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

HasCommand in the application

func (*App) IsAlias added in v2.3.0

func (app *App) IsAlias(str string) bool

IsAlias name check

func (*App) IsCommand

func (app *App) IsCommand(name string) bool

IsCommand name check

func (*App) Names

func (app *App) Names() map[string]int

Names get all command names

func (*App) NewCommand

func (app *App) NewCommand(name, useFor string, config func(c *Command)) *Command

NewCommand create a new command

func (*App) On

func (app *App) On(name string, handler HookFunc)

On add hook handler for a hook event

func (*App) RealCommandName

func (app *App) RealCommandName(alias string) string

RealCommandName get real command name by alias Deprecated

func (*App) RemoveCommand added in v2.3.0

func (app *App) RemoveCommand(names ...string) int

RemoveCommand from the application

func (*App) ResolveName added in v2.3.0

func (app *App) ResolveName(alias string) string

ResolveName get real command name by alias

func (*App) Run

func (app *App) Run() (code int)

Run running application

func (*App) SetDebugMode

func (app *App) SetDebugMode()

SetDebugMode level

func (app *App) SetLogo(logo string, style ...string)

SetLogo text and color style

func (*App) SetQuietMode

func (app *App) SetQuietMode()

SetQuietMode level

func (*App) SetVerbose

func (app *App) SetVerbose(verbose uint)

SetVerbose level

type Argument

type Argument struct {
	// Name argument name. it's required
	Name string
	// Desc argument description message
	Desc string
	// Type name. eg: string, int, array
	// Type string
	// ShowName is a name for display help. default is equals to Name.
	ShowName string
	// Required arg is required
	Required bool
	// IsArray if is array, can allow accept multi values, and must in last.
	IsArray bool
	// valWrapper Value TODO ...
	// value store parsed argument data. (type: string, []string)
	Value interface{}
	// Handler custom argument value parse handler
	Handler func(val interface{}) interface{}
	// Validator you can add an validator, will call it on binding argument value
	Validator func(val interface{}) (interface{}, error)
	// contains filtered or unexported fields
}

Argument a command argument definition

func NewArgument added in v2.1.0

func NewArgument(name, desc string, requiredAndIsArray ...bool) *Argument

NewArgument quick create an new command argument

func (*Argument) Array

func (a *Argument) Array() (ss []string)

Array alias of the Strings()

func (*Argument) Config added in v2.1.1

func (a *Argument) Config(fn func(arg *Argument))

Config the argument

func (*Argument) GetValue added in v2.1.0

func (a *Argument) GetValue() interface{}

GetValue get value by custom handler func

func (*Argument) HasValue

func (a *Argument) HasValue() bool

HasValue value is empty

func (*Argument) HelpName added in v2.3.0

func (a *Argument) HelpName() string

HelpName for render help message

func (*Argument) Index added in v2.1.0

func (a *Argument) Index() int

Index get argument index in the command

func (*Argument) Int

func (a *Argument) Int(defVal ...int) int

Int argument value to int

func (*Argument) IsEmpty added in v2.1.0

func (a *Argument) IsEmpty() bool

IsEmpty argument is empty

func (*Argument) String

func (a *Argument) String(defVal ...string) string

String argument value to string

func (*Argument) StringSplit added in v2.1.0

func (a *Argument) StringSplit(sep ...string) (ss []string)

StringSplit quick split a string argument to string slice

func (*Argument) Strings

func (a *Argument) Strings() (ss []string)

Strings argument value to string array, if argument isArray = true.

func (*Argument) WithValidator added in v2.1.1

func (a *Argument) WithValidator(fn func(interface{}) (interface{}, error)) *Argument

WithValidator set an value validator of the argument

func (*Argument) WithValue added in v2.1.1

func (a *Argument) WithValue(val interface{}) *Argument

WithValue set an value of the argument

type Arguments added in v2.3.0

type Arguments struct {
	// contains filtered or unexported fields
}

Arguments definition

func (*Arguments) Add added in v2.3.0

func (ags *Arguments) Add(arg Argument) *Argument

Add alias of the AddArgument()

func (*Arguments) AddArg added in v2.3.0

func (ags *Arguments) AddArg(name, desc string, requiredAndIsArray ...bool) *Argument

AddArg binding an named argument for the command. Notice:

  • 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

Usage:

cmd.AddArg("name", "description")
cmd.AddArg("name", "description", true) // required
cmd.AddArg("names", "description", true, true) // required and is array

func (*Arguments) AddArgument added in v2.3.0

func (ags *Arguments) AddArgument(arg *Argument) *Argument

AddArgument binding an named argument for the command.

Notice:

  • 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

func (*Arguments) Arg added in v2.3.0

func (ags *Arguments) Arg(name string) *Argument

Arg get arg by defined name. Usage:

intVal := ags.Arg("name").Int()
strVal := ags.Arg("name").String()
arrVal := ags.Arg("names").Array()

func (*Arguments) ArgByIndex added in v2.3.0

func (ags *Arguments) ArgByIndex(i int) *Argument

ArgByIndex get named arg by index

func (*Arguments) Args added in v2.3.0

func (ags *Arguments) Args() []*Argument

Args get all defined argument

func (*Arguments) BindArg added in v2.3.0

func (ags *Arguments) BindArg(arg Argument) *Argument

BindArg alias of the AddArgument()

func (*Arguments) ParseArgs added in v2.3.0

func (ags *Arguments) ParseArgs(args []string) (err error)

ParseArgs for Arguments

func (*Arguments) SetName added in v2.3.0

func (ags *Arguments) SetName(name string)

SetName for Arguments

func (*Arguments) SetValidateNum added in v2.3.0

func (ags *Arguments) SetValidateNum(validateNum bool)

SetValidateNum check

type Booleans

type Booleans []bool

Booleans The bool flag list, implemented flag.Value interface

func (*Booleans) Set

func (s *Booleans) Set(value string) error

Set new value

func (*Booleans) String

func (s *Booleans) String() string

String to string

type CmdFunc

type CmdFunc func(c *Command, args []string) error

CmdFunc definition

func (CmdFunc) Run

func (f CmdFunc) Run(c *Command, args []string) error

Run implement the Runner interface

type Command

type Command struct {

	// Name is the command name.
	Name string

	// UseFor is the command description message.
	UseFor string
	// Aliases is the command name's alias names
	Aliases []string
	// Config func, will call on `initialize`.
	// - you can config options and other init works
	Config func(c *Command)
	// Flags(command options) is a set of flags specific to this command.
	// Flags flag.FlagSet
	// Examples some usage example display
	Examples string
	// Func is the command handler func. Func Runner
	Func CmdFunc
	// Help is the long help message text
	Help string

	// CustomFlags indicates that the command will do its own flag parsing.
	CustomFlags bool
	// Flags options for the command.
	Flags
	// Arguments for the command
	Arguments
	// contains filtered or unexported fields
}

Command a CLI command structure

func NewCommand

func NewCommand(name, useFor string, fn ...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) AliasesString

func (c *Command) AliasesString(sep ...string) string

AliasesString returns aliases string

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

func (c *Command) Errorf(format string, v ...interface{}) error

Errorf format message and add error to the command

func (*Command) Fire

func (c *Command) Fire(event string, data interface{})

Fire event handler by name

func (Command) GlobalFlags added in v2.3.0

func (c Command) GlobalFlags() *Flags

GlobalFlags get the app GlobalFlags

func (*Command) ID

func (c *Command) ID() string

ID get command ID name.

func (*Command) IsAlone

func (c *Command) IsAlone() bool

IsAlone running

func (*Command) IsDisabled

func (c *Command) IsDisabled() bool

IsDisabled get cmd is disabled

func (*Command) Logf

func (c *Command) Logf(level uint, format string, v ...interface{})

Logf print log message

func (*Command) Module

func (c *Command) Module() string

Module name of the grouped command

func (*Command) MustRun

func (c *Command) MustRun(inArgs []string)

MustRun Alone the current command, will panic on error

func (*Command) NotAlone

func (c *Command) NotAlone() bool

NotAlone running

func (*Command) On

func (c *Command) On(name string, handler HookFunc)

On add hook handler for a hook event

func (*Command) Run

func (c *Command) Run(inArgs []string) (err error)

Run Alone the current command

func (*Command) Runnable

func (c *Command) Runnable() bool

Runnable reports whether the command can be run; otherwise it is a documentation pseudo-command such as import path.

func (*Command) SetFunc

func (c *Command) SetFunc(fn CmdFunc) *Command

SetFunc Settings command handler func

func (*Command) ShowHelp

func (c *Command) ShowHelp()

ShowHelp show command help info

type Commander added in v2.3.0

type Commander interface {
	// Creator for create new command
	Creator() *Command
	// Prepare bind Flags or Arguments for the command
	Prepare(c *Command)
	// Execute(c *Command, args []string) error
	Run(c *Command, args []string) error
}

Commander interface definition

type Executor added in v2.3.0

type Executor interface {
}

Executor definition

type FlagMeta added in v2.3.0

type FlagMeta struct {
	// varPtr interface{}
	// name and description
	Name, Desc string
	// default value for the flag option
	DefVal interface{}

	// short names. eg: ["o", "a"]
	Shorts []string
	// special setting
	Hidden, Required bool
	// contains filtered or unexported fields
}

FlagMeta for an flag(option/argument)

func (*FlagMeta) DValue added in v2.3.0

func (m *FlagMeta) DValue() *goutil.Value

DValue wrap the default value

func (*FlagMeta) Description added in v2.3.0

func (m *FlagMeta) Description() string

Description of the flag

type Flags added in v2.3.0

type Flags struct {
	// FlagsOption option for render help message
	FlagsOption
	// contains filtered or unexported fields
}

Flags struct definition

func NewFlags added in v2.3.0

func NewFlags(name ...string) *Flags

NewFlags create an new Flags

func (*Flags) BoolOpt added in v2.3.0

func (fs *Flags) BoolOpt(p *bool, name, shorts string, defValue bool, desc string)

BoolOpt binding an bool option

func (*Flags) BoolVar added in v2.3.0

func (fs *Flags) BoolVar(p *bool, meta FlagMeta)

BoolVar binding an bool option flag

func (*Flags) FSet added in v2.3.0

func (fs *Flags) FSet() *flag.FlagSet

FSet get the raw *flag.FlagSet

func (*Flags) FlagMeta added in v2.3.0

func (fs *Flags) FlagMeta(name string) *FlagMeta

FlagMeta get FlagMeta by name

func (*Flags) FlagNames added in v2.3.0

func (fs *Flags) FlagNames() map[string]int

FlagNames return all option names

func (*Flags) Float64Opt added in v2.3.0

func (fs *Flags) Float64Opt(p *float64, name, shorts string, defValue float64, desc string)

Float64Opt binding an float64 option

func (*Flags) Float64Var added in v2.3.0

func (fs *Flags) Float64Var(p *float64, meta FlagMeta)

Float64Var binding an float64 option flag

func (*Flags) FromStruct added in v2.3.0

func (fs *Flags) FromStruct(ptr interface{}) error

FromStruct from struct tag binding options

func (*Flags) HasFlagMeta added in v2.3.0

func (fs *Flags) HasFlagMeta(name string) bool

HasFlagMeta check it is has FlagMeta

func (*Flags) HasOption added in v2.3.0

func (fs *Flags) HasOption(name string) bool

HasOption check it is a option name

func (*Flags) InitFlagSet added in v2.3.0

func (fs *Flags) InitFlagSet(name string)

create and init flag.FlagSet

func (*Flags) Int64Opt added in v2.3.0

func (fs *Flags) Int64Opt(p *int64, name, shorts string, defValue int64, desc string)

Int64Opt binding an int64 option

func (*Flags) Int64Var added in v2.3.0

func (fs *Flags) Int64Var(p *int64, meta FlagMeta)

Int64Var binding an uint option flag

func (*Flags) IntOpt added in v2.3.0

func (fs *Flags) IntOpt(p *int, name, shorts string, defValue int, desc string)

IntOpt binding an int option

func (*Flags) IntVar added in v2.3.0

func (fs *Flags) IntVar(p *int, meta FlagMeta)

IntVar binding an int option flag

func (*Flags) IsShortName added in v2.3.0

func (fs *Flags) IsShortName(short string) bool

IsShortcut check it is a shortcut name

func (*Flags) IsShortOpt added in v2.3.0

func (fs *Flags) IsShortOpt(short string) bool

IsShortOpt alias of the IsShortcut()

func (*Flags) IterAll added in v2.3.0

func (fs *Flags) IterAll(fn func(f *flag.Flag, meta *FlagMeta))

IterAll Iteration all flag options with metadata

func (*Flags) LookupFlag added in v2.3.0

func (fs *Flags) LookupFlag(name string) *flag.Flag

LookupFlag get flag.Flag by name

func (*Flags) Metas added in v2.3.0

func (fs *Flags) Metas() map[string]*FlagMeta

Metas get all flag metas

func (*Flags) Name added in v2.3.0

func (fs *Flags) Name() string

Name of the Flags

func (*Flags) Parse added in v2.3.0

func (fs *Flags) Parse(args []string) error

Parse given arguments

func (*Flags) PrintHelpPanel added in v2.3.0

func (fs *Flags) PrintHelpPanel()

PrintHelpPanel for all options to the gf.out

func (*Flags) RawArg added in v2.3.0

func (fs *Flags) RawArg(i int) string

RawArg get an argument value by index

func (*Flags) RawArgs added in v2.3.0

func (fs *Flags) RawArgs() []string

RawArgs get all raw arguments

func (*Flags) SetFlagSet added in v2.3.0

func (fs *Flags) SetFlagSet(fSet *flag.FlagSet)

SetFlagSet set the raw *flag.FlagSet

func (*Flags) SetOutput added in v2.3.0

func (fs *Flags) SetOutput(out io.Writer)

SetOutput for the Flags

func (*Flags) ShortNames added in v2.3.0

func (fs *Flags) ShortNames(name string) (ss []string)

ShortNames get all short-names of the option

func (*Flags) StrOpt added in v2.3.0

func (fs *Flags) StrOpt(p *string, name, shorts, defValue, desc string)

StrOpt binding an string option

func (*Flags) StrVar added in v2.3.0

func (fs *Flags) StrVar(p *string, meta FlagMeta)

StrVar binding an string option flag

func (*Flags) String added in v2.3.0

func (fs *Flags) String() string

String for all flag options

func (*Flags) Uint64Opt added in v2.3.0

func (fs *Flags) Uint64Opt(p *uint64, name, shorts string, defValue uint64, desc string)

Uint64Opt binding an uint64 option

func (*Flags) Uint64Var added in v2.3.0

func (fs *Flags) Uint64Var(p *uint64, meta FlagMeta)

Uint64Var binding an uint option flag

func (*Flags) UintOpt added in v2.3.0

func (fs *Flags) UintOpt(p *uint, name, shorts string, defValue uint, desc string)

UintOpt binding an uint option

func (*Flags) UintVar added in v2.3.0

func (fs *Flags) UintVar(p *uint, meta FlagMeta)

UintVar binding an uint option flag

func (*Flags) Var added in v2.3.0

func (fs *Flags) Var(p flag.Value, meta FlagMeta)

Var binding an custom var option flag

func (*Flags) VarOpt added in v2.3.0

func (fs *Flags) VarOpt(p flag.Value, name, shorts, desc string)

VarOpt binding a custom var option Usage:

var names gcli.Strings
cmd.VarOpt(&names, "tables", "t", "description ...")

func (*Flags) WithOption added in v2.3.0

func (fs *Flags) WithOption(cfg FlagsOption) *Flags

WithOption for render help panel message

type FlagsOption added in v2.3.0

type FlagsOption struct {
	// WithoutType dont display flag data type on print help
	WithoutType bool
	// NameDescOL flag and desc at one line on print help
	NameDescOL bool
	// Alignment flag align left or right. default is: right
	Alignment uint8
}

FlagsOption for render help information

type GlobalOpts

type GlobalOpts struct {
	// contains filtered or unexported fields
}

GlobalOpts global flags

type HelpVars

type HelpVars struct {
	// varLeft, varRight string
	// varFormat string
	// Vars you can add some vars map for render help info
	Vars map[string]string
}

HelpVars struct. provide string var function for render help template.

func (*HelpVars) AddVar

func (hv *HelpVars) AddVar(name, value string)

AddVar get command name

func (*HelpVars) AddVars

func (hv *HelpVars) AddVars(vars map[string]string)

AddVars add multi tpl vars

func (*HelpVars) GetVar

func (hv *HelpVars) GetVar(name string) string

GetVar get a help var by name

func (*HelpVars) GetVars

func (hv *HelpVars) GetVars() map[string]string

GetVars get all tpl vars

func (*HelpVars) ReplaceVars

func (hv *HelpVars) ReplaceVars(input string) string

ReplaceVars replace vars in the input string.

type HookFunc

type HookFunc func(obj ...interface{})

HookFunc definition. func arguments:

in app, like: func(app *App, data interface{})
in cmd, like: func(cmd *Command, data interface{})

type HookFunc func(obj interface{}, data interface{})

type Hooks added in v2.3.0

type Hooks struct {
	// contains filtered or unexported fields
}

Hooks struct

func (*Hooks) AddOn added in v2.3.0

func (h *Hooks) AddOn(name string, handler HookFunc)

AddOn register on not exists hook.

func (*Hooks) ClearHooks added in v2.3.0

func (h *Hooks) ClearHooks()

ClearHooks clear hooks data

func (*Hooks) Fire added in v2.3.0

func (h *Hooks) Fire(event string, data ...interface{})

Fire event by name, allow with event data

func (*Hooks) On added in v2.3.0

func (h *Hooks) On(name string, handler HookFunc)

On register event hook by name

type Ints

type Ints []int

Ints The int flag list, implemented flag.Value interface

func (*Ints) Set

func (s *Ints) Set(value string) error

Set new value

func (*Ints) String

func (s *Ints) String() string

String to string

type Logo struct {
	Text  string // ASCII logo string
	Style string // eg "info"
}

Logo app logo, ASCII logo

type Runner

type Runner interface {
	// Config(c *Command)
	Run(c *Command, args []string) error
}

Runner interface

type RunningAble added in v2.3.0

type RunningAble struct {
}

Executor definition

type Strings

type Strings []string

Strings The string flag list, implemented flag.Value interface

func (*Strings) Set

func (s *Strings) Set(value string) error

Set new value

func (*Strings) String

func (s *Strings) String() string

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