-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgetopt.go
203 lines (163 loc) · 5.39 KB
/
getopt.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Copyright (c) 2011, SoundCloud Ltd., Daniel Bornkessel
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Source code and contact info at http://github.com/kesselborn/go-getopt
package getopt
import "os"
const (
InvalidOption = iota
MissingValue
InvalidValue
MissingOption
OptionValueError
ConsistencyError
ConfigFileNotFound
ConfigParsed
MissingArgument
NoSubCommand
NoScope
UnknownSubCommand
UnknownScope
)
const OPTIONS_SEPARATOR = "--"
type GetOptError struct {
ErrorCode int
message string
}
func (err *GetOptError) Error() (message string) {
return err.message
}
func (optionsDefinition Options) usageHelpOptionNames() (shortOpt string, longOpt string) {
shortOpt = "h"
longOpt = "help"
for _, option := range optionsDefinition.Definitions {
if option.Flags&Usage > 0 {
shortOpt = option.ShortOpt()
}
if option.Flags&Help > 0 {
longOpt = option.LongOpt()
}
}
return
}
// todo: method signature sucks
func (optionsDefinition Options) checkForHelpOrUsage(args []string, usageString string, helpString string) (wantsHelp bool, wantsUsage bool) {
for _, arg := range args {
switch arg {
case usageString:
wantsUsage = true
case helpString:
wantsHelp = true
case OPTIONS_SEPARATOR:
goto allOptsParsed
}
}
allOptsParsed:
return
}
func (optionsDefinition Options) ParseCommandLine() (options map[string]OptionValue, arguments []string, passThrough []string, err *GetOptError) {
return optionsDefinition.parseCommandLineImpl(os.Args[1:], mapifyEnvironment(os.Environ()), 0)
}
func (optionsDefinition Options) parseCommandLineImpl(args []string, environment map[string]string, flags int) (options map[string]OptionValue, arguments []string, passThrough []string, err *GetOptError) {
if err = checkOptionsDefinitionConsistency(optionsDefinition); err == nil {
options = make(map[string]OptionValue)
arguments = make([]string, 0)
for _, option := range optionsDefinition.Definitions {
switch {
case option.Flags&Flag != 0: // all flags are false by default
options[option.Key()], err = assignValue(false, "false")
case option.Flags&ExampleIsDefault != 0: // set default
var newOptionValue OptionValue
newOptionValue, err = assign(option.DefaultValue)
newOptionValue.Set = false
options[option.Key()] = newOptionValue
}
}
usageString, helpString := optionsDefinition.usageHelpOptionNames()
wantsHelp, wantsUsage := optionsDefinition.checkForHelpOrUsage(args, "-"+usageString, "--"+helpString)
if err == nil {
err = optionsDefinition.setEnvAndConfigValues(options, environment)
for i := 0; i < len(args) && err == nil; i++ {
var opt, val string
var found bool
token := args[i]
if argumentsEnd(token) {
passThrough = args[i+1:]
break
}
if isValue(token) {
arguments = append(arguments, token)
continue
}
opt, val, found = parseShortOpt(token)
if found {
buffer := token
for found && optionsDefinition.IsFlag(opt) && len(buffer) > 2 {
// concatenated options ... continue parsing
currentOption, _ := optionsDefinition.FindOption(opt)
key := currentOption.Key()
options[key], err = assignValue(currentOption.DefaultValue, "true")
// make it look as if we have a normal option with a '-' prefix
buffer = "-" + buffer[2:]
opt, val, found = parseShortOpt(buffer)
}
} else {
opt, val, found = parseLongOpt(token)
}
currentOption, found := optionsDefinition.FindOption(opt)
key := currentOption.Key()
if !found {
err = &GetOptError{InvalidOption, "invalid option '" + token + "'"}
break
}
if optionsDefinition.IsFlag(opt) {
options[key], err = assignValue(true, "true")
} else {
if val == "" {
if len(args) > i+1 && isValue(args[i+1]) {
i = i + 1
val = args[i]
} else {
err = &GetOptError{MissingValue, "Option '" + token + "' needs a value"}
break
}
}
if !isValue(val) {
err = &GetOptError{InvalidValue, "Option '" + token + "' got invalid value: '" + val + "'"}
break
}
options[key], err = assignValue(currentOption.DefaultValue, val)
}
}
}
if configKey := optionsDefinition.ConfigOptionKey(); configKey != "" && flags&ConfigParsed == 0 {
if option, found := options[configKey]; found {
if environment, e := processConfigFile(option.String, environment); e == nil {
return optionsDefinition.parseCommandLineImpl(args, environment, flags|ConfigParsed)
} else if option.Set == true { // if config file had a default value, don't freak out
err = e
}
}
}
if err == nil {
for _, requiredOption := range optionsDefinition.RequiredOptions() {
if options[requiredOption].Set == false {
err = &GetOptError{MissingOption, "Option '" + requiredOption + "' is missing"}
break
}
}
requiredArguments := optionsDefinition.RequiredArguments()
if numOfRequiredArguments := len(requiredArguments.Definitions); numOfRequiredArguments > len(arguments) {
firstMissingArgumentName := requiredArguments.Definitions[len(arguments)].Key()
err = &GetOptError{MissingArgument, "Missing required argument <" + firstMissingArgumentName + ">"}
}
}
if wantsHelp {
options[helpString], err = assignValue("", "help")
}
if wantsUsage {
options[helpString], err = assignValue("", "usage")
}
}
return
}