-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflag.go
More file actions
97 lines (76 loc) · 2.08 KB
/
flag.go
File metadata and controls
97 lines (76 loc) · 2.08 KB
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
package cli
import (
"fmt"
"github.com/bobg/errors"
"github.com/broothie/option"
"github.com/samber/lo"
)
const helpFlagName = "help"
type Flag struct {
name string
description string
aliases []string
shorts []rune
isHelp bool
isVersion bool
isHidden bool
isInherited bool
parser argParser
defaultEnvName string
defaultValue any
value any
}
func newFlag(name, description string, options ...option.Option[*Flag]) (*Flag, error) {
baseFlag := &Flag{
name: name,
description: description,
parser: NewArgParser(StringParser),
defaultValue: "",
}
flag, err := option.Apply(baseFlag, options...)
if err != nil {
return nil, errors.Wrapf(err, "building flag %q", name)
}
if err := flag.validateConfig(); err != nil {
return nil, errors.Wrapf(err, "invalid flag %q", name)
}
return flag, nil
}
func (f *Flag) isBool() bool {
return isBoolParser(f.parser)
}
func (c *Command) findFlag(name string) (*Flag, bool) {
return c.findFlagUpToRoot(func(flag *Flag) bool { return flag.name == name })
}
func (c *Command) findFlagUpToRoot(predicate func(*Flag) bool) (*Flag, bool) {
for current := c; current != nil; current = current.parent {
currentIsSelf := current == c
flags := current.flags
if !currentIsSelf {
flags = lo.Filter(flags, func(flag *Flag, _ int) bool { return flag.isInherited })
}
flag, found := lo.Find(flags, predicate)
if found {
return flag, true
}
}
return nil, false
}
func (c *Command) flagsUpToRoot() []*Flag {
flags := c.flags
flagSet := lo.Associate(flags, func(flag *Flag) (string, bool) { return flag.name, true })
for current := c.parent; current != nil; current = current.parent {
flags = append(flags, lo.Filter(current.flags, func(flag *Flag, _ int) bool {
defer func() { flagSet[flag.name] = true }()
return flag.isInherited && !flagSet[flag.name]
})...)
}
return flags
}
func dashifyShort(short rune) string {
return fmt.Sprintf("-%c", short)
}
func isBoolParser(parser argParser) bool {
_, isBool := parser.Type().(bool)
return isBool
}