bin

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2023 License: Apache-2.0 Imports: 22 Imported by: 0

README

uymas/bin

命令行生成工具

格式

# 命令解析
$ [command] <option>

# 简单选项
$ <option>

#
# -- 与 - 的区别,参考Linux常用命令格式
--fix	# 选项全拼
-fix    # 选择简写,等同于 -f -i -x

#
# 命令行数据格式
--name='Joshua Conero'
--name 'Joshua Conero'

# only-option 作为无值选项
--only-option --last-name Conero
# 短标签映射关系(需要建立映射关系)
# -N,--name
# -O,--only-option
# 数组型参数
--persons Conero Jahn Lile Any --prex

# 实现属性严格检查开关(此时需要注册所有选择)

数据格式

支持的基本类型如下:

  • 数字 number
    • 整形 int64
    • 浮点型 float64
  • 布尔类型 bool
  • 字符串 string
# 字符串
# string
$ 'the data string.'	# the data string.
$ "the data string."	# the data string.

# 数字类型,默认最长的数字类型
# int64, float64
$ 8						# int64
$ 8.88					# float64

# bool 类型(不区分大小写)
$ True
$ true

# 数组
# 分割符号(separator)  默认","
$ 'a','b','c','d'		# array [a, b, c, d]
# "," 分割
$ --separator-comma 
$ -spt-c
$ --array a1 a3 a4 a5
$ --array {a1,a3,a4,a5}
特殊数据支持

待实现

#
# 解析 json 字符串、支持json字符串、文件或地址
$ --load-json,--LJ <json-string>
$ --load-json-file,--LJF <json-filename>
$ --load-json-url,--LJU <json-url-url>

#
# url 地址数据形式支持
$ --load-url,--LU <url-字符串数据>
$ --load-url-file,--LUF <url-filename>
$ --load-url-url,--LUU <url-url-url>

#
# 脚本支持
$ --script <file-name> 只是脚本解析
解析算法实现
python
def option_parse(args, strict_option_list=None):
    '''
    见: _example/design/option-parse/option-parse.py
    '''
    pass

教程

路由状态分为:命令匹配成功 、空命令状态、自定义函数路由成功状态。

命令行程序可实现 对象式函数式, 同时持:对象式/函数式混合风格

对象式
package main

import (
	"fmt"
	"gitee.com/conero/uymas/bin"
)
// 命令 test
type Test struct {
	bin.Command
}
// 项目初始化
func (a *Test) Init ()  {
    // 重写方法时必先系统父结构体方法[!!]
    a.Command.Init()
    
    // todo ....
}
// 运行,执行内二级命令分发
func (a *Test) Run ()  {
	fmt.Println("ffff.")
}

// 命令 yang
type Yang struct {
	bin.Command
}


func main() {
	//router := &bin.Router{}
	//bin.Register("test", &Test{})
	//bin.Register("yang", &Yang{})
	//bin.Adapter(router)
	bin.RegisterApps(map[string]interface{}{
		"test": &Test{},
		"yang": &Yang{},
	})
	bin.Run()
}

函数式
package main

import (
	"gitee.com/conero/uymas/bin"
)


func main() {
	// 项目注册
	bin.RegisterFunc("name", func() {
		fmt.Println(" conero/uymas/bin example with Base.")
	})

	// 未知命令
	bin.UnfindFunc(func(cmd string) {
		fmt.Println(cmd + "unfind(functional)")
	})

	// 空函数
	bin.EmptyFunc(func() {
		fmt.Println("empty(functional)")
	})

	bin.Run()
}

新式函数命令工具

FRdata
数据加载

支持多种数据加载

# 大量数据加载实现
./uymas-bin.exe --load-json '{"json":"json 字符串"}' --load-json='{"json2": "方法二"}'
./uymas-bin.exe --load-url-style 'key=value&k2=v2&k3=v3'
./uymas-bin.exe --load-session-style 'key:value; k2:v2; k3:v3;'

# 不同数据加载
# 长选项
--key 'value'
--key='value'
--command-style

# 单选项
-P 'value'
-C
json
url-style
session-style
struct 设置到命令路由

定义Struct直接映射为命令路由注册

type CMD struct {
	Title    string   //标题
	Command  string   //命令行
	Alias    []string //别名
	Describe string   //描述

	HelpMessage string           //帮助信息
	HelpCall    func(cc *CliCmd) //帮助信息回调

	//回调,可以默认为当前本身
	Todo    func(cc *CliCmd) //命令回调
	TodoApp interface{}      //命令绑定信息
}
命令
// 命令描述

Documentation

Overview

Package bin is sample command application lib, provides functional and classic style Apis.

Index

Examples

Constants

View Source
const (
	AppMethodInit     = "Init"
	AppMethodRun      = "Run"
	AppMethodNoSubC   = "SubCommandUnfind"
	AppMethodHelp     = "Help"
	FuncRegisterEmpty = "_inner_empty_func"
)
View Source
const (
	CmdApp initIota = iota
	CmdFunc
)

the Cmd of type

View Source
const (
	AppTagName            = "cmd"
	OptValidationRequire  = "required" // 必须
	OptValidationOptional = "optional" // 可选
)
View Source
const (
	PlgCmdGetTitle   = "plg-cmd-title"
	PlgCmdGetProfile = "plg-cmd--profile"
)
View Source
const (
	ReplContinue = iota
	ReplBreak
	ReplExit
)
View Source
const OptionTagName = "arg"

Variables

This section is empty.

Functions

func CleanoutString added in v1.1.0

func CleanoutString(ss string) string

CleanoutString clear out the raw input string like:

`"string"`		=> `string`
`"'string'"`	=> `'string'`
`'string'`		=> `string`
`'"string"'`	=> `"string"`

func Cmd2StringMap added in v1.1.0

func Cmd2StringMap(c string) string

Cmd2StringMap command string turn to map string, for standard go method name. like:

`get-videos` -> `GetVideos`
`get_videos` -> `GetVideos`

func FormatKv added in v0.5.2

func FormatKv(kv any, params ...string) string

FormatKv The `k-v` data format to beautiful str. FormatKv(kv map[string]interface{}, pref string) provide pref param form FormatKv. FormatKv(kv map[string]interface{}, pref string, md string) provide pref and middle param form FormatK. the `Kv` support map/struct, but not ptr(pointer)

func FormatKvSort added in v1.1.0

func FormatKvSort(kv any, params ...string) string

FormatKvSort The `k-v` data format to beautiful str. FormatKvSort(kv map[string]interface{}, pref string) provide pref param form FormatKv. FormatKvSort(kv map[string]interface{}, pref string, md string) provide pref and middle param form FormatK.

func FormatQue added in v0.5.0

func FormatQue(que any, prefs ...string) string

FormatQue format the string array, using for cli output pretty. where prefs is empty default use the array index

func FormatTable added in v0.5.0

func FormatTable(table any, args ...any) string

FormatTable Table format output by slice:

(table, bool) if is use the idx, table is 2 dimensional array.

Bug(FormatQue): chinese text cannot alignment

func GetHelpEmbed added in v1.1.0

func GetHelpEmbed(content string, args ...string) string

GetHelpEmbed GetHelpEmbed(content string, lang string)

func ParseValueByStr added in v1.1.0

func ParseValueByStr(ss string) any

ParseValueByStr parse the command value to really type by format.

func PlgCmdList added in v1.3.0

func PlgCmdList() []string

PlgCmdList Get Plugin Sub-Command list, support windows/linux/darwin.

func ReplCommand added in v1.2.0

func ReplCommand(name string, cli *CLI)

ReplCommand create a repl cli sub command

Types

type App

type App struct {
	Title       string // app title
	Description string // app description text
	CmdList     []AppCmd
	// contains filtered or unexported fields
}

func (*App) Append added in v1.1.2

func (c *App) Append(ac ...AppCmd) *App

Append add new cmd

func (*App) GetDoc added in v1.1.2

func (c *App) GetDoc() string

func (*App) Run added in v1.1.2

func (c *App) Run(args ...string)

Run run cmd application

type AppCmd added in v1.1.2

type AppCmd struct {
	Alias    []string // the alias list of cmd
	Name     string   // cmd name default by `AppCmd` struct
	Title    string   // the description of cmd
	Option   []any
	Register any // register name
}

type AppOption added in v1.1.2

type AppOption struct {
	Validation string // validation item like: required, optional(default)
	Name       string
	Alias      []string

	IsSet bool // option is set
	// contains filtered or unexported fields
}

AppOption parse struct tag syntax `cmd: "tagName;"` data valid: required, optional(default) name: "name,n,N" example help: `help,h; optional`

func ParseOptionTag added in v1.1.2

func ParseOptionTag(tag string) *AppOption

type AppOptionGroup added in v1.1.2

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

AppOptionGroup the group of many of AppOption.

func ParseOptionGroup added in v1.1.2

func ParseOptionGroup(v any) *AppOptionGroup

func (*AppOptionGroup) Option added in v1.1.2

func (c *AppOptionGroup) Option(name string) *AppOption

Option get option by name

func (*AppOptionGroup) OptionSearchAlias added in v1.1.2

func (c *AppOptionGroup) OptionSearchAlias(name string) *AppOption

func (*AppOptionGroup) ParseEach added in v1.1.2

func (c *AppOptionGroup) ParseEach(v any, each func(*AppOption)) error

func (*AppOptionGroup) Unmarshal added in v1.1.2

func (c *AppOptionGroup) Unmarshal(cmd *Arg, v any) error

type Arg added in v1.2.0

type Arg struct {
	Data       map[string]any    // the data from the `DataRaw` by parse for type
	DataRaw    map[string]string // the cli application apply the data
	Command    string            // the current command
	SubCommand string            // the sub command
	Setting    []string          // the setting of command
	Raw        []string          // the raw args
	// contains filtered or unexported fields
}

Arg the command of the cli application.

func NewCliCmd added in v1.1.0

func NewCliCmd(args ...string) *Arg

NewCliCmd the construct of `Arg`, args default set os.Args if no function arguments

func NewCliCmdByString added in v1.1.0

func NewCliCmdByString(ss string) *Arg

NewCliCmdByString construction of `Arg` by string

func (*Arg) AppendData added in v1.2.0

func (app *Arg) AppendData(vMap map[string]any) *Arg

AppendData append the Data

func (*Arg) Arg added in v1.2.0

func (app *Arg) Arg(keys ...string) any

Arg get arg after parsed the raw data

func (*Arg) ArgBool added in v1.2.0

func (app *Arg) ArgBool(keys ...string) bool

ArgBool get args data identified as bool

func (*Arg) ArgDefault added in v1.2.0

func (app *Arg) ArgDefault(key string, def any) any

ArgDefault can default value to get the arg

func (*Arg) ArgFloat64 added in v1.2.0

func (app *Arg) ArgFloat64(keys ...string) float64

ArgFloat64 get args data identified as float64

func (*Arg) ArgInt added in v1.2.0

func (app *Arg) ArgInt(keys ...string) int

ArgInt get args data identified as int

func (*Arg) ArgRaw added in v1.2.0

func (app *Arg) ArgRaw(keys ...string) string

ArgRaw get raw args data, because some args has alias list.

func (*Arg) ArgRawDefault added in v1.2.0

func (app *Arg) ArgRawDefault(key, def string) string

ArgRawDefault get raw arg has default

func (*Arg) ArgRawLine added in v1.2.0

func (app *Arg) ArgRawLine() string

ArgRawLine get the raw line input.

func (*Arg) ArgStringSlice added in v1.2.0

func (app *Arg) ArgStringSlice(keys ...string) []string

ArgStringSlice get string-slice param args

func (*Arg) CallCmd added in v1.2.0

func (app *Arg) CallCmd(cmd string)

CallCmd call cmd

func (*Arg) CheckMustKey added in v1.2.0

func (app *Arg) CheckMustKey(keys ...string) bool

CheckMustKey check the data key must in the sets and support multi

func (*Arg) CheckSetting added in v1.2.0

func (app *Arg) CheckSetting(sets ...string) bool

CheckSetting to checkout if the set exist in `Arg` sets and support multi.

func (*Arg) CmdType added in v1.2.0

func (app *Arg) CmdType() int

func (*Arg) CommandAlias added in v1.2.0

func (app *Arg) CommandAlias(key string, alias ...string) *Arg

CommandAlias Tip: in the future will merge method like CommandAlias And CommandAliasAll, chose one from twos.

func (*Arg) CommandAliasAll added in v1.2.0

func (app *Arg) CommandAliasAll(alias map[string][]string) *Arg

func (*Arg) Context added in v1.2.0

func (app *Arg) Context() CLI

Context get the context of `CLI`, in case `AppCmd` not `FunctionCmd`

func (*Arg) Cwd added in v1.2.0

func (app *Arg) Cwd() string

Cwd get the application current word dir.

func (*Arg) IsPlgCmd added in v1.3.0

func (app *Arg) IsPlgCmd() bool

func (*Arg) Next added in v1.2.0

func (app *Arg) Next(keys ...string) string

Next Get key values from multiple key values

func (*Arg) NextList added in v1.3.0

func (app *Arg) NextList(keys ...string) []string

NextList get the next list value exclude option.

func (*Arg) QueueNext added in v1.2.0

func (app *Arg) QueueNext(key string) string

QueueNext get next key from order left to right

func (*Arg) SubCommandAlias added in v1.2.0

func (app *Arg) SubCommandAlias(key string, alias ...string) *Arg

func (*Arg) SubCommandAliasAll added in v1.2.0

func (app *Arg) SubCommandAliasAll(alias map[string][]string) *Arg

type CLI added in v1.1.0

type CLI struct {

	//external fields
	UnLoadDataSyntax   bool   //not support load data syntax, like json/url.
	UnLoadScriptSyntax bool   // disable allow load script like shell syntax.
	ScriptOption       string // default: --script,-s
	ScriptFileOption   string // default: --file,-f
	// DisPlgCmdDetect Turn off Plugin Command detection
	DisPlgCmdDetect bool
	// contains filtered or unexported fields
}

CLI the cli application

func NewCLI added in v1.1.0

func NewCLI() *CLI

NewCLI the construct of `CLI`

Example (Func)
cli := NewCLI()
cli.RegisterAny(func() {
	fmt.Println("Hello world, cli.")
})
cli.Run()
Output:

Hello world, cli.
Example (Repl)
var input = bufio.NewScanner(os.Stdin)
prefShow := func() {
	fmt.Print("$ uymas> ")
}
cli := NewCLI()
cli.RegisterAny(new(defaultAppHelloWorld))
prefShow()
for input.Scan() {
	text := input.Text()
	text = strings.TrimSpace(text)
	switch text {
	case "exit":
		os.Exit(0)
	default:
		// to run struct command.
		var cmdsList = parser.NewParser(text)
		for _, cmdArgs := range cmdsList {
			cli.Run(cmdArgs...)
		}
	}
	fmt.Println()
	prefShow()
}
Output:

Example (Struct)
cli := NewCLI()
// add the new struct instance.
// type defaultAppHelloWorld struct {
//	bin.CliApp
// }
//
// func (w *defaultAppHelloWorld) DefaultIndex() {
//	fmt.Println("Hello world, struct cli.")
// }
cli.RegisterAny(new(defaultAppHelloWorld))
cli.Run()
Output:

Hello world, struct cli.

func (*CLI) CallCmd added in v1.1.0

func (cli *CLI) CallCmd(cmd string)

CallCmd call the application cmd

func (*CLI) CmdExist added in v1.1.0

func (cli *CLI) CmdExist(cmds ...string) bool

CmdExist test cmd exist in application

func (*CLI) Describe added in v1.1.0

func (cli *CLI) Describe(desc string) bool

func (*CLI) GetCmdList added in v1.1.0

func (cli *CLI) GetCmdList() []string

GetCmdList get the list cmd of application

func (*CLI) GetDescribe added in v1.1.0

func (cli *CLI) GetDescribe(cmd string) string

GetDescribe support the `cmd, alias` param.

func (*CLI) GetInjection added in v1.1.0

func (cli *CLI) GetInjection(key string) any

GetInjection get Injection data

func (*CLI) Inject added in v1.1.0

func (cli *CLI) Inject(key string, value any) *CLI

Inject inject for data from outside.

func (*CLI) RegisterAny added in v1.1.0

func (cli *CLI) RegisterAny(action any) *CLI

RegisterAny when command input not handler will callback the register, the format like:

  1. function `func(cmd string, cc *Arg)`/`func(cmd string)`/`func(cc *Arg)`/CliApp/Base Struct

func (*CLI) RegisterApp added in v1.1.0

func (cli *CLI) RegisterApp(ap any, cmds ...string) *CLI

RegisterApp register the struct app, the format same as RegisterFunc. cmds any be `cmd string` or `cmd, alias string`

func (*CLI) RegisterApps added in v1.1.0

func (cli *CLI) RegisterApps(aps map[string]any) *CLI

RegisterApps Register many apps once.

func (*CLI) RegisterCommand added in v1.1.0

func (cli *CLI) RegisterCommand(c Cmd) *CLI

RegisterCommand register by command struct data

func (*CLI) RegisterEmpty added in v1.1.0

func (cli *CLI) RegisterEmpty(action any) *CLI

RegisterEmpty when the cmd is empty then callback the function, action only be

  1. function `func(cc *Arg)`/`func()` or struct.

func (*CLI) RegisterEnd added in v1.3.0

func (cli *CLI) RegisterEnd(action any) *CLI

RegisterEnd when the cmd is empty then callback the function, action only be

  1. function `func(cc *Arg)`/`func()` or struct.

func (*CLI) RegisterFunc added in v1.1.0

func (cli *CLI) RegisterFunc(todo func(*Arg), cmds ...string) *CLI

RegisterFunc register functional command, the format like

`RegisterFunc(todo func(cc *Arg), cmd string)` or `RegisterFunc(todo func(), cmd, alias string)`

func (*CLI) RegisterUnmatched added in v1.1.1

func (cli *CLI) RegisterUnmatched(callback func(string, *Arg)) *CLI

RegisterUnmatched old method `Unfind` of alias compatibly use `RegisterAny`

func (*CLI) Run added in v1.1.0

func (cli *CLI) Run(args ...string)

Run the application

func (*CLI) RunDefault added in v1.1.1

func (cli *CLI) RunDefault(args ...string)

RunDefault Run cli app using user defined `args` when os.args is empty, it'll be useful to debug or default define.

type CMD added in v1.1.0

type CMD struct {
	Title   string //the title of `CMD`
	Command string
	Alias   []string //the alias of `CMD`, support many alias command

	//help information
	Describe    string
	HelpMessage string     //help message
	HelpCall    func(*Arg) //help message by `Func`

	//the action by the Func
	Todo    func(*Arg) //cli callback
	TodoApp any        //bind from App struct
}

CMD the struct to be a map for cli application @todo need to do

type CliApp added in v1.1.0

type CliApp struct {
	Cc *Arg
}

CliApp the cli app.

func (*CliApp) Construct added in v1.2.0

func (c *CliApp) Construct()

Construct implement method for `CliAppCompleteInterface` interface.

func (*CliApp) DefaultEnd added in v1.3.0

func (c *CliApp) DefaultEnd()

func (*CliApp) DefaultHelp added in v1.2.0

func (c *CliApp) DefaultHelp()

func (*CliApp) DefaultIndex added in v1.2.0

func (c *CliApp) DefaultIndex()

func (*CliApp) DefaultUnmatched added in v1.2.0

func (c *CliApp) DefaultUnmatched()

type CliAppCompleteInterface added in v1.1.0

type CliAppCompleteInterface interface {
	CliAppInterface
	DefaultHelp()
	DefaultIndex()
	DefaultUnmatched()
	DefaultEnd()
}

CliAppCompleteInterface the complete CliApp show hand method should have a field name like `Cc` *Arg the method call order by `construct > command > help > index > unmatched`

type CliAppInterface added in v1.1.0

type CliAppInterface interface {
	Construct()
}

CliAppInterface the interface of CliApp

type CliCmd deprecated added in v1.1.0

type CliCmd = Arg

CliCmd as the alias of Arg

Deprecated: maybe will be deleted when next version, please use Arg replace.

type Cmd added in v1.1.0

type Cmd struct {
	Command  string
	Alias    any                   //string, []string. the alias of the command
	Describe string                //describe the command
	Handler  func(cc *Arg)         //when command call then handler the request
	Options  map[string]CmdOptions // the command option
}

Cmd define the struct command

type CmdOptions added in v1.1.0

type CmdOptions struct {
	Option   string
	Alias    any
	Describe string
}

type Option added in v1.1.0

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

Option the command of options parse.

func (*Option) Unmarshal added in v1.1.0

func (c *Option) Unmarshal(v any)

Unmarshal parse the struct tag name arg <Name type `arg:"i name"`>

type PlgCProfile added in v1.3.0

type PlgCProfile struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	ExecName    string `json:"execName,omitempty"`
}

func (*PlgCProfile) GetRunCmd added in v1.3.0

func (c *PlgCProfile) GetRunCmd(args ...string) (*exec.Cmd, error)

func (*PlgCProfile) Run added in v1.3.0

func (c *PlgCProfile) Run(args ...string) ([]byte, error)

type PluginCommand added in v1.3.0

type PluginCommand struct {
	Name     string
	Descript string
	*CLI
}

PluginCommand Hot swap command (sub command)

func NewPluginCommand added in v1.3.0

func NewPluginCommand() *PluginCommand

type Repl added in v1.2.0

type Repl struct {
	Name        string
	Title       string
	HandlerFunc func(string) int
	BeforeExit  func()   // 退出前回调
	Exit        []string // 退出列表,默认为 exit
}

func (Repl) Run added in v1.2.0

func (c Repl) Run(cli *CLI)

Run to start repl command

Directories

Path Synopsis
Package butil bin util package will not run the init(), but bin will
Package butil bin util package will not run the init(), but bin will
syntax
Package syntax is bin language syntax extend, like digital computing.
Package syntax is bin language syntax extend, like digital computing.
Package tag reflect struct tag for bin
Package tag reflect struct tag for bin

Jump to

Keyboard shortcuts

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