cli

package
v3.0.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2018 License: Apache-2.0 Imports: 11 Imported by: 0

README

Aliyun CLI Toolkit

Because aliyun cli need process unknown flags,and the following popular library did not support this feature

Code Structure

Command

.Run

.Help

Flag
FlagSet
Ctx
i18n
TODO

Documentation

Overview

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

* Copyright (C) 2017-2018 Alibaba Group Holding Limited

Index

Examples

Constants

View Source
const (
	ColorOff = "\033[0m" // Reset Color
	// Regular Colors
	Black  = "\033[0;30m" // Black
	Red    = "\033[0;31m" // Red
	Green  = "\033[0;32m" // Green
	Yellow = "\033[0;33m" // Yellow
	Blue   = "\033[0;34m" // Blue
	Purple = "\033[0;35m" // Purple
	Cyan   = "\033[0;36m" // Cyan
	White  = "\033[0;37m" // White

	// Bold
	BBlack  = "\033[1;30m" // Black
	BRed    = "\033[1;31m" // Red
	BGreen  = "\033[1;32m" // Green
	BYellow = "\033[1;33m" // Yellow
	BBlue   = "\033[1;34m" // Blue
	BPurple = "\033[1;35m" // Purple
	BCyan   = "\033[1;36m" // Cyan
	BWhite  = "\033[1;37m" // White

	// Underline
	UBlack  = "\033[4;30m" // Black
	URed    = "\033[4;31m" // Red
	UGreen  = "\033[4;32m" // Green
	UYellow = "\033[4;33m" // Yellow
	UBlue   = "\033[4;34m" // Blue
	UPurple = "\033[4;35m" // Purple
	UCyan   = "\033[4;36m" // Cyan
	UWhite  = "\033[4;37m" // White

	// Background
	OnBlack  = "\033[40m" // Black
	OnRed    = "\033[41m" // Red
	OnGreen  = "\033[42m" // Green
	OnYellow = "\033[43m" // Yellow
	OnBlue   = "\033[44m" // Blue
	OnPurple = "\033[45m" // Purple
	OnCyan   = "\033[46m" // Cyan
	OnWhite  = "\033[47m" // White

	// High Intensty
	IBlack  = "\033[0;90m" // Black
	IRed    = "\033[0;91m" // Red
	IGreen  = "\033[0;92m" // Green
	IYellow = "\033[0;93m" // Yellow
	IBlue   = "\033[0;94m" // Blue
	IPurple = "\033[0;95m" // Purple
	ICyan   = "\033[0;96m" // Cyan
	IWhite  = "\033[0;97m" // White

	// Bold High Intensty
	BIBlack  = "\033[1;90m" // Black
	BIRed    = "\033[1;91m" // Red
	BIGreen  = "\033[1;92m" // Green
	BIYellow = "\033[1;93m" // Yellow
	BIBlue   = "\033[1;94m" // Blue
	BIPurple = "\033[1;95m" // Purple
	BICyan   = "\033[1;96m" // Cyan
	BIWhite  = "\033[1;97m" // White

	// High Intensty backgrounds
	OnIBlack  = "\033[0;100m" // Black
	OnIRed    = "\033[0;101m" // Red
	OnIGreen  = "\033[0;102m" // Green
	OnIYellow = "\033[0;103m" // Yellow
	OnIBlue   = "\033[0;104m" // Blue
	OnIPurple = "\033[10;95m" // Purple
	OnICyan   = "\033[0;106m" // Cyan
	OnIWhite  = "\033[0;107m" // White
)
View Source
const (
	DebugColor   = White
	InfoColor    = Cyan
	NoticeColor  = BYellow
	WarningColor = BPurple
	ErrorColor   = BRed
)
View Source
const (
	AssignedNone       = AssignedMode(-1)
	AssignedDefault    = AssignedMode(0)
	AssignedOnce       = AssignedMode(1)
	AssignedRepeatable = AssignedMode(9)
)
View Source
const (
	Ins = iota
	Del
	Sub
	Match
)
View Source
const DefaultSuggestDistance = 2

Variables

View Source
var HelpFlag = &Flag{
	Name:         "help",
	Short:        i18n.T("print help", "打印帮助信息"),
	AssignedMode: AssignedNone,
}

default help flag

View Source
var (
	Version = "0.0.1"
)

This variable is replaced in compile time `-ldflags "-X 'github.com/aliyun/aliyun-cli/cli.Version=${VERSION}'"`

Functions

func CalculateStringDistance

func CalculateStringDistance(source string, target string) int

func Debug

func Debug(s string)

func Debugf

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

func DistanceForMatrix

func DistanceForMatrix(matrix [][]int) int

DistanceForMatrix reads the edit distance off the given Levenshtein matrix.

func DistanceForStrings

func DistanceForStrings(source []rune, target []rune, op Options) int

DistanceForStrings returns the edit distance between source and target.

It has a runtime proportional to len(source) * len(target) and memory use proportional to len(target).

Example
source := "a"
target := "aa"
distance := DistanceForStrings([]rune(source), []rune(target), DefaultOptions)
fmt.Printf(`Distance between "%s" and "%s" computed as %d`, source, target, distance)
Output:

Distance between "a" and "aa" computed as 1

func Error

func Error(s string)

func Errorf

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

func GetVersion

func GetVersion() string

func Info

func Info(s string)

func Infof

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

func LogMatrix

func LogMatrix(source []rune, target []rune, matrix [][]int)

LogMatrix writes a visual representation of the given matrix for the given strings to os.Stderr. This function is deprecated, use WriteMatrix(source, target, matrix, os.Stderr) instead.

func MatrixForStrings

func MatrixForStrings(source []rune, target []rune, op Options) [][]int

MatrixForStrings generates a 2-D array representing the dynamic programming table used by the Levenshtein algorithm, as described e.g. here: http://www.let.rug.nl/kleiweg/lev/ The reason for putting the creation of the table into a separate function is that it cannot only be used for reading of the edit distance between two strings, but also e.g. to backtrace an edit script that provides an alignment between the characters of both strings.

func NewErrorWithTip

func NewErrorWithTip(err error, tipFormat string, args ...interface{}) error

func NewInvalidCommandError

func NewInvalidCommandError(name string, ctx *Context) error

func NewInvalidFlagError

func NewInvalidFlagError(name string, ctx *Context) error

func Notice

func Notice(s string)

func Noticef

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

func PrintSuggestions

func PrintSuggestions(lang string, ss []string)

func RatioForMatrix

func RatioForMatrix(matrix [][]int) float64

RatioForMatrix returns the Levenshtein ratio for the given matrix. The ratio is computed as follows:

(sourceLength + targetLength - distance) / (sourceLength + targetLength)

func RatioForStrings

func RatioForStrings(source []rune, target []rune, op Options) float64

RatioForStrings returns the Levenshtein ratio for the given strings. The ratio is computed as follows:

(sourceLength + targetLength - distance) / (sourceLength + targetLength)

func SplitString

func SplitString(s string, sep string) []string

func SplitStringWithPrefix

func SplitStringWithPrefix(s string, splitters string) (string, string, bool)

func UnquoteString

func UnquoteString(s string) string

func Warning

func Warning(s string)

func Warningf

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

func WriteMatrix

func WriteMatrix(source []rune, target []rune, matrix [][]int, writer io.Writer)

WriteMatrix writes a visual representation of the given matrix for the given strings to the given writer.

Example
source := []rune("neighbor")
target := []rune("Neighbour")
matrix := MatrixForStrings(source, target, DefaultOptions)
WriteMatrix(source, target, matrix, os.Stdout)
Output:

      N  e  i  g  h  b  o  u  r
   0  1  2  3  4  5  6  7  8  9
n  1  2  3  4  5  6  7  8  9 10
e  2  3  2  3  4  5  6  7  8  9
i  3  4  3  2  3  4  5  6  7  8
g  4  5  4  3  2  3  4  5  6  7
h  5  6  5  4  3  2  3  4  5  6
b  6  7  6  5  4  3  2  3  4  5
o  7  8  7  6  5  4  3  2  3  4
r  8  9  8  7  6  5  4  3  4  3

Types

type AssignedMode

type AssignedMode int

type Command

type Command struct {
	// Command Name
	Name string

	// Short is the short description shown in the 'help' output.
	Short *i18n.Text

	// Long is the long message shown in the 'help <this-command>' output.
	Long *i18n.Text

	// Syntax for usage
	Usage string

	// Sample command
	Sample string

	// Enable unknown flags
	EnableUnknownFlag bool

	// enable suggest distance,
	// disable -1
	// 0: default distance
	SuggestDistance int

	// Hidden command
	Hidden bool

	// Run, command error will be catch
	Run func(ctx *Context, args []string) error

	// Help
	Help func(ctx *Context, args []string) error

	// auto compete
	AutoComplete func(ctx *Context, args []string) []string
	// contains filtered or unexported fields
}

func NewAutoCompleteCommand

func NewAutoCompleteCommand() *Command

func NewVersionCommand

func NewVersionCommand() *Command

func (*Command) AddSubCommand

func (c *Command) AddSubCommand(cmd *Command)

func (*Command) Execute

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

func (*Command) ExecuteComplete

func (c *Command) ExecuteComplete(ctx *Context, args []string)

func (*Command) Flags

func (c *Command) Flags() *FlagSet

func (*Command) GetSubCommand

func (c *Command) GetSubCommand(s string) *Command

func (*Command) GetSuggestDistance

func (c *Command) GetSuggestDistance() int

func (*Command) GetSuggestions

func (c *Command) GetSuggestions(s string) []string

func (*Command) GetUsageWithParent

func (c *Command) GetUsageWithParent() string

func (*Command) PrintFailed

func (c *Command) PrintFailed(err error, suggestion string)

func (*Command) PrintFlags

func (c *Command) PrintFlags(ctx *Context)

func (*Command) PrintHead

func (c *Command) PrintHead()

func (*Command) PrintSample

func (c *Command) PrintSample()

func (*Command) PrintSubCommands

func (c *Command) PrintSubCommands()

func (*Command) PrintTail

func (c *Command) PrintTail()

func (*Command) PrintUsage

func (c *Command) PrintUsage()

type Completion

type Completion struct {
	Current string
	Args    []string
	// contains filtered or unexported fields
}

func ParseCompletion

func ParseCompletion() *Completion

func (*Completion) GetArgs

func (c *Completion) GetArgs() []string

func (*Completion) GetCurrent

func (c *Completion) GetCurrent() string

type Context

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

CLI Command Context

func NewCommandContext

func NewCommandContext() *Context

func (*Context) CheckFlags

func (ctx *Context) CheckFlags() error

func (*Context) Command

func (ctx *Context) Command() *Command

func (*Context) Completion

func (ctx *Context) Completion() *Completion

func (*Context) EnterCommand

func (ctx *Context) EnterCommand(cmd *Command)

Before go into the sub command, we need traverse flags and merge with parent

func (*Context) Flags

func (ctx *Context) Flags() *FlagSet

func (*Context) IsHelp

func (ctx *Context) IsHelp() bool

func (*Context) UnknownFlags

func (ctx *Context) UnknownFlags() *FlagSet

type EditOperation

type EditOperation int

func (EditOperation) String

func (operation EditOperation) String() string

type EditScript

type EditScript []EditOperation

func EditScriptForMatrix

func EditScriptForMatrix(matrix [][]int, op Options) EditScript

EditScriptForMatrix returns an optimal edit script based on the given Levenshtein matrix.

func EditScriptForStrings

func EditScriptForStrings(source []rune, target []rune, op Options) EditScript

EditScriptForStrings returns an optimal edit script to turn source into target.

type ErrorWithTip

type ErrorWithTip interface {
	GetTip(lang string) string
}

If command.Execute return Noticeable error, print i18n Notice under error information

type Field

type Field struct {
	//
	// appear in `--flag key1=value1, key2=value2`
	// if Key assigned with "", it can used with `--flag value1 value2`
	Key string

	//
	// if Required is true, this field must be assigned
	Required bool

	//
	// if Repeatable is true, this field can appear multiply times, eg: "--flag key1=value1 key2=value2"
	Repeatable bool

	//
	// if field not appear, use this value, not used with Required
	DefaultValue string

	//
	// Message show
	Short *i18n.Text
	// contains filtered or unexported fields
}

type Flag

type Flag struct {
	// Name of flag --{Name}
	Name string

	// Flag is the single characters
	Shorthand rune

	// Message print with --help command
	Short *i18n.Text

	// Message print with `help --flag` command
	Long *i18n.Text

	// If DefaultValue is not "" and Required is true, if flag is not assign
	//   GetValue() will return DefaultValue, and IsAssigned() will be false
	DefaultValue string

	// If Required is true, the flag must be assigned with `--flag value` or DefaultValue is not empty
	Required bool

	// Enable flag has alias names
	Aliases []string

	// Ref to AssignedMode
	// `AssignedNone`: 		flag only appear with `--flag1` `--flag2`
	// `AssignedDefault`: 	flag can appear with `--flag1` or `--flag1 value1`
	// `AssignedOnce`: 		flag only appear with `--flag1 value1`
	// `AssignedRepeatable`: flag can appear multi times sample: `--flag1 [v1] [v2] [v3] [field1=value1]`, use with Fields
	AssignedMode AssignedMode

	// If Persistent is true, the flag can apply to child commands
	Persistent bool

	// If Hidden is true, it will not appear in --help mode
	Hidden bool

	// Using in FlagSet.GetByCategory()...
	Category string

	// Use to validate flag is in correct format
	Validate func(f *Flag) error

	// Flag can assigned with --flag field1=value1 field2=value2 value3 ...
	// must used with AssignedMode=AssignedRepeatable
	Fields []Field

	// Flag can't appear with other flags, use Flag.Name
	ExcludeWith []string
	// contains filtered or unexported fields
}

func (*Flag) GetFieldValue

func (f *Flag) GetFieldValue(key string) (string, bool)

--flag field1=value1

func (*Flag) GetFieldValues

func (f *Flag) GetFieldValues(key string) []string

func (*Flag) GetFormations

func (f *Flag) GetFormations() []string

get all appears forms, maybe {"--Name", "--Alias1", "-Shorthand"}

func (*Flag) GetIntegerOrDefault

func (f *Flag) GetIntegerOrDefault(def int) int

TODO: flag support integer validate return def if Flag is not assign or assign failed

func (*Flag) GetStringOrDefault

func (f *Flag) GetStringOrDefault(def string) string

return def if Flag is not assigned

func (*Flag) GetValue

func (f *Flag) GetValue() (string, bool)

return flag value, if not assigned return f.DefaultValue

for `AssignedMode == AssignedRepeatable`. Use GetValues() to get all values

func (*Flag) GetValues

func (f *Flag) GetValues() []string

for `AssignedMode == AssignedRepeatable` flag, return values

func (*Flag) IsAssigned

func (f *Flag) IsAssigned() bool

return true if flag appeared, either `--flag1` or `--flag1 value1`

type FlagSet

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

func NewFlagSet

func NewFlagSet() *FlagSet

func (*FlagSet) Add

func (fs *FlagSet) Add(f *Flag)

call from user program, if flag duplicated, panic!

func (*FlagSet) AddByName

func (fs *FlagSet) AddByName(name string) (*Flag, error)

add by name, not support add by shorthand

func (*FlagSet) Flags

func (fs *FlagSet) Flags() []*Flag

traverse all values

func (*FlagSet) Get

func (fs *FlagSet) Get(name string) *Flag

get flag by name, sample --name

func (*FlagSet) GetByShorthand

func (fs *FlagSet) GetByShorthand(c rune) *Flag

get flag by shorthand, sample -a

func (*FlagSet) GetSuggestions

func (fs *FlagSet) GetSuggestions(name string, distance int) []string

get suggestions

func (*FlagSet) GetValue

func (fs *FlagSet) GetValue(name string) (string, bool)

get value by flag name, not recommended

type InvalidCommandError

type InvalidCommandError struct {
	Name string
	// contains filtered or unexported fields
}

OUTPUT: Error: "'%s' is not a valid command

{Hint}

func (*InvalidCommandError) Error

func (e *InvalidCommandError) Error() string

func (*InvalidCommandError) GetSuggestions

func (e *InvalidCommandError) GetSuggestions() []string

type InvalidFlagError

type InvalidFlagError struct {
	Flag string
	// contains filtered or unexported fields
}

func (*InvalidFlagError) Error

func (e *InvalidFlagError) Error() string

func (*InvalidFlagError) GetSuggestions

func (e *InvalidFlagError) GetSuggestions() []string

type MatchFunction

type MatchFunction func(rune, rune) bool

type Options

type Options struct {
	InsCost int
	DelCost int
	SubCost int
	Matches MatchFunction
}
var DefaultOptions Options = Options{
	InsCost: 1,
	DelCost: 1,
	SubCost: 2,
	Matches: func(sourceCharacter rune, targetCharacter rune) bool {
		return sourceCharacter == targetCharacter
	},
}

DefaultOptions is the default options: insertion cost is 1, deletion cost is 1, substitution cost is 2, and two runes match iff they are the same.

type Parser

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

func NewParser

func NewParser(args []string, detector flagDetector) *Parser

func (*Parser) GetRemains

func (p *Parser) GetRemains() []string

func (*Parser) ReadAll

func (p *Parser) ReadAll() ([]string, error)

func (*Parser) ReadNextArg

func (p *Parser) ReadNextArg() (arg string, more bool, err error)

type Suggester

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

helper class for Suggester

func NewSuggester

func NewSuggester(v string, distance int) *Suggester

func (*Suggester) Apply

func (a *Suggester) Apply(s string)

func (*Suggester) GetResults

func (a *Suggester) GetResults() []string

type SuggestibleError

type SuggestibleError interface {
	GetSuggestions() []string
}

error with suggestions

Jump to

Keyboard shortcuts

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