Debian Codegraph @

docs/v2/examples/subcommands.md

raw symbols SCIP
1 ---
2 tags:
3 - v2
4 search:
5 boost: 2
6 ---
7
8 Subcommands can be defined for a more git-like command line app.
9
10 <!-- {
11 "args": ["template", "add"],
12 "output": "new task template: .+"
13 } -->
14 ```go
15 package main
16
17 import (
18 "fmt"
19 "log"
20 "os"
21
22 "github.com/urfave/cli/v2"
23 )
24
25 func main() {
26 app := &cli.App{
27 Commands: []*cli.Command{
28 {
29 Name: "add",
30 Aliases: []string{"a"},
31 Usage: "add a task to the list",
32 Action: func(cCtx *cli.Context) error {
33 fmt.Println("added task: ", cCtx.Args().First())
34 return nil
35 },
36 },
37 {
38 Name: "complete",
39 Aliases: []string{"c"},
40 Usage: "complete a task on the list",
41 Action: func(cCtx *cli.Context) error {
42 fmt.Println("completed task: ", cCtx.Args().First())
43 return nil
44 },
45 },
46 {
47 Name: "template",
48 Aliases: []string{"t"},
49 Usage: "options for task templates",
50 Subcommands: []*cli.Command{
51 {
52 Name: "add",
53 Usage: "add a new template",
54 Action: func(cCtx *cli.Context) error {
55 fmt.Println("new task template: ", cCtx.Args().First())
56 return nil
57 },
58 },
59 {
60 Name: "remove",
61 Usage: "remove an existing template",
62 Action: func(cCtx *cli.Context) error {
63 fmt.Println("removed task template: ", cCtx.Args().First())
64 return nil
65 },
66 },
67 },
68 },
69 },
70 }
71
72 if err := app.Run(os.Args); err != nil {
73 log.Fatal(err)
74 }
75 }
76 ```