Debian Codegraph @

docs/v3/examples/flags/advanced.md

raw symbols SCIP
1 ---
2 tags:
3 - v3
4 search:
5 boost: 2
6 ---
7
8 #### Alternate Names
9
10 You can set alternate (or short) names for flags by providing a list of strings for `Aliases`
11 e.g.
12
13 <!-- {
14 "args": ["&#45;&#45;help"],
15 "output": "&#45;&#45;lang string, &#45;l string.*language for the greeting.*default: \"english\""
16 } -->
17 ```go
18 package main
19
20 import (
21 "log"
22 "os"
23 "context"
24
25 "github.com/urfave/cli/v3"
26 )
27
28 func main() {
29 cmd := &cli.Command{
30 Flags: []cli.Flag{
31 &cli.StringFlag{
32 Name: "lang",
33 Aliases: []string{"l"},
34 Value: "english",
35 Usage: "language for the greeting",
36 },
37 },
38 }
39
40 if err := cmd.Run(context.Background(), os.Args); err != nil {
41 log.Fatal(err)
42 }
43 }
44 ```
45
46 That flag can then be set with `--lang spanish` or `-l spanish`. Note that
47 giving two different forms of the same flag in the same command invocation is an
48 error.
49
50 #### Multiple Values per Single Flag
51
52 As noted in the basics for flag, the simple flags allow only one value per flag and only the last
53 entered value on command line will be returned to user on query.
54
55 `urfave/cli` also supports multi-value flags called slice flags. These flags can take multiple values of same type.
56 In addition they can be invoked multiple times on the command line and values will be appended to original value
57 of the flag and returned to the user as a slice
58
59 - `IntSliceFlag`
60 - `Int8SliceFlag`
61 - `Int16SliceFlag`
62 - `Int32SliceFlag`
63 - `Int64SliceFlag`
64 - `UintSliceFlag`
65 - `Uint8SliceFlag`
66 - `Uint16SliceFlag`
67 - `Uint32SliceFlag`
68 - `Uint64SliceFlag`
69 - `StringSliceFlag`
70 - `FloatSliceFlag`
71
72 <!-- {
73 "args": ["&#45;&#45;greeting", "Hello", "&#45;&#45;greeting", "Hola"],
74 "output": "Hello, Hola"
75 } -->
76 ```go
77 package main
78
79 import (
80 "fmt"
81 "log"
82 "os"
83 "strings"
84 "context"
85
86 "github.com/urfave/cli/v3"
87 )
88
89 func main() {
90 cmd := &cli.Command{
91 Flags: []cli.Flag{
92 &cli.StringSliceFlag{
93 Name: "greeting",
94 Usage: "Pass multiple greetings",
95 },
96 },
97 Action: func(ctx context.Context, cmd *cli.Command) error {
98 fmt.Println(strings.Join(cmd.StringSlice("greeting"), `, `))
99 return nil
100 },
101 }
102
103 if err := cmd.Run(context.Background(), os.Args); err != nil {
104 log.Fatal(err)
105 }
106 }
107 ```
108
109 Multiple values need to be passed as separate, repeating flags, e.g. `--greeting Hello --greeting Hola`.
110
111 #### Count for bool flag
112
113 For bool flags you can specify the flag multiple times to get a count(e.g -v -v -v or -vvv)
114
115 > If you want to support the `-vvv` flag, you need to set `Command.UseShortOptionHandling`.
116
117 <!-- {
118 "args": ["&#45;&#45;foo", "&#45;&#45;foo", "&#45;fff"],
119 "output": "count 5"
120 } -->
121 ```go
122 package main
123
124 import (
125 "fmt"
126 "log"
127 "os"
128 "context"
129
130 "github.com/urfave/cli/v3"
131 )
132
133 func main() {
134 var count int
135
136 cmd := &cli.Command{
137 UseShortOptionHandling: true,
138 Flags: []cli.Flag{
139 &cli.BoolFlag{
140 Name: "foo",
141 Usage: "foo greeting",
142 Aliases: []string{"f"},
143 Config: cli.BoolConfig{
144 Count: &count,
145 },
146 },
147 },
148 Action: func(ctx context.Context, cmd *cli.Command) error {
149 fmt.Println("count", count)
150 return nil
151 },
152 }
153
154 if err := cmd.Run(context.Background(), os.Args); err != nil {
155 log.Fatal(err)
156 }
157 }
158 ```
159
160 #### Placeholder Values
161
162 Sometimes it's useful to specify a flag's value within the usage string itself.
163 Such placeholders are indicated with back quotes.
164
165 For example this:
166
167 <!-- {
168 "args": ["&#45;&#45;help"],
169 "output": "&#45;&#45;config FILE, &#45;c FILE"
170 } -->
171 ```go
172 package main
173
174 import (
175 "log"
176 "os"
177 "context"
178
179 "github.com/urfave/cli/v3"
180 )
181
182 func main() {
183 cmd := &cli.Command{
184 Flags: []cli.Flag{
185 &cli.StringFlag{
186 Name: "config",
187 Aliases: []string{"c"},
188 Usage: "Load configuration from `FILE`",
189 },
190 },
191 }
192
193 if err := cmd.Run(context.Background(), os.Args); err != nil {
194 log.Fatal(err)
195 }
196 }
197 ```
198
199 Will result in help output like:
200
201 ```
202 --config FILE, -c FILE Load configuration from FILE
203 ```
204
205 Note that only the first placeholder is used. Subsequent back-quoted words will
206 be left as-is.
207
208
209 #### Ordering
210
211 Flags for the application and commands are shown in the order they are defined.
212 However, it's possible to sort them from outside this library by using `FlagsByName`
213 or `CommandsByName` with `sort`.
214
215 For example this:
216
217 <!-- {
218 "args": ["&#45;&#45;help"],
219 "output": ".*Load configuration from FILE\n.*Language for the greeting.*"
220 } -->
221 ```go
222 package main
223
224 import (
225 "log"
226 "os"
227 "sort"
228 "context"
229
230 "github.com/urfave/cli/v3"
231 )
232
233 func main() {
234 cmd := &cli.Command{
235 Flags: []cli.Flag{
236 &cli.StringFlag{
237 Name: "lang",
238 Aliases: []string{"l"},
239 Value: "english",
240 Usage: "Language for the greeting",
241 },
242 &cli.StringFlag{
243 Name: "config",
244 Aliases: []string{"c"},
245 Usage: "Load configuration from `FILE`",
246 },
247 },
248 Commands: []*cli.Command{
249 {
250 Name: "complete",
251 Aliases: []string{"c"},
252 Usage: "complete a task on the list",
253 Action: func(ctx context.Context, cmd *cli.Command) error {
254 return nil
255 },
256 },
257 {
258 Name: "add",
259 Aliases: []string{"a"},
260 Usage: "add a task to the list",
261 Action: func(ctx context.Context, cmd *cli.Command) error {
262 return nil
263 },
264 },
265 },
266 }
267
268 sort.Sort(cli.FlagsByName(cmd.Flags))
269
270 if err := cmd.Run(context.Background(), os.Args); err != nil {
271 log.Fatal(err)
272 }
273 }
274 ```
275
276 Will result in help output like:
277
278 ```
279 --config FILE, -c FILE Load configuration from FILE
280 --lang value, -l value Language for the greeting (default: "english")
281 ```
282
283 #### Required Flags
284
285 You can mark a flag as *required* by setting the `Required` field to `true`. If a user
286 does not provide a required flag, they will be shown an error message.
287
288 Take for example this app that requires the `lang` flag:
289
290 <!-- {
291 "error": "Required flag \"lang\" not set"
292 } -->
293 ```go
294 package main
295
296 import (
297 "fmt"
298 "log"
299 "os"
300 "context"
301
302 "github.com/urfave/cli/v3"
303 )
304
305 func main() {
306 cmd := &cli.Command{
307 Flags: []cli.Flag{
308 &cli.StringFlag{
309 Name: "lang",
310 Value: "english",
311 Usage: "language for the greeting",
312 Required: true,
313 },
314 },
315 Action: func(ctx context.Context, cmd *cli.Command) error {
316 output := "Hello"
317 if cmd.String("lang") == "spanish" {
318 output = "Hola"
319 }
320 fmt.Println(output)
321 return nil
322 },
323 }
324
325 if err := cmd.Run(context.Background(), os.Args); err != nil {
326 log.Fatal(err)
327 }
328 }
329 ```
330
331 If the command is run without the `lang` flag, the user will see the following message
332
333 ```
334 Required flag "lang" not set
335 ```
336
337 #### Flag Groups
338
339 You can make groups of flags that are mutually exclusive of each other.
340 This provides the ability to provide configuration options out of which
341 only one can be defined on the command line.
342
343 Take for example this app that looks up a user using one of multiple options:
344
345 <!-- {
346 "error": "one of these flags needs to be provided: login, id"
347 } -->
348 ```go
349 package main
350
351 import (
352 "context"
353 "encoding/json"
354 "fmt"
355 "log"
356 "os"
357
358 "github.com/urfave/cli/v3"
359 )
360
361 func main() {
362 cmd := &cli.Command{
363 Name: "authors",
364 MutuallyExclusiveFlags: []cli.MutuallyExclusiveFlags{
365 {
366 Required: true,
367 Flags: [][]cli.Flag{
368 {
369 &cli.StringFlag{
370 Name: "login",
371 Usage: "the username of the user",
372 },
373 },
374 {
375 &cli.StringFlag{
376 Name: "id",
377 Usage: "the user id (defaults to 'me' for current user)",
378 },
379 },
380 },
381 },
382 },
383 Action: func(ctx context.Context, cmd *cli.Command) error {
384 u, err := getUser(ctx, cmd)
385 if err != nil {
386 return err
387 }
388 data, err := json.Marshal(u)
389 if err != nil {
390 return err
391 }
392 fmt.Println(string(data))
393 return nil
394 },
395 }
396
397 if err := cmd.Run(context.Background(), os.Args); err != nil {
398 log.Fatal(err)
399 }
400 }
401
402 type User struct {
403 Id string `json:"id"`
404 Login string `json:"login"`
405 FirstName string `json:"firstName"`
406 LastName string `json:"lastName"`
407 }
408
409 // Mock function that returns a static user value.
410 // Would retrieve a user from an API or database with other functions.
411 func getUser(ctx context.Context, cmd *cli.Command) (User, error) {
412 u := User{
413 Id: "abc123",
414 Login: "[email protected]",
415 FirstName: "Virginia",
416 LastName: "Woolf",
417 }
418 if login := cmd.String("login"); login != "" {
419 fmt.Printf("Getting user by login: %s\n", login)
420 u.Login = login
421 }
422 if id := cmd.String("id"); id != "" {
423 fmt.Printf("Getting user by id: %s\n", id)
424 u.Id = id
425 }
426 return u, nil
427 }
428 ```
429
430 If the command is run without either the `login` or `id` flag, the user will
431 see the following message
432
433 ```
434 one of these flags needs to be provided: login, id
435 ```
436
437
438 #### Default Values for help output
439
440 Sometimes it's useful to specify a flag's default help-text value within the
441 flag declaration. This can be useful if the default value for a flag is a
442 computed value. The default value can be set via the `DefaultText` struct field.
443
444 For example this:
445
446 <!-- {
447 "args": ["&#45;&#45;help"],
448 "output": "&#45;&#45;port int"
449 } -->
450 ```go
451 package main
452
453 import (
454 "log"
455 "os"
456 "context"
457
458 "github.com/urfave/cli/v3"
459 )
460
461 func main() {
462 cmd := &cli.Command{
463 Flags: []cli.Flag{
464 &cli.IntFlag{
465 Name: "port",
466 Usage: "Use a randomized port",
467 Value: 0,
468 DefaultText: "random",
469 },
470 },
471 }
472
473 if err := cmd.Run(context.Background(), os.Args); err != nil {
474 log.Fatal(err)
475 }
476 }
477 ```
478
479 Will result in help output like:
480
481 ```
482 --port value Use a randomized port (default: random)
483 ```
484
485 #### Flag Actions
486
487 Handlers can be registered per flag which are triggered after a flag has been processed.
488 This can be used for a variety of purposes, one of which is flag validation
489
490 <!-- {
491 "args": ["&#45;&#45;port","70000"],
492 "error": "Flag port value 70000 out of range[0-65535]"
493 } -->
494 ```go
495 package main
496
497 import (
498 "log"
499 "os"
500 "fmt"
501 "context"
502
503 "github.com/urfave/cli/v3"
504 )
505
506 func main() {
507 cmd := &cli.Command{
508 Flags: []cli.Flag{
509 &cli.IntFlag{
510 Name: "port",
511 Usage: "Use a randomized port",
512 Value: 0,
513 DefaultText: "random",
514 Action: func(ctx context.Context, cmd *cli.Command, v int) error {
515 if v >= 65536 {
516 return fmt.Errorf("Flag port value %v out of range[0-65535]", v)
517 }
518 return nil
519 },
520 },
521 },
522 }
523
524 if err := cmd.Run(context.Background(), os.Args); err != nil {
525 log.Fatal(err)
526 }
527 }
528 ```
529
530 Will result in help output like:
531
532 ```
533 Flag port value 70000 out of range[0-65535]
534 ```