cmd类

package
v0.0.0-...-7e18bce Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2024 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

包gcmd提供控制台操作,如读取选项/参数和运行命令。 md5:bb72337a704c599f

Index

Examples

Constants

View Source
const (
	CtxKeyParser         gctx.StrKey = `CtxKeyParser`
	CtxKeyCommand        gctx.StrKey = `CtxKeyCommand`
	CtxKeyArgumentsIndex gctx.StrKey = `CtxKeyArgumentsIndex`
)

Variables

This section is empty.

Functions

func BuildOptions

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

BuildOptions 将选项构建为字符串。 md5:c722b017f3a50346

func GetArg

func GetArg(index int, def ...string) *gvar.Var

GetArg 作为gvar.Var返回索引为`index`的参数。 md5:12ea2f8d74c6370d

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

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

}
Output:

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

func GetArgAll

func GetArgAll() []string

GetArgAll 返回所有解析的参数。 md5:85cc0fd5995d4878

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetArgAll())

}
Output:

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

func GetOpt

func GetOpt(name string, def ...string) *gvar.Var

GetOpt 作为gvar.Var返回名为`name`的选项值。 md5:1859b868ee779be0

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

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

}
Output:

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

func GetOptAll

func GetOptAll() map[string]string

GetOptAll 返回所有已解析的选项。 md5:6de4d266d8991786

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetOptAll())

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

func GetOptWithEnv

func GetOptWithEnv(key string, def ...interface{}) *gvar.Var

GetOptWithEnv 返回指定 `key` 的命令行参数。 如果该参数不存在,则返回指定 `key` 的环境变量。 如果两者都不存在,它将返回默认值 `def`。

获取规则: 1. 命令行参数采用小写格式,例如:gf.`包名`.<变量名>; 2. 环境变量采用大写格式,例如:GF_`包名`_<变量名>。 md5:e3d5c0c773430740

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"

	genv "gitee.com/go_888/goframe/os/genv"
)

func main() {
	fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))
	_ = genv.X设置值("GF_TEST", "YES")
	fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))

}
Output:

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

func Init

func Init(args ...string)

Init 进行自定义初始化。 md5:08f8a2052942d9c8

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetArgAll())

}
Output:

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

func Scan

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

Scan 将 `info` 打印到标准输出,读取并返回用户输入,直到遇到 '\n'。 md5:ddd0cd56978ea021

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	fmt.Println(gcmd.Scan("gf scan"))

}
Output:

gf scan

func Scanf

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

Scanf 将 `info` 按照 `format` 格式打印到标准输出,然后读取并返回用户输入,直到遇到换行符'\n'停止。 md5:8aa27cd5ac6f9224

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	fmt.Println(gcmd.Scanf("gf %s", "scanf"))

}
Output:

gf scanf

Types

type Argument

type Argument struct {
	Name   string // Option name.
	Short  string // Option short.
	Brief  string // 这个选项的简要信息,用于帮助信息中。 md5:b913553040a0d889
	IsArg  bool   // IsArg 标记这个参数从命令行参数而不是选项中获取值。 md5:24e6cc6cb658557a
	Orphan bool   // 此选项是否有值与之绑定。 md5:bc1b6ee078e2683c
}

Argument 是某些命令使用的命令值。 md5:e5c110dcf519025a

type Command

type Command struct {
	Name          string        // 命令名称(大小写敏感)。 md5:44e7c13c9c0eced2
	Usage         string        // 关于其用途的简短描述,例如:gf build main.go [选项]. md5:e2660484a0edfee8
	Brief         string        // 一个简短的描述,说明此命令将执行的操作。 md5:4a0304d2ac452238
	Description   string        // 一个详细的描述。 md5:b83b3d2318b54bce
	Arguments     []Argument    // 参数数组,配置此命令的行为。 md5:9c82b0f6e377e648
	Func          Function      // Custom function.
	FuncWithValue FuncWithValue // 自定义函数,带有输出参数,能够与命令调用者进行交互。 md5:586037addaa736f6
	HelpFunc      Function      // Custom help function
	Examples      string        // Usage examples.
	Additional    string        // 关于此命令的附加信息,将追加到帮助信息的末尾。 md5:328b9830bf970895
	Strict        bool          // 严格的解析选项,这意味着如果提供无效的选项,它会返回错误。 md5:5e8eec207aef7c7a
	CaseSensitive bool          // 区分大小写的解析选项,这意味着它以区分大小写的方式解析输入选项。 md5:b18eddb5f60c7176
	Config        string        // 配置节点名称,它也会从配置组件中获取值,以及从命令行中获取。 md5:0f67ea7288e8e541
	// contains filtered or unexported fields
}

Command 包含有关可以处理自定义逻辑的参数的信息。 md5:b0e0f23cc6e868c5

func CommandFromCtx

func CommandFromCtx(ctx context.Context) *Command

CommandFromCtx从上下文检索并返回Command。 md5:81a6b36fc029401b

Example
package main

import (
	"context"
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"

	gctx "gitee.com/go_888/goframe/os/gctx"
)

func main() {
	var (
		command = gcmd.Command{
			Name: "start",
		}
	)

	ctx := context.WithValue(gctx.X创建(), gcmd.CtxKeyCommand, &command)
	unAddCtx := context.WithValue(gctx.X创建(), gcmd.CtxKeyCommand, &gcmd.Command{})
	nonKeyCtx := context.WithValue(gctx.X创建(), "Testkey", &gcmd.Command{})

	fmt.Println(gcmd.CommandFromCtx(ctx).Name)
	fmt.Println(gcmd.CommandFromCtx(unAddCtx).Name)
	fmt.Println(gcmd.CommandFromCtx(nonKeyCtx) == nil)

}
Output:

start

true

func NewFromObject

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

NewFromObject 使用给定的对象创建并返回一个根命令对象。 md5:3bdd362e3ec9f337

func (*Command) AddCommand

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

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

Example
package main

import (
	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	commandRoot := &gcmd.Command{
		Name: "gf",
	}
	commandRoot.AddCommand(&gcmd.Command{
		Name: "start",
	}, &gcmd.Command{})

	commandRoot.Print()

}
Output:

USAGE
    gf COMMAND [OPTION]

COMMAND
    start

func (*Command) AddObject

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

AddObject 通过struct对象向当前命令添加一个或多个子命令。 md5:8de76f64f667f83d

Example
var (
	command = gcmd.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)。 md5:f96bdfd3fe6f19a6

Example
package main

import (
	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	commandRoot := &gcmd.Command{
		Name: "gf",
	}
	commandRoot.AddCommand(&gcmd.Command{
		Name: "start",
	}, &gcmd.Command{})

	commandRoot.Print()

}
Output:

USAGE
    gf COMMAND [OPTION]

COMMAND
    start

func (*Command) PrintTo

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

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

func (*Command) Run

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

Run 调用与该命令绑定的自定义函数,根据os.Args执行。 如果发生任何错误,它将使进程退出并返回退出代码1。 md5:f6512536eb3555fe

func (*Command) RunWithError

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

RunWithError 调用与该命令关联的 os.Args 中的自定义函数,同时输出错误信息。 md5:59f4632a1aab9342

func (*Command) RunWithSpecificArgs

func (c *Command) RunWithSpecificArgs(ctx context.Context, args []string) (value interface{}, err error)

RunWithSpecificArgs 使用绑定到该命令的特定参数调用自定义函数,并将值和错误输出传递给它。 md5:48c98cbef4733851

func (*Command) RunWithValue

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

RunWithValue 调用与该命令绑定的 os.Args 中的自定义函数,传入值作为输出。如果发生任何错误,它将退出进程并返回退出码 1。 md5:4d204c2503673c10

func (*Command) RunWithValueError

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

RunWithValueError 使用os.Args中的值调用与此命令关联的自定义函数,并带有值和错误输出。 md5:007ad372fee78f96

type FuncWithValue

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

FuncWithValue 类似于 Func,但它带有输出参数,这些参数可以与命令调用者进行交互。 md5:e8459756fad8cbb9

type Function

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

Function 是一个绑定到特定参数的自定义命令回调函数。 md5:74f820cae660a1b5

type Parser

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

Parser for arguments.

func Parse

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

Parse 创建并返回一个新的Parser,使用os.Args和受支持的选项。

请注意,参数`supportedOptions`是[key: need argument]形式,其中 `supportedOptions`的值项表示相应的选项名是否需要参数。

可选参数`strict`指定如果遇到无效选项时,是否停止解析并返回错误。 md5:136e728aecd2a3b5

Example
package main

import (
	"fmt"
	"os"

	"gitee.com/go_888/goframe/frame/g"
	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	os.Args = []string{"gf", "build", "main.go", "-o=gf.exe", "-y"}
	p, err := gcmd.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 创建并返回一个新的Parser,具有给定的参数和支持的选项。

注意,参数`supportedOptions`是一个[选项名称: 需要参数]的映射,这意味着`supportedOptions`的值项表示对应选项名称是否需要参数。

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

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	p, _ := gcmd.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 从上下文中检索并返回解析器。 md5:260bf6b7d06ebc7c

Example
package main

import (
	"context"
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"

	gctx "gitee.com/go_888/goframe/os/gctx"
)

func main() {
	parser, _ := gcmd.Parse(nil)

	ctx := context.WithValue(gctx.X创建(), gcmd.CtxKeyParser, parser)
	nilCtx := context.WithValue(gctx.X创建(), "NilCtxKeyParser", parser)

	fmt.Println(gcmd.ParserFromCtx(ctx).GetArgAll())
	fmt.Println(gcmd.ParserFromCtx(nilCtx) == nil)

}
Output:

[gf build main.go]
true

func (*Parser) GetArg

func (p *Parser) GetArg(index int, def ...string) *gvar.Var

GetArg 作为gvar.Var返回索引为`index`的参数。 md5:12ea2f8d74c6370d

Example
package main

import (
	"fmt"

	gcmd "gitee.com/go_888/goframe/os/gcmd"
)

func main() {
	p, _ := gcmd.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 返回所有解析的参数。 md5:85cc0fd5995d4878

func (*Parser) GetOpt

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

GetOpt 作为gvar.Var返回名为`name`的选项值。 md5:1859b868ee779be0

func (*Parser) GetOptAll

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

GetOptAll 返回所有已解析的选项。 md5:6de4d266d8991786

func (Parser) MarshalJSON

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

MarshalJSON 实现了接口 MarshalJSON 以供 json.Marshal 使用。 md5:43c3b36e60a18f9a

type ParserOption

type ParserOption struct {
	CaseSensitive bool // 以区分大小写的方式标记选项解析。 md5:8d9524f23421dc60
	Strict        bool // 如果传入了无效的选项,是否停止解析并返回错误。 md5:2564adc332d2fd51
}

ParserOption负责管理解析选项。 md5:6294496b49d5c3bb

Jump to

Keyboard shortcuts

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