cmd类

package
v0.0.0-...-2910145 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2024 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package gcmd 提供控制台操作功能,例如选项/参数读取和命令执行。

Index

Examples

Constants

View Source
const (
	CtxKeyParser    上下文类.StrKey = `CtxKeyParser`
	CtxKeyCommand   上下文类.StrKey = `CtxKeyCommand`
	CtxKeyArguments 上下文类.StrKey = `CtxKeyArguments`
)

Variables

This section is empty.

Functions

func BuildOptions

func BuildOptions(m map[string]string, prefix ...string) string

BuildOptions 将选项构建为字符串。

func GetArg

func GetArg(index int, def ...string) *泛型类.Var

GetArg 返回位于`index`处的参数作为gvar.Var类型。

Example
cmd类.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(
	`Arg[0]: "%v", Arg[1]: "%v", Arg[2]: "%v", Arg[3]: "%v"`,
	cmd类.GetArg(0), cmd类.GetArg(1), cmd类.GetArg(2), cmd类.GetArg(3),
)
Output:

Arg[0]: "gf", Arg[1]: "build", Arg[2]: "main.go", Arg[3]: ""

func GetArgAll

func GetArgAll() []string

GetArgAll 返回所有已解析的参数。

Example
cmd类.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(`%#v`, cmd类.GetArgAll())
Output:

[]string{"gf", "build", "main.go"}

func GetOpt

func GetOpt(name string, def ...string) *泛型类.Var

GetOpt 函数返回名为 `name` 的选项值,类型为 gvar.Var。

Example
cmd类.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(
	`Opt["o"]: "%v", Opt["y"]: "%v", Opt["d"]: "%v"`,
	cmd类.GetOpt("o"), cmd类.GetOpt("y"), cmd类.GetOpt("d", "default value"),
)
Output:

Opt["o"]: "gf.exe", Opt["y"]: "", Opt["d"]: "default value"

func GetOptAll

func GetOptAll() map[string]string

GetOptAll 返回所有已解析的选项。

Example
cmd类.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(`%#v`, cmd类.GetOptAll())

// May Output:
// map[string]string{"o":"gf.exe", "y":""}
Output:

func GetOptWithEnv

func GetOptWithEnv(key string, def ...interface{}) *泛型类.Var

GetOptWithEnv returns the command line argument of the specified `key`. If the argument does not exist, then it returns the environment variable with specified `key`. It returns the default value `def` if none of them exists.

Fetching Rules: 1. Command line arguments are in lowercase format, eg: gf.`package name`.<variable name>; 2. Environment arguments are in uppercase format, eg: GF_`package name`_<variable name>;

Example
fmt.Printf("Opt[gf.test]:%s\n", cmd类.GetOptWithEnv("gf.test"))
_ = 环境变量类.X设置值("GF_TEST", "YES")
fmt.Printf("Opt[gf.test]:%s\n", cmd类.GetOptWithEnv("gf.test"))
Output:

Opt[gf.test]:
Opt[gf.test]:YES

func Init

func Init(args ...string)

Init 进行自定义初始化。

Example
cmd类.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
fmt.Printf(`%#v`, cmd类.GetArgAll())
Output:

[]string{"gf", "build", "main.go"}

func Scan

func Scan(info ...interface{}) string

Scan 将 `info` 输出到标准输出(stdout),然后读取并返回用户输入,直到遇到换行符('\n')时停止。

Example
fmt.Println(cmd类.Scan("gf scan"))
Output:

gf scan

func Scanf

func Scanf(format string, info ...interface{}) string

Scanf 函数将按照 `format` 格式打印 `info` 到标准输出(stdout),然后读取用户输入,直到遇到换行符 '\n' 为止,并返回所读取的用户输入内容。

Example
fmt.Println(cmd类.Scanf("gf %s", "scanf"))
Output:

gf scanf

Types

type Argument

type Argument struct {
	Name   string // Option name.
	Short  string // Option short.
	Brief  string // 该Option的简要信息,用于帮助信息中。
	IsArg  bool   // IsArg 标记这个参数从命令行参数而非选项中获取值。
	Orphan bool   // 是否此Option已绑定或未绑定值。
}

Argument 是某些命令所使用的命令值。

type Command

type Command struct {
	Name          string        // 命令名称(区分大小写)。
	Usage         string        // 一行简短的描述,关于其使用方式,例如:gf build main.go [选项]
	Brief         string        // 这个命令将要执行的简短描述
	Description   string        // 一段详细描述
	Arguments     []Argument    // 参数数组,用于配置此命令的行为。
	Func          Function      // Custom function.
	FuncWithValue FuncWithValue // 自定义函数,带有输出参数,可以与命令调用者进行交互。
	HelpFunc      Function      // 自定义帮助函数
	Examples      string        // Usage examples.
	Additional    string        // 这个命令的附加信息,将会被添加到帮助信息的末尾。
	Strict        bool          // 严格解析选项,这意味着如果给出无效选项将返回错误。
	CaseSensitive bool          // CaseSensitive 解析选项,表示以区分大小写的方式解析输入选项。
	Config        string        // 配置节点名称,该名称同时从配置组件和命令行中获取值。
	// contains filtered or unexported fields
}

Command 结构体保存了关于一个可以处理自定义逻辑的参数的信息。

func CommandFromCtx

func CommandFromCtx(ctx context.Context) *Command

CommandFromCtx 从上下文中检索并返回 Command。

Example
var (
	command = cmd类.Command{
		Name: "start",
	}
)

ctx := context.WithValue(上下文类.X创建(), cmd类.CtxKeyCommand, &command)
unAddCtx := context.WithValue(上下文类.X创建(), cmd类.CtxKeyCommand, &cmd类.Command{})
nonKeyCtx := context.WithValue(上下文类.X创建(), "Testkey", &cmd类.Command{})

fmt.Println(cmd类.CommandFromCtx(ctx).Name)
fmt.Println(cmd类.CommandFromCtx(unAddCtx).Name)
fmt.Println(cmd类.CommandFromCtx(nonKeyCtx) == nil)
Output:

start

true

func NewFromObject

func NewFromObject(object interface{}) (rootCmd *Command, err error)

NewFromObject 通过给定的对象创建并返回一个根命令对象。

func (*Command) AddCommand

func (c *Command) AddCommand(commands ...*Command) error

AddCommand 向当前命令添加一个或多个子命令。

Example
commandRoot := &cmd类.Command{
	Name: "gf",
}
commandRoot.AddCommand(&cmd类.Command{
	Name: "start",
}, &cmd类.Command{})

commandRoot.Print()
Output:

USAGE
    gf COMMAND [OPTION]

COMMAND
    start

func (*Command) AddObject

func (c *Command) AddObject(objects ...interface{}) error

AddObject 通过结构体对象向当前命令添加一个或多个子命令。

Example
var (
	command = cmd类.Command{
		Name: "start",
	}
)

command.AddObject(&TestCmdObject{})

command.Print()
Output:

USAGE
    start COMMAND [OPTION]

COMMAND
    root    root env command

func (*Command) Print

func (c *Command) Print()

Print 将当前命令的帮助信息打印到标准输出(stdout)中。

Example
commandRoot := &cmd类.Command{
	Name: "gf",
}
commandRoot.AddCommand(&cmd类.Command{
	Name: "start",
}, &cmd类.Command{})

commandRoot.Print()
Output:

USAGE
    gf COMMAND [OPTION]

COMMAND
    start

func (*Command) PrintTo

func (c *Command) PrintTo(writer io.Writer)

PrintTo 将帮助信息打印到自定义的 io.Writer。

func (*Command) Run

func (c *Command) Run(ctx context.Context)

Run调用与此命令绑定的自定义函数。 如果出现任何错误,它将使用退出码1退出此进程。

func (*Command) RunWithError

func (c *Command) RunWithError(ctx context.Context) (err error)

RunWithError 调用与此命令绑定的自定义函数,并带有错误输出。

func (*Command) RunWithValue

func (c *Command) RunWithValue(ctx context.Context) (value interface{})

RunWithValue 调用与此命令绑定的自定义函数,并传入输出的值。 如果发生任何错误,该过程将以退出码 1 退出。

func (*Command) RunWithValueError

func (c *Command) RunWithValueError(ctx context.Context) (value interface{}, err error)

RunWithValueError 调用与此命令绑定的自定义函数,并带有值和错误输出。

type FuncWithValue

type FuncWithValue func(ctx context.Context, parser *Parser) (out interface{}, err error)

FuncWithValue 类似于 Func,但是带有输出参数,可以与命令调用者进行交互。

type Function

type Function func(ctx context.Context, parser *Parser) (err error)

Function 是一个自定义命令回调函数,它绑定到某个特定参数。

type Parser

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

参数解析器

func Parse

func Parse(supportedOptions map[string]bool, option ...ParserOption) (*Parser, error)

Parse 创建并返回一个新的 Parser,其参数为 os.Args 以及支持的选项。

注意,参数 `supportedOptions` 形式为 [选项名: 是否需要参数],这意味着 `supportedOptions` 的值项表示对应的选项名是否需要参数。

可选参数 `strict` 指定在遇到无效选项时是否停止解析并返回错误。

Example
os.Args = []string{"gf", "build", "main.go", "-o=gf.exe", "-y"}
p, err := cmd类.Parse(g.MapStrBool{
	"o,output": true,
	"y,yes":    false,
})
if err != nil {
	panic(err)
}
fmt.Println(p.GetOpt("o"))
fmt.Println(p.GetOpt("output"))
fmt.Println(p.GetOpt("y") != nil)
fmt.Println(p.GetOpt("yes") != nil)
fmt.Println(p.GetOpt("none") != nil)
fmt.Println(p.GetOpt("none", "Def"))
Output:

gf.exe
gf.exe
true
true
false
Def

func ParseArgs

func ParseArgs(args []string, supportedOptions map[string]bool, option ...ParserOption) (*Parser, error)

ParseArgs 创建并返回一个新的解析器,该解析器包含给定的参数及支持的选项。

注意,参数 `supportedOptions` 形式为 [选项名称: 是否需要参数],这意味着 `supportedOptions` 中的值项表示对应的选项名称是否需要参数。

可选参数 `strict` 指定了当遇到无效选项时,是否停止解析并返回错误。

Example
p, _ := cmd类.ParseArgs([]string{
	"gf", "--force", "remove", "-fq", "-p=www", "path", "-n", "root",
}, nil)

fmt.Println(p.GetArgAll())
fmt.Println(p.GetOptAll())
Output:

[gf path]
map[force:remove fq: n:root p:www]

func ParserFromCtx

func ParserFromCtx(ctx context.Context) *Parser

ParserFromCtx 从上下文中检索并返回 Parser。

Example
parser, _ := cmd类.Parse(nil)

ctx := context.WithValue(上下文类.X创建(), cmd类.CtxKeyParser, parser)
nilCtx := context.WithValue(上下文类.X创建(), "NilCtxKeyParser", parser)

fmt.Println(cmd类.ParserFromCtx(ctx).GetArgAll())
fmt.Println(cmd类.ParserFromCtx(nilCtx) == nil)
Output:

[gf build main.go]
true

func (*Parser) GetArg

func (p *Parser) GetArg(index int, def ...string) *泛型类.Var

GetArg 返回位于`index`处的参数作为gvar.Var类型。

Example
p, _ := cmd类.ParseArgs([]string{
	"gf", "--force", "remove", "-fq", "-p=www", "path", "-n", "root",
}, nil)

fmt.Println(p.GetArg(-1, "Def").String())
fmt.Println(p.GetArg(-1) == nil)
Output:

Def
true

func (*Parser) GetArgAll

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

GetArgAll 返回所有已解析的参数。

func (*Parser) GetOpt

func (p *Parser) GetOpt(name string, def ...interface{}) *泛型类.Var

GetOpt 函数返回名为 `name` 的选项值,类型为 gvar.Var。

func (*Parser) GetOptAll

func (p *Parser) GetOptAll() map[string]string

GetOptAll 返回所有已解析的选项。

func (Parser) MarshalJSON

func (p Parser) MarshalJSON() ([]byte, error)

MarshalJSON 实现了 json.Marshal 接口所需的 MarshalJSON 方法。

type ParserOption

type ParserOption struct {
	CaseSensitive bool // 以区分大小写的方式标记选项解析
	Strict        bool // 如果传递了无效的选项,则停止解析并返回错误。
}

ParserOption 管理解析选项。

Jump to

Keyboard shortcuts

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