Debian Codegraph @

docs/v3/examples/full-api-example.md

raw symbols SCIP
1 ---
2 tags:
3 - v3
4 search:
5 boost: 2
6 ---
7
8 **Notice**: This is a contrived (functioning) example meant strictly for API
9 demonstration purposes. Use of one's imagination is encouraged.
10
11 <!-- {
12 "output": "made it!\nPhew!"
13 } -->
14 ```go
15 package main
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "io"
22 "io/ioutil"
23 "os"
24 "time"
25 "slices"
26
27 "github.com/urfave/cli/v3"
28 )
29
30 func init() {
31 cli.RootCommandHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n"
32 cli.CommandHelpTemplate += "\nYMMV\n"
33 cli.SubcommandHelpTemplate += "\nor something\n"
34
35 cli.HelpFlag = &cli.BoolFlag{Name: "halp"}
36 cli.VersionFlag = &cli.BoolFlag{Name: "print-version", Aliases: []string{"V"}}
37
38 cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
39 fmt.Fprintf(w, "best of luck to you\n")
40 }
41 cli.VersionPrinter = func(cmd *cli.Command) {
42 fmt.Fprintf(cmd.Root().Writer, "version=%s\n", cmd.Root().Version)
43 }
44 cli.OsExiter = func(cmd int) {
45 fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", cmd)
46 }
47 cli.ErrWriter = ioutil.Discard
48 cli.FlagStringer = func(fl cli.Flag) string {
49 return fmt.Sprintf("\t\t%s", fl.Names()[0])
50 }
51 }
52
53 type hexWriter struct{}
54
55 func (w *hexWriter) Write(p []byte) (int, error) {
56 for _, b := range p {
57 fmt.Printf("%x", b)
58 }
59 fmt.Printf("\n")
60
61 return len(p), nil
62 }
63
64 type genericType struct {
65 s string
66 }
67
68 func (g *genericType) Set(value string) error {
69 g.s = value
70 return nil
71 }
72
73 func (g *genericType) String() string {
74 return g.s
75 }
76
77 func main() {
78 cmd := &cli.Command{
79 Name: "kənˈtrīv",
80 Version: "v19.99.0",
81 /*Authors: []any{
82 &cli.Author{
83 Name: "Example Human",
84 Email: "[email protected]",
85 },
86 },*/
87 Copyright: "(c) 1999 Serious Enterprise",
88 Usage: "demonstrate available API",
89 UsageText: "contrive - demonstrating the available API",
90 ArgsUsage: "[args and such]",
91 Commands: []*cli.Command{
92 &cli.Command{
93 Name: "doo",
94 Aliases: []string{"do"},
95 Category: "motion",
96 Usage: "do the doo",
97 UsageText: "doo - does the dooing",
98 Description: "no really, there is a lot of dooing to be done",
99 ArgsUsage: "[arrgh]",
100 Flags: []cli.Flag{
101 &cli.BoolFlag{Name: "forever", Aliases: []string{"forevvarr"}},
102 },
103 Commands: []*cli.Command{
104 &cli.Command{
105 Name: "wop",
106 Action: wopAction,
107 },
108 },
109 SkipFlagParsing: false,
110 HideHelp: false,
111 Hidden: false,
112 ShellComplete: func(ctx context.Context, cmd *cli.Command) {
113 fmt.Fprintf(cmd.Root().Writer, "--better\n")
114 },
115 Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
116 fmt.Fprintf(cmd.Root().Writer, "brace for impact\n")
117 return nil, nil
118 },
119 After: func(ctx context.Context, cmd *cli.Command) error {
120 fmt.Fprintf(cmd.Root().Writer, "did we lose anyone?\n")
121 return nil
122 },
123 Action: func(ctx context.Context, cmd *cli.Command) error {
124 cmd.FullName()
125 cmd.HasName("wop")
126 cmd.Names()
127 cmd.VisibleFlags()
128 fmt.Fprintf(cmd.Root().Writer, "dodododododoodododddooooododododooo\n")
129 if cmd.Bool("forever") {
130 cmd.Run(ctx, nil)
131 }
132 return nil
133 },
134 OnUsageError: func(ctx context.Context, cmd *cli.Command, err error, isSubcommand bool) error {
135 fmt.Fprintf(cmd.Root().Writer, "for shame\n")
136 return err
137 },
138 },
139 },
140 Flags: []cli.Flag{
141 &cli.BoolFlag{Name: "fancy"},
142 &cli.BoolFlag{Value: true, Name: "fancier"},
143 &cli.DurationFlag{Name: "howlong", Aliases: []string{"H"}, Value: time.Second * 3},
144 &cli.FloatFlag{Name: "howmuch"},
145 &cli.IntFlag{Name: "longdistance", Validator: func (t int) error {
146 if t < 10 {
147 return fmt.Errorf("10 miles isn't long distance!!!!")
148 }
149 return nil
150 }},
151 &cli.IntSliceFlag{Name: "intervals"},
152 &cli.StringFlag{Name: "dance-move", Aliases: []string{"d"}, Validator: func(move string) error {
153 moves := []string{"salsa", "tap", "two-step", "lock-step"}
154 if !slices.Contains(moves, move) {
155 return fmt.Errorf("Haven't learnt %s move yet", move)
156 }
157 return nil
158 }},
159 &cli.StringSliceFlag{Name: "names", Aliases: []string{"N"}},
160 &cli.UintFlag{Name: "age"},
161 },
162 EnableShellCompletion: true,
163 HideHelp: false,
164 HideVersion: false,
165 ShellComplete: func(ctx context.Context, cmd *cli.Command) {
166 fmt.Fprintf(cmd.Root().Writer, "lipstick\nkiss\nme\nlipstick\nringo\n")
167 },
168 Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
169 fmt.Fprintf(cmd.Root().Writer, "HEEEERE GOES\n")
170 return nil, nil
171 },
172 After: func(ctx context.Context, cmd *cli.Command) error {
173 fmt.Fprintf(cmd.Root().Writer, "Phew!\n")
174 return nil
175 },
176 CommandNotFound: func(ctx context.Context, cmd *cli.Command, command string) {
177 fmt.Fprintf(cmd.Root().Writer, "Thar be no %q here.\n", command)
178 },
179 OnUsageError: func(ctx context.Context, cmd *cli.Command, err error, isSubcommand bool) error {
180 if isSubcommand {
181 return err
182 }
183
184 fmt.Fprintf(cmd.Root().Writer, "WRONG: %#v\n", err)
185 return nil
186 },
187 Action: func(ctx context.Context, cmd *cli.Command) error {
188 cli.DefaultRootCommandComplete(ctx, cmd)
189 cli.HandleExitCoder(errors.New("not an exit coder, though"))
190 cli.ShowRootCommandHelp(cmd)
191 cli.ShowCommandHelp(ctx, cmd, "also-nope")
192 cli.ShowSubcommandHelp(cmd)
193 cli.ShowVersion(cmd)
194
195 fmt.Printf("%#v\n", cmd.Root().Command("doo"))
196 if cmd.Bool("infinite") {
197 cmd.Root().Run(ctx, []string{"app", "doo", "wop"})
198 }
199
200 if cmd.Bool("forevar") {
201 cmd.Root().Run(ctx, nil)
202 }
203 fmt.Printf("%#v\n", cmd.Root().VisibleCategories())
204 fmt.Printf("%#v\n", cmd.Root().VisibleCommands())
205 fmt.Printf("%#v\n", cmd.Root().VisibleFlags())
206
207 fmt.Printf("%#v\n", cmd.Args().First())
208 if cmd.Args().Len() > 0 {
209 fmt.Printf("%#v\n", cmd.Args().Get(1))
210 }
211 fmt.Printf("%#v\n", cmd.Args().Present())
212 fmt.Printf("%#v\n", cmd.Args().Tail())
213
214 ec := cli.Exit("ohwell", 86)
215 fmt.Fprintf(cmd.Root().Writer, "%d", ec.ExitCode())
216 fmt.Printf("made it!\n")
217 return ec
218 },
219 Metadata: map[string]interface{}{
220 "layers": "many",
221 "explicable": false,
222 "whatever-values": 19.99,
223 },
224 }
225
226 if os.Getenv("HEXY") != "" {
227 cmd.Writer = &hexWriter{}
228 cmd.ErrWriter = &hexWriter{}
229 }
230
231 cmd.Run(context.Background(), os.Args)
232 }
233
234 func wopAction(ctx context.Context, cmd *cli.Command) error {
235 fmt.Fprintf(cmd.Root().Writer, ":wave: over here, eh\n")
236 return nil
237 }
238 ```