gcli: github.com/gookit/gcli Index | Files | Directories

package gcli

import "github.com/gookit/gcli"

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

Package Files

app.go app_run.go cmd.go cmd_opt_arg.go cmd_run.go gcli.go helper.go

Constants

const (
    VerbQuiet uint = iota // don't report anything
    VerbError             // reporting on error
    VerbWarn
    VerbInfo
    VerbDebug
    VerbCrazy
)

constants for error level 0 - 4

const (
    EvtInit   = "init"
    EvtBefore = "before"
    EvtAfter  = "after"
    EvtError  = "error"
)

constants for hooks event, there are default allowed event names

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

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

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

Variables

var (

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

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

func Exit Uses

func Exit(code int)

Exit program

func Logf Uses

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

Logf print log message

func Print Uses

func Print(args ...interface{})

Print messages

func Printf Uses

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

Printf messages

func Println Uses

func Println(args ...interface{})

Println messages

func SetDebugMode Uses

func SetDebugMode()

SetDebugMode level

func SetQuietMode Uses

func SetQuietMode()

SetQuietMode level

func SetStrictMode Uses

func SetStrictMode(strict bool)

SetStrictMode for parse flags

func SetVerbose Uses

func SetVerbose(verbose uint)

SetVerbose level

func StrictMode Uses

func StrictMode() bool

StrictMode get is strict mode

func Verbose Uses

func Verbose() uint

Verbose returns verbose level

type App Uses

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 ASCII logo setting
     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 Uses

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

InitStdApp create the default cli app.

func NewApp Uses

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 Uses

func StdApp() *App

StdApp get the default std app

func (*App) Add Uses

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

Add add one or multi command(s)

func (*App) AddAliases Uses

func (app *App) AddAliases(command string, names []string)

AddAliases add alias names for a command

func (*App) AddCommand Uses

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

AddCommand add a new command

func (*App) AddError Uses

func (app *App) AddError(err error)

AddError to the application

func (*App) CleanArgs Uses

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

CleanArgs get clean args

func (*App) CommandName Uses

func (app *App) CommandName() string

CommandName get current command name

func (*App) CommandNames Uses

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

CommandNames get all command names

func (*App) Commands Uses

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

Commands get all commands

func (*App) Config Uses

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

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

func (*App) DefaultCommand Uses

func (app *App) DefaultCommand(name string)

DefaultCommand set default command name

func (*App) Exec Uses

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

Exec running other command in current command

func (*App) IsCommand Uses

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

IsCommand name check

func (*App) Names Uses

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

Names get all command names

func (*App) NewCommand Uses

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

NewCommand create a new command

func (*App) On Uses

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

On add hook handler for a hook event

func (*App) RealCommandName Uses

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

RealCommandName get real command name by alias

func (*App) Run Uses

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

Run running application

func (*App) SetDebugMode Uses

func (app *App) SetDebugMode()

SetDebugMode level

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

SetLogo text and color style

func (*App) SetQuietMode Uses

func (app *App) SetQuietMode()

SetQuietMode level

func (*App) SetVerbose Uses

func (app *App) SetVerbose(verbose uint)

SetVerbose level

type Argument Uses

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(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 Uses

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

NewArgument quick create an new command argument

func (*Argument) Array Uses

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

Array alias of the Strings()

func (*Argument) Config Uses

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

Config the argument

func (*Argument) GetValue Uses

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

GetValue get value by custom handler func

func (*Argument) HasValue Uses

func (a *Argument) HasValue() bool

HasValue value is empty

func (*Argument) Index Uses

func (a *Argument) Index() int

Index get argument index in the command

func (*Argument) Int Uses

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

Int argument value to int

func (*Argument) IsEmpty Uses

func (a *Argument) IsEmpty() bool

IsEmpty argument is empty

func (*Argument) String Uses

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

String argument value to string

func (*Argument) StringSplit Uses

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

StringSplit quick split a string argument to string slice

func (*Argument) Strings Uses

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

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

func (*Argument) WithValidator Uses

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

WithValidator set an value validator of the argument

func (*Argument) WithValue Uses

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

WithValue set an value of the argument

type Booleans Uses

type Booleans []bool

Booleans The bool flag list, implemented flag.Value interface

func (*Booleans) Set Uses

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

Set new value

func (*Booleans) String Uses

func (s *Booleans) String() string

String to string

type CmdFunc Uses

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

CmdFunc definition

func (CmdFunc) Run Uses

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

Run implement the Runner interface

type CmdLine Uses

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

CmdLine store common data for CLI

func (*CmdLine) ArgLine Uses

func (c *CmdLine) ArgLine() string

ArgLine os.Args to string, but no binName.

func (*CmdLine) BinName Uses

func (c *CmdLine) BinName() string

BinName get bin script name

func (*CmdLine) OsArgs Uses

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

OsArgs is equals to `os.Args`

func (*CmdLine) OsName Uses

func (c *CmdLine) OsName() string

OsName is equals to `runtime.GOOS`

func (*CmdLine) PID Uses

func (c *CmdLine) PID() int

PID get PID

func (*CmdLine) WorkDir Uses

func (c *CmdLine) WorkDir() string

WorkDir get work dir

type Command Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

AliasesString returns aliases string

func (*Command) App Uses

func (c *Command) App() *App

App returns the CLI application

func (*Command) Arg Uses

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 Uses

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

ArgByIndex get named arg by index

func (*Command) Args Uses

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

Args get all defined argument

func (*Command) AttachTo Uses

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

AttachTo attach the command to CLI application

func (*Command) BoolOpt Uses

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

BoolOpt binding a bool option

func (*Command) Copy Uses

func (c *Command) Copy() *Command

Copy a new command for current

func (*Command) Disable Uses

func (c *Command) Disable()

Disable set cmd is disabled

func (*Command) Errorf Uses

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

Errorf format message and add error to the command

func (*Command) Fire Uses

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

Fire event handler by name

func (*Command) ID Uses

func (c *Command) ID() string

ID get command ID name.

func (*Command) IntOpt Uses

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

IntOpt binding a int option

func (*Command) IsAlone Uses

func (c *Command) IsAlone() bool

IsAlone running

func (*Command) IsDisabled Uses

func (c *Command) IsDisabled() bool

IsDisabled get cmd is disabled

func (*Command) Logf Uses

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

Logf print log message

func (*Command) Module Uses

func (c *Command) Module() string

Module name of the grouped command

func (*Command) MustRun Uses

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

MustRun Alone the current command, will panic on error

func (*Command) NotAlone Uses

func (c *Command) NotAlone() bool

NotAlone running

func (*Command) On Uses

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

On add hook handler for a hook event

func (*Command) OptDes Uses

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

OptDes get option description by option name

func (*Command) OptFlag Uses

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

OptFlag get option Flag by option name

func (*Command) OptNames Uses

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

OptNames return all option names

func (*Command) ParseDefaults Uses

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 Uses

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

RawArg get an argument value by index

func (*Command) RawArgs Uses

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

RawArgs get all raw arguments

func (*Command) Run Uses

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

Run Alone the current command

func (*Command) Runnable Uses

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 Uses

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

SetFunc Settings command handler func

func (*Command) ShortName Uses

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

ShortName get a shortcut name by option name

func (*Command) ShowHelp Uses

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

ShowHelp show command help info

func (*Command) StrOpt Uses

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

StrOpt binding a string option

func (*Command) UintOpt Uses

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

UintOpt binding a uint option

func (*Command) VarOpt Uses

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 Uses

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

GlobalOpts global flags

type HelpVars Uses

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 Uses

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

AddVar get command name

func (*HelpVars) AddVars Uses

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

AddVars add multi tpl vars

func (*HelpVars) GetVar Uses

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

GetVar get a help var by name

func (*HelpVars) GetVars Uses

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

GetVars get all tpl vars

func (*HelpVars) ReplaceVars Uses

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

ReplaceVars replace vars in the input string.

type HookFunc Uses

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 Uses

type Ints []int

Ints The int flag list, implemented flag.Value interface

func (*Ints) Set Uses

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

Set new value

func (*Ints) String Uses

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 Uses

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

Runner interface

type SimpleHooks Uses

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

SimpleHooks struct

func (*SimpleHooks) AddOn Uses

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

AddOn register on not exists hook.

func (*SimpleHooks) ClearHooks Uses

func (sh *SimpleHooks) ClearHooks()

ClearHooks clear hooks data

func (*SimpleHooks) Fire Uses

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

Fire event by name, allow with event data

func (*SimpleHooks) On Uses

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

On register event hook by name

type Strings Uses

type Strings []string

Strings The string flag list, implemented flag.Value interface

func (*Strings) Set Uses

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

Set new value

func (*Strings) String Uses

func (s *Strings) String() string

String to string

Directories

PathSynopsis
builtin
builtin/filewatcher
builtin/launcheditor
builtin/reverseproxy
builtin/tcpproxy
_examples
_examples/alone
_examples/cmd
_examples/srvmanager
helper
interactPackage interact collect some interactive methods for CLI
progress
sflagPackage sflag is an simple cli flag parse tool
showPackage show provides some formatter tools for display data.
show/emoji
show/symbols
show/table

Package gcli imports 16 packages (graph) and is imported by 18 packages. Updated 2019-10-01. Refresh now. Tools for package owners.