bin

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2022 License: Apache-2.0 Imports: 14 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 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 interface{}, 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 interface{}, 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 interface{}, 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 interface{}, args ...interface{}) 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) interface{}

ParseValueByStr parse the command value to really type by format.

Types

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

GetInjection get Injection data

func (*CLI) Inject added in v1.1.0

func (cli *CLI) Inject(key string, value interface{}) *CLI

Inject inject for data from outside.

func (*CLI) RegisterAny added in v1.1.0

func (cli *CLI) RegisterAny(action interface{}) *CLI

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

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

func (*CLI) RegisterApp added in v1.1.0

func (cli *CLI) RegisterApp(ap interface{}, 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]interface{}) *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 interface{}) *CLI

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

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

func (*CLI) RegisterFunc added in v1.1.0

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

RegisterFunc register functional command, the format like

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

func (*CLI) Run added in v1.1.0

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

Run the run the application

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(*CliCmd) //help message by `Func`

	//the action by the Func
	Todo    func(*CliCmd) //cli callback
	TodoApp interface{}   //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 *CliCmd
}

CliApp the cli app.

type CliAppCompleteInterface added in v1.1.0

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

CliAppCompleteInterface the complete CliApp show hand method should have a field name like `Cc *CliCmd` 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 added in v1.1.0

type CliCmd struct {
	Data       map[string]interface{} // 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
}

CliCmd the command of the cli application.

func NewCliCmd added in v1.1.0

func NewCliCmd(args ...string) *CliCmd

NewCliCmd the construct of `CliCmd`

func NewCliCmdByString added in v1.1.0

func NewCliCmdByString(ss string) *CliCmd

NewCliCmdByString construction of `CliCmd` by string

@todo notice: `--test-string="Joshua 存在空格的字符串 Conero"` 解析失败

func (*CliCmd) AppendData added in v1.1.0

func (app *CliCmd) AppendData(vMap map[string]interface{}) *CliCmd

AppendData append the Data

func (*CliCmd) Arg added in v1.1.0

func (app *CliCmd) Arg(keys ...string) interface{}

Arg get arg after parsed the raw data

func (*CliCmd) ArgDefault added in v1.1.0

func (app *CliCmd) ArgDefault(key string, def interface{}) interface{}

ArgDefault can default value to get the arg

func (*CliCmd) ArgInt added in v1.1.0

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

ArgInt get args data see as int

func (*CliCmd) ArgRaw added in v1.1.0

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

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

func (*CliCmd) ArgRawDefault added in v1.1.0

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

ArgRawDefault get raw arg has default

func (*CliCmd) ArgRawLine added in v1.1.0

func (app *CliCmd) ArgRawLine() string

ArgRawLine get the raw line input.

func (*CliCmd) ArgStringSlice added in v1.1.0

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

ArgStringSlice get string-slice param args

func (*CliCmd) CallCmd added in v1.1.0

func (app *CliCmd) CallCmd(cmd string)

CallCmd call cmd

func (*CliCmd) CheckMustKey added in v1.1.0

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

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

func (*CliCmd) CheckSetting added in v1.1.0

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

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

func (*CliCmd) CmdType added in v1.1.0

func (app *CliCmd) CmdType() int

func (*CliCmd) CommandAlias added in v1.1.0

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

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

func (*CliCmd) CommandAliasAll added in v1.1.0

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

func (*CliCmd) Context added in v1.1.0

func (app *CliCmd) Context() CLI

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

func (*CliCmd) Cwd added in v1.1.0

func (app *CliCmd) Cwd() string

Cwd get the application current word dir.

func (*CliCmd) Next added in v1.1.0

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

Next Get key values from multiple key values

func (*CliCmd) QueueNext added in v1.1.0

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

QueueNext get next key from order left to right

func (*CliCmd) SubCommandAlias added in v1.1.0

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

func (*CliCmd) SubCommandAliasAll added in v1.1.0

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

type Cmd added in v1.1.0

type Cmd struct {
	Command  string
	Alias    interface{}           //string, []string. the alias of the command
	Describe string                //describe the command
	Handler  func(cc *CliCmd)      //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    interface{}
	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 interface{})

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

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.

Jump to

Keyboard shortcuts

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