/
parse.go
293 lines (262 loc) · 6.79 KB
/
parse.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
// Copyright (C) 2023-2024 Takayuki Sato. All Rights Reserved.
// This program is free software under MIT License.
// See the file LICENSE in this distribution for more details.
package cliargs
import (
"fmt"
"os"
"path"
"strings"
"unicode"
)
// InvalidOption is the error interface which provides method declarations
// to retrieve an option that caused this error and an error message.
type InvalidOption interface {
GetOpt() string
Error() string
}
// OptionHasInvalidChar is the error which indicates that an invalid character
// is found in the option.
type OptionHasInvalidChar struct{ Option string }
// Error is the method to retrieve the message of this error.
func (e OptionHasInvalidChar) Error() string {
return fmt.Sprintf("OptionHasInvalidChar{Option:%s}", e.Option)
}
// GetOpt is the method to retrieve the option that caused this error.
func (e OptionHasInvalidChar) GetOpt() string {
return e.Option
}
var (
empty = make([]string, 0)
rangeOfAlphabets = &unicode.RangeTable{
R16: []unicode.Range16{
{0x0041, 0x005a, 1}, // A-Z
{0x0061, 0x007a, 1}, // a-z
},
}
rangeOfAlNumMarks = &unicode.RangeTable{
R16: []unicode.Range16{
{0x002d, 0x002d, 1}, // -
{0x0030, 0x0039, 1}, // 0-9
{0x0041, 0x005a, 1}, // A-Z
{0x0061, 0x007a, 1}, // a-z
},
}
)
// Cmd is the structure which contains a command name, command arguments, and
// option arguments that are parsed from command line arguments without
// configurations.
// And this provides methods to check if they are specified and to obtain them.
type Cmd struct {
Name string
args []string
opts map[string][]string
}
// HasOpt is the method which checks if the option is specified in command line
// arguments.
func (cmd Cmd) HasOpt(name string) bool {
_, exists := cmd.opts[name]
return exists
}
// OptArg is the method to get the first option argument of the specified named
// option.
func (cmd Cmd) OptArg(name string) string {
arr := cmd.opts[name]
// If no entry, map returns a nil slice.
// If a value of a found entry is an empty slice.
// Both returned values are zero length in common.
if len(arr) == 0 {
return ""
} else {
return arr[0]
}
}
// OptArgs is the method to get the option arguments which are all specified
// with name in command line arguments.
func (cmd Cmd) OptArgs(name string) []string {
return cmd.opts[name]
}
// Args is the method to get command arguments which are specified in command
// line arguments and are not associated with any options.
func (cmd Cmd) Args() []string {
return cmd.args
}
// Parse is the function to parse command line arguments without
// configurations.
// This function divides command line arguments to command arguments, which
// are not associated with any options, and options, of which each has a name
// and option arguments.
// If an option appears multiple times in command line arguments, the option
// has multiple option arguments.
// Options are divided to long format options and short format options.
//
// A long format option starts with "--" and follows multiple characters which
// consists of alphabets, numbers, and '-'.
// (A character immediately after the heading "--" allows only an alphabet.)
// A long format option can be followed by "=" and its option argument.
//
// A short format option starts with "-" and follows single character which is
// an alphabet.
// Multiple short options can be combined into one argument.
// (For example -a -b -c can be combined into -abc.)
// Moreover, a short option can be followed by "=" and its option argument.
// In case of combined short options, only the last short option can take an
// option argument.
// (For example, -abc=3 is equal to -a -b -c=3.)
func Parse() (Cmd, error) {
var args = make([]string, 0)
var opts = make(map[string][]string)
var collectArgs = func(a ...string) {
args = append(args, a...)
}
var collectOpts = func(name string, a ...string) error {
arr, exists := opts[name]
if !exists {
arr = empty
}
opts[name] = append(arr, a...)
return nil
}
var cmdName string
if len(os.Args) > 0 {
cmdName = path.Base(os.Args[0])
}
var osArgs1 []string
if len(os.Args) > 1 {
osArgs1 = os.Args[1:]
}
err := parseArgs(osArgs1, collectArgs, collectOpts, _false)
return Cmd{Name: cmdName, args: args, opts: opts}, err
}
func _false(_ string) bool {
return false
}
func parseArgs(
osArgs []string,
collectArgs func(...string),
collectOpts func(string, ...string) error,
takeArgs func(string) bool,
) error {
isNonOpt := false
prevOptTakingArgs := ""
var firstErr error = nil
L0:
for iArg, arg := range osArgs {
if isNonOpt {
collectArgs(arg)
} else if len(prevOptTakingArgs) > 0 {
err := collectOpts(prevOptTakingArgs, arg)
if err != nil {
if firstErr == nil {
firstErr = err
}
continue L0
}
prevOptTakingArgs = ""
} else if strings.HasPrefix(arg, "--") {
if len(arg) == 2 {
isNonOpt = true
continue L0
}
arg = arg[2:]
i := 0
for _, r := range arg {
if i > 0 {
if r == '=' {
err := collectOpts(arg[0:i], arg[i+1:])
if err != nil {
if firstErr == nil {
firstErr = err
}
continue L0
}
break
}
if !unicode.Is(rangeOfAlNumMarks, r) {
if firstErr == nil {
firstErr = OptionHasInvalidChar{Option: arg}
}
continue L0
}
} else {
if !unicode.Is(rangeOfAlphabets, r) {
if firstErr == nil {
firstErr = OptionHasInvalidChar{Option: arg}
}
continue L0
}
}
i++
}
if i == len(arg) {
if takeArgs(arg) && iArg < len(osArgs)-1 {
prevOptTakingArgs = arg
continue L0
}
err := collectOpts(arg)
if err != nil {
if firstErr == nil {
firstErr = err
}
continue L0
}
}
} else if strings.HasPrefix(arg, "-") {
if len(arg) == 1 {
collectArgs(arg)
continue L0
}
arg := arg[1:]
var name string
i := 0
for _, r := range arg {
if i > 0 {
if r == '=' {
if len(name) > 0 {
err := collectOpts(name, arg[i+1:])
if err != nil {
if firstErr == nil {
firstErr = err
}
}
}
continue L0
}
if len(name) > 0 {
err := collectOpts(name)
if err != nil {
if firstErr == nil {
firstErr = err
}
}
}
}
if !unicode.Is(rangeOfAlphabets, r) {
if firstErr == nil {
firstErr = OptionHasInvalidChar{Option: string(r)}
}
name = ""
} else {
name = string(r)
}
i++
}
if i == len(arg) && len(name) > 0 {
if takeArgs(name) && iArg < len(osArgs)-1 {
prevOptTakingArgs = name
} else {
err := collectOpts(name)
if err != nil {
if firstErr == nil {
firstErr = err
}
continue L0
}
}
}
} else {
collectArgs(arg)
}
}
return firstErr
}