Documentation ¶
Overview ¶
Package gcmd 提供控制台操作功能,例如选项/参数读取和命令执行。
Index ¶
- Constants
- func BuildOptions(m map[string]string, prefix ...string) string
- func GetArg(index int, def ...string) *泛型类.Var
- func GetArgAll() []string
- func GetOpt(name string, def ...string) *泛型类.Var
- func GetOptAll() map[string]string
- func GetOptWithEnv(key string, def ...interface{}) *泛型类.Var
- func Init(args ...string)
- func Scan(info ...interface{}) string
- func Scanf(format string, info ...interface{}) string
- type Argument
- type Command
- func (c *Command) AddCommand(commands ...*Command) error
- func (c *Command) AddObject(objects ...interface{}) error
- func (c *Command) Print()
- func (c *Command) PrintTo(writer io.Writer)
- func (c *Command) Run(ctx context.Context)
- func (c *Command) RunWithError(ctx context.Context) (err error)
- func (c *Command) RunWithValue(ctx context.Context) (value interface{})
- func (c *Command) RunWithValueError(ctx context.Context) (value interface{}, err error)
- type FuncWithValue
- type Function
- type Parser
- type ParserOption
Examples ¶
Constants ¶
const ( CtxKeyParser 上下文类.StrKey = `CtxKeyParser` CtxKeyCommand 上下文类.StrKey = `CtxKeyCommand` CtxKeyArguments 上下文类.StrKey = `CtxKeyArguments` )
Variables ¶
This section is empty.
Functions ¶
func BuildOptions ¶
BuildOptions 将选项构建为字符串。
func GetArg ¶
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 ¶
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 ¶
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"}
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 ¶
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 ¶
NewFromObject 通过给定的对象创建并返回一个根命令对象。
func (*Command) AddCommand ¶
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 ¶
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) RunWithError ¶
RunWithError 调用与此命令绑定的自定义函数,并带有错误输出。
func (*Command) RunWithValue ¶
RunWithValue 调用与此命令绑定的自定义函数,并传入输出的值。 如果发生任何错误,该过程将以退出码 1 退出。
type FuncWithValue ¶
FuncWithValue 类似于 Func,但是带有输出参数,可以与命令调用者进行交互。
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 ¶
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 ¶
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) MarshalJSON ¶
MarshalJSON 实现了 json.Marshal 接口所需的 MarshalJSON 方法。
type ParserOption ¶
type ParserOption struct { CaseSensitive bool // 以区分大小写的方式标记选项解析 Strict bool // 如果传递了无效的选项,则停止解析并返回错误。 }
ParserOption 管理解析选项。