Debian Codegraph @

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

raw symbols SCIP
1 ---
2 tags:
3 - v2
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 "errors"
19 "flag"
20 "fmt"
21 "io"
22 "io/ioutil"
23 "os"
24 "time"
25
26 "github.com/urfave/cli/v2"
27 )
28
29 func init() {
30 cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n"
31 cli.CommandHelpTemplate += "\nYMMV\n"
32 cli.SubcommandHelpTemplate += "\nor something\n"
33
34 cli.HelpFlag = &cli.BoolFlag{Name: "halp"}
35 cli.VersionFlag = &cli.BoolFlag{Name: "print-version", Aliases: []string{"V"}}
36
37 cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
38 fmt.Fprintf(w, "best of luck to you\n")
39 }
40 cli.VersionPrinter = func(cCtx *cli.Context) {
41 fmt.Fprintf(cCtx.App.Writer, "version=%s\n", cCtx.App.Version)
42 }
43 cli.OsExiter = func(cCtx int) {
44 fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", cCtx)
45 }
46 cli.ErrWriter = ioutil.Discard
47 cli.FlagStringer = func(fl cli.Flag) string {
48 return fmt.Sprintf("\t\t%s", fl.Names()[0])
49 }
50 }
51
52 type hexWriter struct{}
53
54 func (w *hexWriter) Write(p []byte) (int, error) {
55 for _, b := range p {
56 fmt.Printf("%x", b)
57 }
58 fmt.Printf("\n")
59
60 return len(p), nil
61 }
62
63 type genericType struct {
64 s string
65 }
66
67 func (g *genericType) Set(value string) error {
68 g.s = value
69 return nil
70 }
71
72 func (g *genericType) String() string {
73 return g.s
74 }
75
76 func main() {
77 app := &cli.App{
78 Name: "kənˈtrīv",
79 Version: "v19.99.0",
80 Compiled: time.Now(),
81 Authors: []*cli.Author{
82 &cli.Author{
83 Name: "Example Human",
84 Email: "[email protected]",
85 },
86 },
87 Copyright: "(c) 1999 Serious Enterprise",
88 HelpName: "contrive",
89 Usage: "demonstrate available API",
90 UsageText: "contrive - demonstrating the available API",
91 ArgsUsage: "[args and such]",
92 Commands: []*cli.Command{
93 &cli.Command{
94 Name: "doo",
95 Aliases: []string{"do"},
96 Category: "motion",
97 Usage: "do the doo",
98 UsageText: "doo - does the dooing",
99 Description: "no really, there is a lot of dooing to be done",
100 ArgsUsage: "[arrgh]",
101 Flags: []cli.Flag{
102 &cli.BoolFlag{Name: "forever", Aliases: []string{"forevvarr"}},
103 },
104 Subcommands: []*cli.Command{
105 &cli.Command{
106 Name: "wop",
107 Action: wopAction,
108 },
109 },
110 SkipFlagParsing: false,
111 HideHelp: false,
112 HideHelpCommand: false,
113 Hidden: false,
114 HelpName: "doo!",
115 BashComplete: func(cCtx *cli.Context) {
116 fmt.Fprintf(cCtx.App.Writer, "--better\n")
117 },
118 Before: func(cCtx *cli.Context) error {
119 fmt.Fprintf(cCtx.App.Writer, "brace for impact\n")
120 return nil
121 },
122 After: func(cCtx *cli.Context) error {
123 fmt.Fprintf(cCtx.App.Writer, "did we lose anyone?\n")
124 return nil
125 },
126 Action: func(cCtx *cli.Context) error {
127 cCtx.Command.FullName()
128 cCtx.Command.HasName("wop")
129 cCtx.Command.Names()
130 cCtx.Command.VisibleFlags()
131 fmt.Fprintf(cCtx.App.Writer, "dodododododoodododddooooododododooo\n")
132 if cCtx.Bool("forever") {
133 cCtx.Command.Run(cCtx)
134 }
135 return nil
136 },
137 OnUsageError: func(cCtx *cli.Context, err error, isSubcommand bool) error {
138 fmt.Fprintf(cCtx.App.Writer, "for shame\n")
139 return err
140 },
141 },
142 },
143 Flags: []cli.Flag{
144 &cli.BoolFlag{Name: "fancy"},
145 &cli.BoolFlag{Value: true, Name: "fancier"},
146 &cli.DurationFlag{Name: "howlong", Aliases: []string{"H"}, Value: time.Second * 3},
147 &cli.Float64Flag{Name: "howmuch"},
148 &cli.GenericFlag{Name: "wat", Value: &genericType{}},
149 &cli.Int64Flag{Name: "longdistance"},
150 &cli.Int64SliceFlag{Name: "intervals"},
151 &cli.IntFlag{Name: "distance"},
152 &cli.IntSliceFlag{Name: "times"},
153 &cli.StringFlag{Name: "dance-move", Aliases: []string{"d"}},
154 &cli.StringSliceFlag{Name: "names", Aliases: []string{"N"}},
155 &cli.UintFlag{Name: "age"},
156 &cli.Uint64Flag{Name: "bigage"},
157 },
158 EnableBashCompletion: true,
159 HideHelp: false,
160 HideHelpCommand: false,
161 HideVersion: false,
162 BashComplete: func(cCtx *cli.Context) {
163 fmt.Fprintf(cCtx.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n")
164 },
165 Before: func(cCtx *cli.Context) error {
166 fmt.Fprintf(cCtx.App.Writer, "HEEEERE GOES\n")
167 return nil
168 },
169 After: func(cCtx *cli.Context) error {
170 fmt.Fprintf(cCtx.App.Writer, "Phew!\n")
171 return nil
172 },
173 CommandNotFound: func(cCtx *cli.Context, command string) {
174 fmt.Fprintf(cCtx.App.Writer, "Thar be no %q here.\n", command)
175 },
176 OnUsageError: func(cCtx *cli.Context, err error, isSubcommand bool) error {
177 if isSubcommand {
178 return err
179 }
180
181 fmt.Fprintf(cCtx.App.Writer, "WRONG: %#v\n", err)
182 return nil
183 },
184 Action: func(cCtx *cli.Context) error {
185 cli.DefaultAppComplete(cCtx)
186 cli.HandleExitCoder(errors.New("not an exit coder, though"))
187 cli.ShowAppHelp(cCtx)
188 cli.ShowCommandCompletions(cCtx, "nope")
189 cli.ShowCommandHelp(cCtx, "also-nope")
190 cli.ShowCompletions(cCtx)
191 cli.ShowSubcommandHelp(cCtx)
192 cli.ShowVersion(cCtx)
193
194 fmt.Printf("%#v\n", cCtx.App.Command("doo"))
195 if cCtx.Bool("infinite") {
196 cCtx.App.Run([]string{"app", "doo", "wop"})
197 }
198
199 if cCtx.Bool("forevar") {
200 cCtx.App.RunAsSubcommand(cCtx)
201 }
202 cCtx.App.Setup()
203 fmt.Printf("%#v\n", cCtx.App.VisibleCategories())
204 fmt.Printf("%#v\n", cCtx.App.VisibleCommands())
205 fmt.Printf("%#v\n", cCtx.App.VisibleFlags())
206
207 fmt.Printf("%#v\n", cCtx.Args().First())
208 if cCtx.Args().Len() > 0 {
209 fmt.Printf("%#v\n", cCtx.Args().Get(1))
210 }
211 fmt.Printf("%#v\n", cCtx.Args().Present())
212 fmt.Printf("%#v\n", cCtx.Args().Tail())
213
214 set := flag.NewFlagSet("contrive", 0)
215 nc := cli.NewContext(cCtx.App, set, cCtx)
216
217 fmt.Printf("%#v\n", nc.Args())
218 fmt.Printf("%#v\n", nc.Bool("nope"))
219 fmt.Printf("%#v\n", !nc.Bool("nerp"))
220 fmt.Printf("%#v\n", nc.Duration("howlong"))
221 fmt.Printf("%#v\n", nc.Float64("hay"))
222 fmt.Printf("%#v\n", nc.Generic("bloop"))
223 fmt.Printf("%#v\n", nc.Int64("bonk"))
224 fmt.Printf("%#v\n", nc.Int64Slice("burnks"))
225 fmt.Printf("%#v\n", nc.Int("bips"))
226 fmt.Printf("%#v\n", nc.IntSlice("blups"))
227 fmt.Printf("%#v\n", nc.String("snurt"))
228 fmt.Printf("%#v\n", nc.StringSlice("snurkles"))
229 fmt.Printf("%#v\n", nc.Uint("flub"))
230 fmt.Printf("%#v\n", nc.Uint64("florb"))
231
232 fmt.Printf("%#v\n", nc.FlagNames())
233 fmt.Printf("%#v\n", nc.IsSet("wat"))
234 fmt.Printf("%#v\n", nc.Set("wat", "nope"))
235 fmt.Printf("%#v\n", nc.NArg())
236 fmt.Printf("%#v\n", nc.NumFlags())
237 fmt.Printf("%#v\n", nc.Lineage()[1])
238 nc.Set("wat", "also-nope")
239
240 ec := cli.Exit("ohwell", 86)
241 fmt.Fprintf(cCtx.App.Writer, "%d", ec.ExitCode())
242 fmt.Printf("made it!\n")
243 return ec
244 },
245 Metadata: map[string]interface{}{
246 "layers": "many",
247 "explicable": false,
248 "whatever-values": 19.99,
249 },
250 }
251
252 if os.Getenv("HEXY") != "" {
253 app.Writer = &hexWriter{}
254 app.ErrWriter = &hexWriter{}
255 }
256
257 app.Run(os.Args)
258 }
259
260 func wopAction(cCtx *cli.Context) error {
261 fmt.Fprintf(cCtx.App.Writer, ":wave: over here, eh\n")
262 return nil
263 }
264 ```