Debian Codegraph @

examples_test.go

raw symbols SCIP
1 package cli_test
2
3 import (
4 "context"
5 "fmt"
6 "net/mail"
7 "os"
8 "time"
9
10 // Alias the package import to make the examples runnable on pkg.go.dev.
11 //
12 // See issue #1811.
13 cli "github.com/urfave/cli/v3"
14 )
15
16 func ExampleCommand_Run() {
17 // Declare a command
18 cmd := &cli.Command{
19 Name: "greet",
20 Flags: []cli.Flag{
21 &cli.StringFlag{Name: "name", Value: "pat", Usage: "a name to say"},
22 },
23 Action: func(_ context.Context, cmd *cli.Command) error {
24 fmt.Printf("Hello %[1]v\n", cmd.String("name"))
25 return nil
26 },
27 Authors: []any{
28 &mail.Address{Name: "Oliver Allen", Address: "[email protected]"},
29 "[email protected]",
30 },
31 Version: "v0.13.12",
32 }
33
34 // Simulate the command line arguments
35 os.Args = []string{"greet", "--name", "Jeremy"}
36
37 if err := cmd.Run(context.Background(), os.Args); err != nil {
38 // do something with unhandled errors
39 fmt.Fprintf(os.Stderr, "Unhandled error: %[1]v\n", err)
40 os.Exit(86)
41 }
42 // Output:
43 // Hello Jeremy
44 }
45
46 func ExampleCommand_Run_subcommand() {
47 cmd := &cli.Command{
48 Name: "say",
49 Commands: []*cli.Command{
50 {
51 Name: "hello",
52 Aliases: []string{"hi"},
53 Usage: "use it to see a description",
54 Description: "This is how we describe hello the function",
55 Commands: []*cli.Command{
56 {
57 Name: "english",
58 Aliases: []string{"en"},
59 Usage: "sends a greeting in english",
60 Description: "greets someone in english",
61 Flags: []cli.Flag{
62 &cli.StringFlag{
63 Name: "name",
64 Value: "Bob",
65 Usage: "Name of the person to greet",
66 },
67 },
68 Action: func(_ context.Context, cmd *cli.Command) error {
69 fmt.Println("Hello,", cmd.String("name"))
70 return nil
71 },
72 },
73 },
74 },
75 },
76 }
77
78 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
79 defer cancel()
80
81 // Simulate the command line arguments
82 os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
83
84 _ = cmd.Run(ctx, os.Args)
85 // Output:
86 // Hello, Jeremy
87 }
88
89 func ExampleCommand_Run_appHelp() {
90 cmd := &cli.Command{
91 Name: "greet",
92 Version: "0.1.0",
93 Description: "This is how we describe greet the app",
94 Authors: []any{
95 &mail.Address{Name: "Harrison", Address: "[email protected]"},
96 "Oliver Allen <[email protected]>",
97 },
98 Flags: []cli.Flag{
99 &cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
100 },
101 Arguments: cli.AnyArguments,
102 Commands: []*cli.Command{
103 {
104 Name: "describeit",
105 Aliases: []string{"d"},
106 Usage: "use it to see a description",
107 Description: "This is how we describe describeit the function",
108 ArgsUsage: "[arguments...]",
109 Action: func(context.Context, *cli.Command) error {
110 fmt.Printf("i like to describe things")
111 return nil
112 },
113 },
114 },
115 }
116
117 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
118 defer cancel()
119
120 // Simulate the command line arguments
121 os.Args = []string{"greet", "help"}
122
123 _ = cmd.Run(ctx, os.Args)
124 // Output:
125 // NAME:
126 // greet - A new cli application
127 //
128 // USAGE:
129 // greet [global options] [command [command options]] [arguments...]
130 //
131 // VERSION:
132 // 0.1.0
133 //
134 // DESCRIPTION:
135 // This is how we describe greet the app
136 //
137 // AUTHORS:
138 // "Harrison" <[email protected]>
139 // Oliver Allen <[email protected]>
140 //
141 // COMMANDS:
142 // describeit, d use it to see a description
143 // help, h Shows a list of commands or help for one command
144 //
145 // GLOBAL OPTIONS:
146 // --name string a name to say (default: "bob")
147 // --help, -h show help
148 // --version, -v print the version
149 }
150
151 func ExampleCommand_Run_commandHelp() {
152 cmd := &cli.Command{
153 Name: "greet",
154 Flags: []cli.Flag{
155 &cli.StringFlag{Name: "name", Value: "pat", Usage: "a name to say"},
156 },
157 Action: func(_ context.Context, cmd *cli.Command) error {
158 fmt.Fprintf(cmd.Root().Writer, "hello to %[1]q\n", cmd.String("name"))
159 return nil
160 },
161 Commands: []*cli.Command{
162 {
163 Name: "describeit",
164 Aliases: []string{"d"},
165 Usage: "use it to see a description",
166 Description: "This is how we describe describeit the function",
167 ArgsUsage: "[arguments...]",
168 Action: func(context.Context, *cli.Command) error {
169 fmt.Println("i like to describe things")
170 return nil
171 },
172 },
173 },
174 }
175
176 // Simulate the command line arguments
177 os.Args = []string{"greet", "h", "describeit"}
178
179 _ = cmd.Run(context.Background(), os.Args)
180 // Output:
181 // NAME:
182 // greet describeit - use it to see a description
183 //
184 // USAGE:
185 // greet describeit [options] [arguments...]
186 //
187 // DESCRIPTION:
188 // This is how we describe describeit the function
189 //
190 // OPTIONS:
191 // --help, -h show help
192 //
193 // GLOBAL OPTIONS:
194 // --name string a name to say (default: "pat")
195 }
196
197 func ExampleCommand_Run_noAction() {
198 cmd := &cli.Command{Name: "greet"}
199
200 // Simulate the command line arguments
201 os.Args = []string{"greet"}
202
203 _ = cmd.Run(context.Background(), os.Args)
204 // Output:
205 // NAME:
206 // greet - A new cli application
207 //
208 // USAGE:
209 // greet [global options]
210 //
211 // GLOBAL OPTIONS:
212 // --help, -h show help
213 }
214
215 func ExampleCommand_Run_subcommandNoAction() {
216 cmd := &cli.Command{
217 Name: "greet",
218 Commands: []*cli.Command{
219 {
220 Name: "describeit",
221 Aliases: []string{"d"},
222 Usage: "use it to see a description",
223 ArgsUsage: "[arguments...]",
224 Description: "This is how we describe describeit the function",
225 },
226 },
227 }
228
229 // Simulate the command line arguments
230 os.Args = []string{"greet", "describeit"}
231
232 _ = cmd.Run(context.Background(), os.Args)
233 // Output:
234 // NAME:
235 // greet describeit - use it to see a description
236 //
237 // USAGE:
238 // greet describeit [options] [arguments...]
239 //
240 // DESCRIPTION:
241 // This is how we describe describeit the function
242 //
243 // OPTIONS:
244 // --help, -h show help
245 }
246
247 func ExampleCommand_Run_shellComplete_bash_withShortFlag() {
248 cmd := &cli.Command{
249 Name: "greet",
250 EnableShellCompletion: true,
251 Flags: []cli.Flag{
252 &cli.Int64Flag{
253 Name: "other",
254 Aliases: []string{"o"},
255 },
256 &cli.StringFlag{
257 Name: "xyz",
258 Aliases: []string{"x"},
259 },
260 },
261 }
262
263 // Simulate a bash environment and command line arguments
264 os.Args = []string{"greet", "-", "--generate-shell-completion"}
265
266 _ = cmd.Run(context.Background(), os.Args)
267 // Output:
268 // --other
269 // --xyz
270 // --help:show help
271 }
272
273 func ExampleCommand_Run_shellComplete_bash_withLongFlag() {
274 cmd := &cli.Command{
275 Name: "greet",
276 EnableShellCompletion: true,
277 Flags: []cli.Flag{
278 &cli.Int64Flag{
279 Name: "other",
280 Aliases: []string{"o"},
281 },
282 &cli.StringFlag{
283 Name: "xyz",
284 Aliases: []string{"x"},
285 },
286 &cli.StringFlag{
287 Name: "some-flag,s",
288 },
289 &cli.StringFlag{
290 Name: "similar-flag",
291 },
292 },
293 }
294
295 // Simulate a bash environment and command line arguments
296 os.Args = []string{"greet", "--s", "--generate-shell-completion"}
297
298 _ = cmd.Run(context.Background(), os.Args)
299 // Output:
300 // --some-flag
301 // --similar-flag
302 }
303
304 func ExampleCommand_Run_shellComplete_bash_withMultipleLongFlag() {
305 cmd := &cli.Command{
306 Name: "greet",
307 EnableShellCompletion: true,
308 Flags: []cli.Flag{
309 &cli.Int64Flag{
310 Name: "int-flag",
311 Aliases: []string{"i"},
312 },
313 &cli.StringFlag{
314 Name: "string",
315 Aliases: []string{"s"},
316 },
317 &cli.StringFlag{
318 Name: "string-flag-2",
319 },
320 &cli.StringFlag{
321 Name: "similar-flag",
322 },
323 &cli.StringFlag{
324 Name: "some-flag",
325 },
326 },
327 }
328
329 // Simulate a bash environment and command line arguments
330 os.Args = []string{"greet", "--st", "--generate-shell-completion"}
331
332 _ = cmd.Run(context.Background(), os.Args)
333 // Output:
334 // --string
335 // --string-flag-2
336 }
337
338 func ExampleCommand_Run_shellComplete_bash() {
339 cmd := &cli.Command{
340 Name: "greet",
341 EnableShellCompletion: true,
342 Commands: []*cli.Command{
343 {
344 Name: "describeit",
345 Aliases: []string{"d"},
346 Usage: "use it to see a description",
347 Description: "This is how we describe describeit the function",
348 Action: func(context.Context, *cli.Command) error {
349 fmt.Printf("i like to describe things")
350 return nil
351 },
352 }, {
353 Name: "next",
354 Usage: "next example",
355 Description: "more stuff to see when generating shell completion",
356 Action: func(context.Context, *cli.Command) error {
357 fmt.Printf("the next example")
358 return nil
359 },
360 },
361 },
362 }
363
364 // Simulate a bash environment and command line arguments
365 os.Args = []string{"greet", "--generate-shell-completion"}
366
367 _ = cmd.Run(context.Background(), os.Args)
368 // Output:
369 // describeit:use it to see a description
370 // next:next example
371 // help:Shows a list of commands or help for one command
372 }
373
374 func ExampleCommand_Run_shellComplete_zsh() {
375 cmd := &cli.Command{
376 Name: "greet",
377 EnableShellCompletion: true,
378 Commands: []*cli.Command{
379 {
380 Name: "describeit",
381 Aliases: []string{"d"},
382 Usage: "use it to see a description",
383 Description: "This is how we describe describeit the function",
384 Action: func(context.Context, *cli.Command) error {
385 fmt.Printf("i like to describe things")
386 return nil
387 },
388 }, {
389 Name: "next",
390 Usage: "next example",
391 Description: "more stuff to see when generating bash completion",
392 Action: func(context.Context, *cli.Command) error {
393 fmt.Printf("the next example")
394 return nil
395 },
396 },
397 },
398 }
399
400 // Simulate a zsh environment and command line arguments
401 os.Args = []string{"greet", "--generate-shell-completion"}
402
403 _ = cmd.Run(context.Background(), os.Args)
404 // Output:
405 // describeit:use it to see a description
406 // next:next example
407 // help:Shows a list of commands or help for one command
408 }
409
410 func ExampleCommand_Run_shellComplete_fish() {
411 cmd := &cli.Command{
412 Name: "greet",
413 EnableShellCompletion: true,
414 Commands: []*cli.Command{
415 {
416 Name: "describeit",
417 Aliases: []string{"d"},
418 Usage: "use it to see a description",
419 Description: "This is how we describe describeit the function",
420 Action: func(context.Context, *cli.Command) error {
421 fmt.Printf("i like to describe things")
422 return nil
423 },
424 }, {
425 Name: "next",
426 Usage: "next example",
427 Description: "more stuff to see when generating bash completion",
428 Action: func(context.Context, *cli.Command) error {
429 fmt.Printf("the next example")
430 return nil
431 },
432 },
433 },
434 }
435
436 // Simulate a fish environment and command line arguments
437 os.Args = []string{"greet", "--generate-shell-completion"}
438
439 _ = cmd.Run(context.Background(), os.Args)
440 // Output:
441 // describeit:use it to see a description
442 // next:next example
443 // help:Shows a list of commands or help for one command
444 }
445
446 func ExampleCommand_Run_sliceValues() {
447 cmd := &cli.Command{
448 Name: "multi_values",
449 Flags: []cli.Flag{
450 &cli.StringSliceFlag{Name: "stringSlice"},
451 &cli.FloatSliceFlag{Name: "float64Slice"},
452 &cli.Int64SliceFlag{Name: "intSlice"},
453 },
454 HideHelp: true,
455 Action: func(ctx context.Context, cmd *cli.Command) error {
456 for i, v := range cmd.FlagNames() {
457 fmt.Printf("%d-%s %#v\n", i, v, cmd.Value(v))
458 }
459 err := ctx.Err()
460 fmt.Println("error:", err)
461 return err
462 },
463 }
464
465 // Simulate command line arguments
466 os.Args = []string{
467 "multi_values",
468 "--stringSlice", "parsed1,parsed2", "--stringSlice", "parsed3,parsed4",
469 "--float64Slice", "13.3,14.4", "--float64Slice", "15.5,16.6",
470 "--intSlice", "13,14", "--intSlice", "15,16",
471 }
472
473 _ = cmd.Run(context.Background(), os.Args)
474 // Output:
475 // 0-stringSlice []string{"parsed1", "parsed2", "parsed3", "parsed4"}
476 // 1-float64Slice []float64{13.3, 14.4, 15.5, 16.6}
477 // 2-intSlice []int64{13, 14, 15, 16}
478 // error: <nil>
479 }
480
481 func ExampleCommand_Run_mapValues() {
482 cmd := &cli.Command{
483 Name: "multi_values",
484 Flags: []cli.Flag{
485 &cli.StringMapFlag{Name: "stringMap"},
486 },
487 HideHelp: true,
488 Action: func(ctx context.Context, cmd *cli.Command) error {
489 for i, v := range cmd.FlagNames() {
490 fmt.Printf("%d-%s %#v\n", i, v, cmd.StringMap(v))
491 }
492 fmt.Printf("notfound %#v\n", cmd.StringMap("notfound"))
493 err := ctx.Err()
494 fmt.Println("error:", err)
495 return err
496 },
497 }
498
499 // Simulate command line arguments
500 os.Args = []string{
501 "multi_values",
502 "--stringMap", "parsed1=parsed two", "--stringMap", "parsed3=",
503 }
504
505 _ = cmd.Run(context.Background(), os.Args)
506 // Output:
507 // 0-stringMap map[string]string{"parsed1":"parsed two", "parsed3":""}
508 // notfound map[string]string(nil)
509 // error: <nil>
510 }
511
512 func ExampleBoolWithInverseFlag() {
513 flagWithInverse := &cli.BoolWithInverseFlag{
514 Name: "env",
515 }
516
517 cmd := &cli.Command{
518 Flags: []cli.Flag{
519 flagWithInverse,
520 },
521 Action: func(_ context.Context, cmd *cli.Command) error {
522 if flagWithInverse.IsSet() {
523 if cmd.Bool("env") {
524 fmt.Println("env is set")
525 } else {
526 fmt.Println("no-env is set")
527 }
528 }
529
530 return nil
531 },
532 }
533
534 _ = cmd.Run(context.Background(), []string{"prog", "--no-env"})
535
536 fmt.Println("flags:", len(flagWithInverse.Names()))
537
538 // Output:
539 // no-env is set
540 // flags: 2
541 }
542
543 func ExampleCommand_Suggest() {
544 cmd := &cli.Command{
545 Name: "greet",
546 ErrWriter: os.Stdout,
547 Suggest: true,
548 HideHelp: false,
549 HideHelpCommand: true,
550 CustomRootCommandHelpTemplate: "(this space intentionally left blank)\n",
551 Flags: []cli.Flag{
552 &cli.StringFlag{Name: "name", Value: "squirrel", Usage: "a name to say"},
553 },
554 Action: func(_ context.Context, cmd *cli.Command) error {
555 fmt.Printf("Hello %v\n", cmd.String("name"))
556 return nil
557 },
558 }
559
560 if cmd.Run(context.Background(), []string{"greet", "--nema", "chipmunk"}) == nil {
561 fmt.Println("Expected error")
562 }
563 // Output:
564 // Incorrect Usage: flag provided but not defined: -nema
565 //
566 // Did you mean "--name"?
567 //
568 // (this space intentionally left blank)
569 }
570
571 func ExampleCommand_Suggest_command() {
572 cmd := &cli.Command{
573 ErrWriter: os.Stdout,
574 Name: "greet",
575 Flags: []cli.Flag{
576 &cli.StringFlag{Name: "name", Value: "squirrel", Usage: "a name to say"},
577 },
578 Action: func(_ context.Context, cmd *cli.Command) error {
579 fmt.Printf("Hello %v\n", cmd.String("name"))
580 return nil
581 },
582 Commands: []*cli.Command{
583 {
584 Name: "neighbors",
585 HideHelp: true,
586 HideHelpCommand: true,
587 Suggest: true,
588 CustomHelpTemplate: "(this space intentionally left blank)\n",
589 Flags: []cli.Flag{
590 &cli.BoolFlag{Name: "smiling"},
591 },
592 Action: func(_ context.Context, cmd *cli.Command) error {
593 if cmd.Bool("smiling") {
594 fmt.Println("😀")
595 }
596 fmt.Println("Hello, neighbors")
597 return nil
598 },
599 },
600 },
601 }
602
603 if cmd.Run(context.Background(), []string{"greet", "neighbors", "--sliming"}) == nil {
604 fmt.Println("Expected error")
605 }
606 // Output:
607 // Incorrect Usage: flag provided but not defined: -sliming
608 //
609 // Did you mean "--smiling"?
610 }