forked from jessevdk/go-flags
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser_private.go
98 lines (80 loc) · 2.25 KB
/
parser_private.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
package flags
import (
"fmt"
"unicode/utf8"
)
func (p *Parser) removeGroup(group *Group) {
for i, grp := range p.Groups {
if grp == group {
p.Groups = append(p.Groups[:i], p.Groups[i+1:]...)
break
}
}
}
func (p *Parser) parseOption(group *Group, args []string, name string, option *Option, canarg bool, argument *string, index int) (error, int) {
var err error
if !option.canArgument() {
if canarg && argument != nil {
return newError(ErrNoArgumentForBool,
fmt.Sprintf("bool flag `%s' cannot have an argument", option)),
index
}
err = option.Set(nil)
} else if canarg && (argument != nil || index < len(args)) {
if argument == nil {
argument = &args[index]
index++
}
err = option.Set(argument)
} else if option.OptionalArgument {
err = option.Set(&option.Default)
} else {
return newError(ErrExpectedArgument,
fmt.Sprintf("expected argument for flag `%s'", option)),
index
}
if err != nil {
if _, ok := err.(*Error); !ok {
err = newError(ErrMarshal,
fmt.Sprintf("invalid argument for flag `%s' (expected %s)",
option,
option.value.Type()))
}
}
return err, index
}
func (p *Parser) parseLong(args []string, name string, argument *string, index int) (error, int) {
for _, grp := range p.Groups {
if option := grp.LongNames[name]; option != nil {
return p.parseOption(grp, args, name, option, true, argument, index)
}
}
return newError(ErrUnknownFlag,
fmt.Sprintf("unknown flag `%s'", name)),
index
}
func (p *Parser) getShort(name rune) (*Option, *Group) {
for _, grp := range p.Groups {
option := grp.ShortNames[name]
if option != nil {
return option, grp
}
}
return nil, nil
}
func (p *Parser) parseShort(args []string, name rune, islast bool, argument *string, index int) (error, int) {
names := make([]byte, utf8.RuneLen(name))
utf8.EncodeRune(names, name)
option, grp := p.getShort(name)
if option != nil {
if option.canArgument() && !islast && !option.OptionalArgument {
return newError(ErrExpectedArgument,
fmt.Sprintf("expected argument for flag `%s'", option)),
index
}
return p.parseOption(grp, args, string(names), option, islast, argument, index)
}
return newError(ErrUnknownFlag,
fmt.Sprintf("unknown flag `%s'", string(names))),
index
}