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
|
package opts
type ArgMode int
const (
None ArgMode = iota
Required
Optional
)
type Flag struct {
Key rune
Value string
}
type LongOpt struct {
Short rune
Long string
Arg ArgMode
}
func Get(args []string, optstr string) (flags []Flag, optind int, err error) {
argmap := make(map[rune]bool)
rs := []rune(optstr)
for i, r := range rs {
if r != ':' {
argmap[r] = false
} else if i > 0 {
argmap[rs[i-1]] = true
}
}
for i := 1; i < len(args); i++ {
arg := args[i]
if len(arg) == 0 || arg == "-" || arg[0] != '-' {
optind = i
return
} else if arg == "--" {
optind = i + 1
return
}
rs := []rune(arg[1:])
for j, r := range rs {
var s string
argp, ok := argmap[r]
switch {
case !ok:
return nil, 0, ErrBadOption(r)
case argp && j < len(rs)-1:
s = string(rs[j+1:])
case argp:
i++
if i >= len(args) {
return nil, 0, ErrNoArgument(r)
}
s = args[i]
default:
flags = append(flags, Flag{Key: r})
continue
}
flags = append(flags, Flag{r, s})
break
}
}
optind = len(args)
return
}
|