gcli

package module
Version: v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2019 License: MIT Imports: 12 Imported by: 0

README

cliapp

GoDoc Go Report Card

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

中文说明

Screenshots

app-help

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.v1" // is recommended
// or
import "github.com/gookit/gcli"
package main

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

// for test run: go build ./demo/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) int {
            gcli.Stdout("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
this is my cli application

Version: 1.0.3                                                           
Display app help

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

Examples:

./cliapp
./cliapp -h # can also
./cliapp --help # can also
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_cmd

Display command help

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

cmd-help

Display command tips

command tips

Generate auto completion scripts
import  "github.com/gookit/gcli/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
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) int {
        gcli.Stdout("hello, in the demo command\n")
        return 0
    },
})
Write go file

the source file at: example.go

package cmd

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

// 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) int {
	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 0
}
  • display the command help:
go build ./_examples/cliapp.go && ./cliapp example -h

cmd-help

Progress display

  • progress.Bar progress bar
25/50 [==============>-------------]  50%
  • progress.Txt text progress bar
Data handling ... ... 50% (25/50)
  • progress.LoadBar pending/loading progress bar
  • progress.Counter counter
  • progress.RoundTrip round trip progress bar
[===     ] -> [    === ] -> [ ===    ]
  • progress.DynamicText dynamic text message

Examples:

package main

import "time"
import "github.com/gookit/gcli/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

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

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

not support on windows cmd.exe

// 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")
  • color.Tag
// set a style tag
color.Tag("info").Print("info style text")
color.Tag("info").Printf("%s style text", "info")
color.Tag("info").Println("info style text")

For more information on the use of color libraries, please visit gookit/color

Ref

License

MIT

Documentation

Overview

Package gcli is a simple to use command line application, written using golang

Source code and other details for the project are available at GitHub:

https://github.com/gookit/gcli

usage please ref 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
)
View Source
const HelpVar = "{$%s}"

HelpVar allow var replace in 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 AllCommands

func AllCommands() map[string]*Command

AllCommands returns all commands

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 Verbose

func Verbose() uint

Verbose returns verbose level

Types

type App

type App struct {
	// internal use
	*CmdLine
	// Name app name
	Name string
	// Version app version. like "1.0.1"
	Version string
	// Description app description
	Description string
	Logo Logo
	// Hooks can setting some hooks func on running.
	// allow hooks: "init", "before", "after", "error"
	Hooks map[string]appHookFunc
	// Strict use strict mode. short opt must be begin '-', long opt must be begin '--'
	Strict bool
	// contains filtered or unexported fields
}

App the cli app definition

func Instance added in v1.2.1

func Instance() *App

Instance returns the current application instance

func New

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

New create new app instance. eg:

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

func NewApp

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

NewApp create new app instance. alias of the New() eg:

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

func (*App) Add added in v1.2.1

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

Add add one or multi command(s)

func (*App) AddAliases added in v1.2.1

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

AddAliases add alias names for a command

func (*App) AddCommand added in v1.2.1

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

AddCommand add a new command

func (*App) AddError added in v1.2.1

func (app *App) AddError(err error)

AddError to the application

func (*App) AddVar added in v1.2.1

func (app *App) AddVar(name, value string)

AddVar get command name

func (*App) AddVars added in v1.2.1

func (app *App) AddVars(vars map[string]string)

AddVars add multi tpl vars

func (*App) CommandName added in v1.2.1

func (app *App) CommandName() string

CommandName get current command name

func (*App) CommandNames added in v1.2.1

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

CommandNames get all command names

func (*App) Commands added in v1.2.1

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

Commands get all commands

func (*App) Config added in v1.2.1

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

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

func (*App) DebugMode added in v1.2.1

func (app *App) DebugMode()

DebugMode level

func (*App) DefaultCommand added in v1.2.1

func (app *App) DefaultCommand(name string)

DefaultCommand set default command name

func (*App) Exec added in v1.2.1

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

Exec running other command in current command

func (*App) GetVar added in v1.2.1

func (app *App) GetVar(name string) string

GetVar get a help var by name

func (*App) GetVars added in v1.2.1

func (app *App) GetVars(name string, value string) map[string]string

GetVars get all tpl vars

func (*App) Initialize added in v1.2.1

func (app *App) Initialize()

Initialize application

func (*App) IsCommand added in v1.2.1

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

IsCommand name check

func (*App) NewCommand added in v1.2.1

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

NewCommand create a new command

func (*App) On added in v1.2.1

func (app *App) On(name string, handler func(a *App, data interface{}))

On add hook handler for a hook event

func (*App) QuietMode added in v1.2.1

func (app *App) QuietMode()

QuietMode level

func (*App) RealCommandName added in v1.2.1

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

RealCommandName get real command name by alias

func (*App) Run added in v1.2.1

func (app *App) Run()

Run running application

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

SetLogo text and color style

func (*App) SetVerbose added in v1.2.1

func (app *App) SetVerbose(verbose uint)

SetVerbose level

type Argument

type Argument struct {
	// Name argument name
	Name string
	// ShowName is a name for display help. default is equals to Name.
	ShowName string
	// Description argument description message
	Description string
	// IsArray if is array, can allow accept multi values, and must in last.
	IsArray bool
	// Required arg is required
	Required bool
	// value store parsed argument data. (type: string, []string)
	Value interface{}
	// contains filtered or unexported fields
}

Argument a command argument definition

func (*Argument) Array

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

Array alias of the Strings()

func (*Argument) HasValue added in v1.2.1

func (a *Argument) HasValue() bool

HasValue value is empty

func (*Argument) Int

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

Int argument value to int

func (*Argument) String

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

String argument value to string

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

CmdFunc definition

func (CmdFunc) Run

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

Run implement the Runner interface

type CmdLine

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

CmdLine store common data for CLI

func (*CmdLine) ArgLine added in v1.2.1

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) 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 {
	// is internal use
	*CmdLine
	// Name is the command name.
	Name string
	// UseFor is the command description message.
	UseFor 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)
	// Hooks can setting some hooks func on running.
	// allow hooks: "init", "before", "after", "error"
	Hooks map[string]HookFunc
	// Aliases is the command name's alias names
	Aliases []string
	// 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
	// Vars you can add some vars map for render help info
	Vars map[string]string
	// Help is the long help message text
	Help string
	// Examples some usage example display
	Examples string
	// contains filtered or unexported fields
}

Command a CLI command structure

func NewCommand added in v1.2.1

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

func (c *Command) AddVars(vars map[string]string)

AddVars add multi tpl vars

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 added in v1.2.1

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

func (c *Command) Error() error

Error get error of the command

func (*Command) Errorf

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

Errorf format message and add error to the command

func (*Command) Execute

func (c *Command) Execute(args []string) int

Execute do execute the command

func (*Command) GetVar

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

GetVar get a help var by 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) NotAlone

func (c *Command) NotAlone() bool

NotAlone running

func (*Command) On

func (c *Command) On(name string, handler func(c *Command, data interface{}))

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 Flags arg value

func (*Command) RawArgs

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

RawArgs get Flags args

func (*Command) Run added in v1.2.1

func (c *Command) Run(inArgs []string) int

Run 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 added in v1.2.1

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

func (*Command) WithError

func (c *Command) WithError(err error) int

WithError add a error for the command. Notice: By default the error will be handled by c.defaultErrHandler()

type GlobalOpts

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

GlobalOpts global flags

type HookFunc

type HookFunc func(c *Command, data interface{})

HookFunc definition

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

Runner interface

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