Documentation ¶
Overview ¶
Package gcmd provides console operations, like options/arguments reading and command running.
Index ¶
- Constants
- func BuildOptions(m map[string]string, prefix ...string) string
- func GetArg(index int, def ...string) *gvar.Var
- func GetArgAll() []string
- func GetOpt(name string, def ...string) *gvar.Var
- func GetOptAll() map[string]string
- func GetOptWithEnv(key string, def ...interface{}) *gvar.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) 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 ¶
Variables ¶
This section is empty.
Functions ¶
func BuildOptions ¶
BuildOptions builds the options as string.
func GetArg ¶
GetArg returns the argument at `index` as gvar.Var.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/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 returns all parsed arguments.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/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 ¶
GetOpt returns the option value named `name` as gvar.Var.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/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 ¶
GetOptAll returns all parsed options.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/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 ¶
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 ¶
package main import ( "fmt" "github.com/gogf/gf/v2/os/gcmd" "github.com/gogf/gf/v2/os/genv" ) func main() { fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test")) _ = genv.Set("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 does custom initialization.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/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 prints `info` to stdout, reads and returns user input, which stops by '\n'.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/os/gcmd" ) func main() { fmt.Println(gcmd.Scan("gf scan")) }
Output: gf scan
Types ¶
type Argument ¶
type Argument struct { Name string // Option name. Short string // Option short. Brief string // Brief info about this Option, which is used in help info. IsArg bool // IsArg marks this argument taking value from command line argument instead of option. Orphan bool // Whether this Option having or having no value bound to it. }
Argument is the command value that are used by certain command.
type Command ¶
type Command struct { Name string // Command name(case-sensitive). Usage string // A brief line description about its usage, eg: gf build main.go [OPTION] Brief string // A brief info that describes what this command will do. Description string // A detailed description. Arguments []Argument // Argument array, configuring how this command act. Func Function // Custom function. FuncWithValue FuncWithValue // Custom function with output parameters that can interact with command caller. HelpFunc Function // Custom help function Examples string // Usage examples. Additional string // Additional info about this command, which will be appended to the end of help info. Strict bool // Strict parsing options, which means it returns error if invalid option given. CaseSensitive bool // CaseSensitive parsing options, which means it parses input options in case-sensitive way. Config string // Config node name, which also retrieves the values from config component along with command line. // contains filtered or unexported fields }
Command holds the info about an argument that can handle custom logic.
func CommandFromCtx ¶
CommandFromCtx retrieves and returns Command from context.
Example ¶
package main import ( "context" "fmt" "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gcmd" ) func main() { var ( command = gcmd.Command{ Name: "start", } ) ctx := context.WithValue(gctx.New(), gcmd.CtxKeyCommand, &command) unAddCtx := context.WithValue(gctx.New(), gcmd.CtxKeyCommand, &gcmd.Command{}) nonKeyCtx := context.WithValue(gctx.New(), "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 ¶
NewFromObject creates and returns a root command object using given object.
func (*Command) AddCommand ¶
AddCommand adds one or more sub-commands to current command.
Example ¶
package main import ( "github.com/gogf/gf/v2/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 ¶
AddObject adds one or more sub-commands to current command using struct object.
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 prints help info to stdout for current command.
Example ¶
package main import ( "github.com/gogf/gf/v2/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) Run ¶
Run calls custom function that bound to this command. It exits this process with exit code 1 if any error occurs.
func (*Command) RunWithError ¶
RunWithError calls custom function that bound to this command with error output.
func (*Command) RunWithValue ¶
RunWithValue calls custom function that bound to this command with value output. It exits this process with exit code 1 if any error occurs.
type FuncWithValue ¶
FuncWithValue is similar like Func but with output parameters that can interact with command caller.
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 creates and returns a new Parser with os.Args and supported options.
Note that the parameter `supportedOptions` is as [option name: need argument], which means the value item of `supportedOptions` indicates whether corresponding option name needs argument or not.
The optional parameter `strict` specifies whether stops parsing and returns error if invalid option passed.
Example ¶
package main import ( "fmt" "os" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/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 creates and returns a new Parser with given arguments and supported options.
Note that the parameter `supportedOptions` is as [option name: need argument], which means the value item of `supportedOptions` indicates whether corresponding option name needs argument or not.
The optional parameter `strict` specifies whether stops parsing and returns error if invalid option passed.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/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 ¶
ParserFromCtx retrieves and returns Parser from context.
Example ¶
package main import ( "context" "fmt" "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gcmd" ) func main() { parser, _ := gcmd.Parse(nil) ctx := context.WithValue(gctx.New(), gcmd.CtxKeyParser, parser) nilCtx := context.WithValue(gctx.New(), "NilCtxKeyParser", parser) fmt.Println(gcmd.ParserFromCtx(ctx).GetArgAll()) fmt.Println(gcmd.ParserFromCtx(nilCtx) == nil) }
Output: [gf build main.go] true
func (*Parser) GetArg ¶
GetArg returns the argument at `index` as gvar.Var.
Example ¶
package main import ( "fmt" "github.com/gogf/gf/v2/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) MarshalJSON ¶
MarshalJSON implements the interface MarshalJSON for json.Marshal.
type ParserOption ¶ added in v2.1.0
type ParserOption struct { CaseSensitive bool // Marks options parsing in case-sensitive way. Strict bool // Whether stops parsing and returns error if invalid option passed. }
ParserOption manages the parsing options.