gcli

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2019 License: MIT Imports: 16 Imported by: 14

README

GCli

GitHub tag (latest SemVer) Build Status Codacy Badge GoDoc Go Report Card Coverage Status

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

中文说明

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

Quick start

import "gopkg.in/gookit/gcli.v2" // is recommended
// or
import "github.com/gookit/gcli"
// for go mod
import "github.com/gookit/gcli/v2"
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() {
    runtime.GOMAXPROCS(runtime.NumCPU())

    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 A Command
% ./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.GenAutoCompleteScript())

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

  • 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"
import "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 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 (
	EvtInit   = "init"
	EvtBefore = "before"
	EvtAfter  = "after"
	EvtError  = "error"
)

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 HelpVarFormat = "{$%s}"

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

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

Variables

View Source
var (

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

		osName:  runtime.GOOS,
		binName: os.Args[0],
		argLine: strings.Join(os.Args[1:], " "),
	}
)

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 {
	// internal use
	*CmdLine
	HelpVars
	SimpleHooks // allow hooks: "init", "before", "after", "error"

	// 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
	// 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, names []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) 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) 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

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
	// ShowName is a name for display help. default is equals to Name.
	ShowName string
	// Description argument description message
	Description string
	// Required arg is required
	Required bool
	// IsArray if is array, can allow accept multi values, and must in last.
	IsArray bool
	// value store parsed argument data. (type: string, []string)
	Value interface{}
	// Handler custom argument value parse handler
	Handler func(value interface{}) interface{}
	// contains filtered or unexported fields
}

Argument a command argument definition

func NewArgument added in v2.1.0

func NewArgument(name, description 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) 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) 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.

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 CmdLine

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

CmdLine store common data for CLI

func (*CmdLine) ArgLine

func (c *CmdLine) ArgLine() string

ArgLine os.Args to string, but no binName.

func (*CmdLine) BinName

func (c *CmdLine) BinName() string

BinName get bin script name

func (*CmdLine) OsArgs

func (c *CmdLine) OsArgs() []string

OsArgs is equals to `os.Args`

func (*CmdLine) OsName

func (c *CmdLine) OsName() string

OsName is equals to `runtime.GOOS`

func (*CmdLine) PID

func (c *CmdLine) PID() int

PID get PID

func (*CmdLine) WorkDir

func (c *CmdLine) WorkDir() string

WorkDir get work dir

type Command

type Command struct {
	// CmdLine is internal use
	*CmdLine
	HelpVars
	// SimpleHooks can allow setting some hooks func on running.
	SimpleHooks // allowed hooks: "init", "before", "after", "error"

	// 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
	// Func is the command handler func. Func Runner
	Func CmdFunc
	// Config func, will call on `initialize`. you can config options and other works
	Config func(c *Command)
	// Flags(command options) is a set of flags specific to this command.
	Flags flag.FlagSet
	// CustomFlags indicates that the command will do its own flag parsing.
	CustomFlags bool
	// Examples some usage example display
	Examples string
	// Help is the long help message text
	Help string
	// contains filtered or unexported fields
}

Command a CLI command structure

func NewCommand

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

NewCommand create a new command instance. Usage:

cmd := NewCommand("my-cmd", "description", func(c *Command) { ... })
app.Add(cmd) // OR cmd.AttachTo(app)

func (*Command) AddArg

func (c *Command) AddArg(name, description 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 (*Command) AddArgument added in v2.1.0

func (c *Command) 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 (*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) Arg

func (c *Command) Arg(name string) *Argument

Arg get arg by defined name. Usage:

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

func (*Command) ArgByIndex

func (c *Command) ArgByIndex(i int) *Argument

ArgByIndex get named arg by index

func (*Command) Args

func (c *Command) Args() []*Argument

Args get all defined argument

func (*Command) AttachTo

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

AttachTo attach the command to CLI application

func (*Command) BoolOpt

func (c *Command) BoolOpt(p *bool, name string, short string, defValue bool, description string) *Command

BoolOpt binding a bool option

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

func (c *Command) ID() string

ID get command ID name.

func (*Command) IntOpt

func (c *Command) IntOpt(p *int, name string, short string, defValue int, description string) *Command

IntOpt binding a int option

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

func (c *Command) OptDes(name string) string

OptDes get option description by option name

func (*Command) OptFlag

func (c *Command) OptFlag(name string) *flag.Flag

OptFlag get option Flag by option name

func (*Command) OptNames

func (c *Command) OptNames() map[string]string

OptNames return all option names

func (*Command) ParseDefaults

func (c *Command) ParseDefaults() string

ParseDefaults prints, to standard error unless configured otherwise, the default values of all defined command-line flags in the set. See the documentation for the global function PrintDefaults for more information.

NOTICE: the func is copied from package 'flag', func 'PrintDefaults'

func (*Command) RawArg

func (c *Command) RawArg(i int) string

RawArg get an argument value by index

func (*Command) RawArgs

func (c *Command) RawArgs() []string

RawArgs get all raw arguments

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

func (c *Command) ShortName(name string) string

ShortName get a shortcut name by option name

func (*Command) ShowHelp

func (c *Command) ShowHelp(quit ...bool)

ShowHelp show command help info

func (*Command) StrOpt

func (c *Command) StrOpt(p *string, name string, short string, defValue string, description string) *Command

StrOpt binding a string option

func (*Command) UintOpt

func (c *Command) UintOpt(p *uint, name string, short string, defValue uint, description string) *Command

UintOpt binding a uint option

func (*Command) VarOpt

func (c *Command) VarOpt(p flag.Value, name string, short string, description string) *Command

VarOpt binding a custom var option Usage:

cmd.VarOpt(&opts.Strings, "tables", "t", "description ...")

type GlobalOpts

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

GlobalOpts global flags

type HelpVars

type HelpVars struct {
	// 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 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 {
	Run(cmd *Command, args []string) error
}

Runner interface

type SimpleHooks

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

SimpleHooks struct

func (*SimpleHooks) AddOn added in v2.1.0

func (sh *SimpleHooks) AddOn(name string, handler HookFunc)

AddOn register on not exists hook.

func (*SimpleHooks) ClearHooks

func (sh *SimpleHooks) ClearHooks()

ClearHooks clear hooks data

func (*SimpleHooks) Fire

func (sh *SimpleHooks) Fire(event string, data ...interface{})

Fire event by name, allow with event data

func (*SimpleHooks) On

func (sh *SimpleHooks) On(name string, handler HookFunc)

On register event hook by name

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
Package interact collect some interactive methods for CLI
Package interact collect some interactive methods for CLI
Package sflag is an simple cli flag parse tool
Package sflag is an simple cli flag parse tool
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