Debian Codegraph @

flag.go

raw symbols SCIP
1 package cli
2
3 import (
4 "context"
5 "fmt"
6 "slices"
7 "strings"
8 "time"
9 )
10
11 const defaultPlaceholder = "value"
12
13 const (
14 defaultSliceFlagSeparator = ","
15 defaultMapFlagKeyValueSeparator = "="
16 disableSliceFlagSeparator = false
17 )
18
19 var slPfx = fmt.Sprintf("sl:::%d:::", time.Now().UTC().UnixNano())
20
21 // GenerateShellCompletionFlag enables shell completion
22 var GenerateShellCompletionFlag Flag = &BoolFlag{
23 Name: "generate-shell-completion",
24 Hidden: true,
25 }
26
27 // VersionFlag prints the version for the application
28 var VersionFlag Flag = &BoolFlag{
29 Name: "version",
30 Aliases: []string{"v"},
31 Usage: "print the version",
32 HideDefault: true,
33 Local: true,
34 }
35
36 // HelpFlag prints the help for all commands and subcommands.
37 // Set to nil to disable the flag. The subcommand
38 // will still be added unless HideHelp or HideHelpCommand is set to true.
39 var HelpFlag Flag = &BoolFlag{
40 Name: "help",
41 Aliases: []string{"h"},
42 Usage: "show help",
43 HideDefault: true,
44 Local: true,
45 }
46
47 // FlagStringer converts a flag definition to a string. This is used by help
48 // to display a flag.
49 var FlagStringer FlagStringFunc = stringifyFlag
50
51 // Serializer is used to circumvent the limitations of flag.FlagSet.Set
52 type Serializer interface {
53 Serialize() string
54 }
55
56 // FlagNamePrefixer converts a full flag name and its placeholder into the help
57 // message flag prefix. This is used by the default FlagStringer.
58 var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames
59
60 // FlagEnvHinter annotates flag help message with the environment variable
61 // details. This is used by the default FlagStringer.
62 var FlagEnvHinter FlagEnvHintFunc = withEnvHint
63
64 // FlagFileHinter annotates flag help message with the environment variable
65 // details. This is used by the default FlagStringer.
66 var FlagFileHinter FlagFileHintFunc = withFileHint
67
68 // FlagsByName is a slice of Flag.
69 type FlagsByName []Flag
70
71 func (f FlagsByName) Len() int {
72 return len(f)
73 }
74
75 func (f FlagsByName) Less(i, j int) bool {
76 return lexicographicLess(f[i].Names()[0], f[j].Names()[0])
77 }
78
79 func (f FlagsByName) Swap(i, j int) {
80 f[i], f[j] = f[j], f[i]
81 }
82
83 // ActionableFlag is an interface that wraps Flag interface and RunAction operation.
84 type ActionableFlag interface {
85 RunAction(context.Context, *Command) error
86 }
87
88 // Flag is a common interface related to parsing flags in cli.
89 // For more advanced flag parsing techniques, it is recommended that
90 // this interface be implemented.
91 type Flag interface {
92 fmt.Stringer
93
94 // Retrieve the value of the Flag
95 Get() any
96
97 // Lifecycle methods.
98 // flag callback prior to parsing
99 PreParse() error
100
101 // flag callback post parsing
102 PostParse() error
103
104 // Apply Flag settings to the given flag set
105 Set(string, string) error
106
107 // All possible names for this flag
108 Names() []string
109
110 // Whether the flag has been set or not
111 IsSet() bool
112 }
113
114 // RequiredFlag is an interface that allows us to mark flags as required
115 // it allows flags required flags to be backwards compatible with the Flag interface
116 type RequiredFlag interface {
117 // whether the flag is a required flag or not
118 IsRequired() bool
119 }
120
121 // DocGenerationFlag is an interface that allows documentation generation for the flag
122 type DocGenerationFlag interface {
123 // TakesValue returns true if the flag takes a value, otherwise false
124 TakesValue() bool
125
126 // GetUsage returns the usage string for the flag
127 GetUsage() string
128
129 // GetValue returns the flags value as string representation and an empty
130 // string if the flag takes no value at all.
131 GetValue() string
132
133 // GetDefaultText returns the default text for this flag
134 GetDefaultText() string
135
136 // GetEnvVars returns the env vars for this flag
137 GetEnvVars() []string
138
139 // IsDefaultVisible returns whether the default value should be shown in
140 // help text
141 IsDefaultVisible() bool
142 // TypeName to detect if a flag is a string, bool, etc.
143 TypeName() string
144 }
145
146 // DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags.
147 type DocGenerationMultiValueFlag interface {
148 DocGenerationFlag
149
150 // IsMultiValueFlag returns true for flags that can be given multiple times.
151 IsMultiValueFlag() bool
152 }
153
154 // SchemaTyper is an optional interface for flags that can report their
155 // JSON Schema type for programmatic introspection.
156 type SchemaTyper interface {
157 // SchemaType returns the JSON Schema type name for the value this
158 // flag accepts: "boolean", "integer", "number", "string", "array",
159 // "object". Returns "" if the flag does not map cleanly.
160 SchemaType() string
161 }
162
163 // SchemaItemsTyper is an optional interface for multi-value flags that
164 // can report the JSON Schema type of their elements.
165 type SchemaItemsTyper interface {
166 // SchemaItemsType returns the JSON Schema type of elements for
167 // array-type flags. Returns "" for single-value or object flags.
168 SchemaItemsType() string
169 }
170
171 // Countable is an interface to enable detection of flag values which support
172 // repetitive flags
173 type Countable interface {
174 Count() int
175 }
176
177 // VisibleFlag is an interface that allows to check if a flag is visible
178 type VisibleFlag interface {
179 // IsVisible returns true if the flag is not hidden, otherwise false
180 IsVisible() bool
181 }
182
183 // CategorizableFlag is an interface that allows us to potentially
184 // use a flag in a categorized representation.
185 type CategorizableFlag interface {
186 // Returns the category of the flag
187 GetCategory() string
188
189 // Sets the category of the flag
190 SetCategory(string)
191 }
192
193 // LocalFlag is an interface to enable detection of flags which are local
194 // to current command
195 type LocalFlag interface {
196 IsLocal() bool
197 }
198
199 func visibleFlags(fl []Flag) []Flag {
200 var visible []Flag
201 for _, f := range fl {
202 if vf, ok := f.(VisibleFlag); ok && vf.IsVisible() {
203 visible = append(visible, f)
204 }
205 }
206 return visible
207 }
208
209 func FlagNames(name string, aliases []string) []string {
210 var ret []string
211
212 for _, part := range append([]string{name}, aliases...) {
213 // v1 -> v2 migration warning zone:
214 // Strip off anything after the first found comma or space, which
215 // *hopefully* makes it a tiny bit more obvious that unexpected behavior is
216 // caused by using the v1 form of stringly typed "Name".
217 if i := strings.IndexAny(part, ", "); i >= 0 {
218 ret = append(ret, part[:i])
219 } else {
220 ret = append(ret, part)
221 }
222 }
223
224 return ret
225 }
226
227 func hasFlag(flags []Flag, fl Flag) bool {
228 return slices.Contains(flags, fl)
229 }
230
231 func flagSplitMultiValues(val string, sliceSeparator string, disableSliceSeparator bool) []string {
232 if disableSliceSeparator {
233 return []string{val}
234 }
235
236 if len(sliceSeparator) == 0 {
237 sliceSeparator = defaultSliceFlagSeparator
238 }
239 return strings.Split(val, sliceSeparator)
240 }