-
Notifications
You must be signed in to change notification settings - Fork 0
/
getopt.go
297 lines (275 loc) · 8.99 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Package getopt implements a command-line argument parser.
//
// It tries to cover all common styles of option syntaxes, and provides context
// information when given a partial input. It is mainly useful for writing
// completion engines and wrapper programs.
//
// If you are looking for an option parser for your go program, consider using
// the flag package in the standard library instead.
package getopt
//go:generate stringer -type=Config,Arity,ContextType -output=string.go
import (
"fmt"
"strings"
"github.com/markusbkk/elvish/pkg/diag"
)
// Config configurates the parsing behavior.
type Config uint
const (
// Stop parsing options after "--".
StopAfterDoubleDash Config = 1 << iota
// Stop parsing options before the first non-option argument.
StopBeforeFirstNonOption
// Allow long options to start with "-", and disallow short options.
// Replicates the behavior of getopt_long_only and the flag package.
LongOnly
// Config to replicate the behavior of GNU's getopt_long.
GNU = StopAfterDoubleDash
// Config to replicate the behavior of BSD's getopt_long.
BSD = StopAfterDoubleDash | StopBeforeFirstNonOption
)
// Tests whether a configuration has all specified flags set.
func (c Config) has(bits Config) bool { return c&bits == bits }
// OptionSpec is a command-line option.
type OptionSpec struct {
// Short option. Set to 0 for long-only.
Short rune
// Long option. Set to "" for short-only.
Long string
// Whether the option takes an argument, and whether it is required.
Arity Arity
}
// Arity indicates whether an option takes an argument, and whether it is
// required.
type Arity uint
const (
// The option takes no argument.
NoArgument Arity = iota
// The option requires an argument. The argument can come either directly
// after a short option (-oarg), after a long option followed by an equal
// sign (--long=arg), or as a separate argument after the option (-o arg,
// --long arg).
RequiredArgument
// The option takes an optional argument. The argument can come either
// directly after a short option (-oarg) or after a long option followed by
// an equal sign (--long=arg).
OptionalArgument
)
// Option represents a parsed option.
type Option struct {
Spec *OptionSpec
Unknown bool
Long bool
Argument string
}
// Context describes the context of the last argument.
type Context struct {
// The nature of the context.
Type ContextType
// Current option, with a likely incomplete Argument. Non-nil when Type is
// OptionArgument.
Option *Option
// Current partial long option name or argument. Non-empty when Type is
// LongOption or Argument.
Text string
}
// ContextType encodes how the last argument can be completed.
type ContextType uint
const (
// OptionOrArgument indicates that the last element may be either a new
// option or a new argument. Returned when it is an empty string.
OptionOrArgument ContextType = iota
// AnyOption indicates that the last element must be new option, short or
// long. Returned when it is "-".
AnyOption
// LongOption indicates that the last element is a long option (but not its
// argument). The partial name of the long option is stored in Context.Text.
LongOption
// ChainShortOption indicates that a new short option may be chained.
// Returned when the last element consists of a chain of options that take
// no arguments.
ChainShortOption
// OptionArgument indicates that the last element list must be an argument
// to an option. The option in question is stored in Context.Option.
OptionArgument
// Argument indicates that the last element is a non-option argument. The
// partial argument is stored in Context.Text.
Argument
)
// Parse parses an argument list. It returns the parsed options, the non-option
// arguments, and any error.
func Parse(args []string, specs []*OptionSpec, cfg Config) ([]*Option, []string, error) {
opts, nonOptArgs, opt, _ := parse(args, specs, cfg)
var err error
if opt != nil {
err = fmt.Errorf("missing argument for %s", optionPart(opt))
}
for _, opt := range opts {
if opt.Unknown {
err = diag.Errors(err, fmt.Errorf("unknown option %s", optionPart(opt)))
}
}
return opts, nonOptArgs, err
}
func optionPart(opt *Option) string {
if opt.Long {
return "--" + opt.Spec.Long
}
return "-" + string(opt.Spec.Short)
}
// Complete parses an argument list for completion. It returns the parsed
// options, the non-option arguments, and the context of the last argument. It
// tolerates unknown options, assuming that they take optional arguments.
func Complete(args []string, specs []*OptionSpec, cfg Config) ([]*Option, []string, Context) {
opts, nonOptArgs, opt, stopOpt := parse(args[:len(args)-1], specs, cfg)
arg := args[len(args)-1]
var ctx Context
switch {
case opt != nil:
opt.Argument = arg
ctx = Context{Type: OptionArgument, Option: opt}
case stopOpt:
ctx = Context{Type: Argument, Text: arg}
case arg == "":
ctx = Context{Type: OptionOrArgument}
case arg == "-":
ctx = Context{Type: AnyOption}
case strings.HasPrefix(arg, "--"):
if !strings.ContainsRune(arg, '=') {
ctx = Context{Type: LongOption, Text: arg[2:]}
} else {
newopt, _ := parseLong(arg[2:], specs)
ctx = Context{Type: OptionArgument, Option: newopt}
}
case strings.HasPrefix(arg, "-"):
if cfg.has(LongOnly) {
if !strings.ContainsRune(arg, '=') {
ctx = Context{Type: LongOption, Text: arg[1:]}
} else {
newopt, _ := parseLong(arg[1:], specs)
ctx = Context{Type: OptionArgument, Option: newopt}
}
} else {
newopts, _ := parseShort(arg[1:], specs)
if newopts[len(newopts)-1].Spec.Arity == NoArgument {
opts = append(opts, newopts...)
ctx = Context{Type: ChainShortOption}
} else {
opts = append(opts, newopts[:len(newopts)-1]...)
ctx = Context{Type: OptionArgument, Option: newopts[len(newopts)-1]}
}
}
default:
ctx = Context{Type: Argument, Text: arg}
}
return opts, nonOptArgs, ctx
}
func parse(args []string, spec []*OptionSpec, cfg Config) ([]*Option, []string, *Option, bool) {
var (
opts []*Option
nonOptArgs []string
// Non-nil only when the last argument was an option with required
// argument, but the argument has not been seen.
opt *Option
// Whether option parsing has been stopped. The condition is controlled
// by the StopAfterDoubleDash and StopBeforeFirstNonOption bits in cfg.
stopOpt bool
)
for _, arg := range args {
switch {
case opt != nil:
opt.Argument = arg
opts = append(opts, opt)
opt = nil
case stopOpt:
nonOptArgs = append(nonOptArgs, arg)
case cfg.has(StopAfterDoubleDash) && arg == "--":
stopOpt = true
case strings.HasPrefix(arg, "--") && arg != "--":
newopt, needArg := parseLong(arg[2:], spec)
if needArg {
opt = newopt
} else {
opts = append(opts, newopt)
}
case strings.HasPrefix(arg, "-") && arg != "--" && arg != "-":
if cfg.has(LongOnly) {
newopt, needArg := parseLong(arg[1:], spec)
if needArg {
opt = newopt
} else {
opts = append(opts, newopt)
}
} else {
newopts, needArg := parseShort(arg[1:], spec)
if needArg {
opts = append(opts, newopts[:len(newopts)-1]...)
opt = newopts[len(newopts)-1]
} else {
opts = append(opts, newopts...)
}
}
default:
nonOptArgs = append(nonOptArgs, arg)
if cfg.has(StopBeforeFirstNonOption) {
stopOpt = true
}
}
}
return opts, nonOptArgs, opt, stopOpt
}
// Parses short options, without the leading dash. Returns the parsed options
// and whether an argument is still to be seen.
func parseShort(s string, specs []*OptionSpec) ([]*Option, bool) {
var opts []*Option
var needArg bool
for i, r := range s {
opt := findShort(r, specs)
if opt != nil {
if opt.Arity == NoArgument {
opts = append(opts, &Option{Spec: opt})
continue
} else {
parsed := &Option{Spec: opt, Argument: s[i+len(string(r)):]}
opts = append(opts, parsed)
needArg = parsed.Argument == "" && opt.Arity == RequiredArgument
break
}
}
// Unknown option, treat as taking an optional argument
parsed := &Option{
Spec: &OptionSpec{r, "", OptionalArgument}, Unknown: true,
Argument: s[i+len(string(r)):]}
opts = append(opts, parsed)
break
}
return opts, needArg
}
func findShort(r rune, specs []*OptionSpec) *OptionSpec {
for _, opt := range specs {
if r == opt.Short {
return opt
}
}
return nil
}
// Parses a long option, without the leading dashes. Returns the parsed option
// and whether an argument is still to be seen.
func parseLong(s string, specs []*OptionSpec) (*Option, bool) {
eq := strings.IndexRune(s, '=')
for _, opt := range specs {
if s == opt.Long {
return &Option{Spec: opt, Long: true}, opt.Arity == RequiredArgument
} else if eq != -1 && s[:eq] == opt.Long {
return &Option{Spec: opt, Long: true, Argument: s[eq+1:]}, false
}
}
// Unknown option, treat as taking an optional argument
if eq == -1 {
return &Option{
Spec: &OptionSpec{0, s, OptionalArgument}, Unknown: true, Long: true}, false
}
return &Option{
Spec: &OptionSpec{0, s[:eq], OptionalArgument}, Unknown: true,
Long: true, Argument: s[eq+1:]}, false
}