-
Notifications
You must be signed in to change notification settings - Fork 3
/
command_line_parser.go
118 lines (105 loc) · 2.42 KB
/
command_line_parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package cli
import (
"fmt"
"strings"
)
type commandline struct {
// defined
flags []*Flag
commands []*Command
// parsed results
command *Command
args []string
}
func (c *commandline) parse(arguments []string) (err error) {
for i := 0; i < len(arguments); i++ {
arg := arguments[i]
if arg == "--" {
c.args = append(c.args, arguments[i+1:]...)
break
} else if strings.HasPrefix(arg, "-") && arg != "-" {
peekedNext, err := c.parseOneArg(i, arguments)
if err != nil {
return err
}
if peekedNext {
i++
}
} else {
if len(c.commands) == 0 {
c.args = append(c.args, arg)
} else {
c.command = lookupCommand(c.commands, arg)
c.args = append(c.args, arguments[i:]...)
break
}
}
}
return nil
}
func (c *commandline) parseOneArg(i int, arguments []string) (bool, error) {
prefix := ""
name := ""
valueInline := ""
valueNext := ""
arg := arguments[i]
if strings.HasPrefix(arg, "--") { // long flag
prefix = "--"
kv := strings.SplitN(arg[2:], "=", 2)
name = kv[0]
if len(kv) == 2 { // --name=value
valueInline = kv[1]
} else if i+1 < len(arguments) { // --name value
next := arguments[i+1]
if !strings.HasPrefix(next, "-") {
valueNext = next
}
}
} else { // short flag
prefix = "-"
name = arg[1:2]
if len(arg) > 2 {
if arg[2] == '=' {
valueInline = arg[3:] // -x=value
} else {
valueInline = arg[2:] // -xvalue
}
} else if i+1 < len(arguments) { // -x value
next := arguments[i+1]
if !strings.HasPrefix(next, "-") {
valueNext = next
}
}
}
if len(valueInline) > 0 {
// remove quote for inline value
if strings.HasPrefix(valueInline, "\"") && strings.HasSuffix(valueInline, "\"") {
valueInline = valueInline[1 : len(valueInline)-1]
} else if strings.HasPrefix(valueInline, "'") && strings.HasSuffix(valueInline, "'") {
valueInline = valueInline[1 : len(valueInline)-1]
}
}
flag := lookupFlag(c.flags, name)
if flag == nil {
return false, fmt.Errorf("unrecognized option '%s'", prefix+name)
}
if flag.IsBool {
if valueInline == "" {
valueInline = "true"
}
err := flag.SetValue(valueInline)
return false, err
}
value := valueInline + valueNext
if value == "" {
value = flag.NoOptDefValue
}
if value == "" {
return false, fmt.Errorf("option requires an argument '%s'", prefix+name)
}
err := flag.SetValue(value)
if err != nil {
return false, err
}
return valueNext != "", nil
}