Introduction

The main aspect of command line parsing is option parsing. The gcmd component provides a Parse method for customizing option parsing, including specifying which option names exist and whether each option has values. With this configuration, all parameters and options can be parsed and categorized.

Command - Args Parsing - 图1tip

In most cases, we do not need to explicitly create a Parser object, as we manage multiple commands through hierarchical management and object management. However, the underlying implementation still uses the Parser approach, so understanding the principle in this chapter will suffice.

Related methods:

For more Parser methods, please refer to the API documentation: https://pkg.go.dev/github.com/gogf/gf/v2/os/gcmd#Parser

  1. func Parse(supportedOptions map[string]bool, option ...ParserOption) (*Parser, error)
  2. func ParseWithArgs(args []string, supportedOptions map[string]bool, option ...ParserOption) (*Parser, error)
  3. func ParserFromCtx(ctx context.Context) *Parser
  4. func (p *Parser) GetArg(index int, def ...string) *gvar.Var
  5. func (p *Parser) GetArgAll() []string
  6. func (p *Parser) GetOpt(name string, def ...interface{}) *gvar.Var
  7. func (p *Parser) GetOptAll() map[string]string

Where ParserOption is as follows:

  1. // ParserOption manages the parsing options.
  2. type ParserOption struct {
  3. CaseSensitive bool // Marks options parsing in case-sensitive way.
  4. Strict bool // Whether stops parsing and returns error if invalid option passed.
  5. }

Parsing example:

  1. parser, err := gcmd.Parse(g.MapStrBool{
  2. "n,name": true,
  3. "v,version": true,
  4. "a,arch": true,
  5. "o,os": true,
  6. "p,path": true,
  7. })

As you can see, the option input parameter is actually of map type. The key is the option name, with different names for the same option separated by the , symbol. For instance, in this example, the n and name options are the same option. When the user inputs -n john, both n and name options will receive the data john.

The value is a boolean type indicating whether the option requires value parsing. This option configuration is crucial, as some options do not need to receive data, serving merely as a flag. For example, with the input -f force, if data needs to be parsed, the value for option f is force; otherwise, force is a command line argument rather than an option.

Usage Example

  1. func ExampleParse() {
  2. os.Args = []string{"gf", "build", "main.go", "-o=gf.exe", "-y"}
  3. p, err := gcmd.Parse(g.MapStrBool{
  4. "o,output": true,
  5. "y,yes": false,
  6. })
  7. if err != nil {
  8. panic(err)
  9. }
  10. fmt.Println(p.GetOpt("o"))
  11. fmt.Println(p.GetOpt("output"))
  12. fmt.Println(p.GetOpt("y") != nil)
  13. fmt.Println(p.GetOpt("yes") != nil)
  14. fmt.Println(p.GetOpt("none") != nil)
  15. // Output:
  16. // gf.exe
  17. // gf.exe
  18. // true
  19. // true
  20. // false
  21. }