Debian Codegraph @

docs/v1/examples/version-flag.md

raw symbols SCIP
1 ---
2 tags:
3 - v1
4 ---
5
6 The default version flag (`-v/--version`) is defined as `cli.VersionFlag`, which
7 is checked by the cli internals in order to print the `App.Version` via
8 `cli.VersionPrinter` and break execution.
9
10 #### Customization
11
12 The default flag may be customized to something other than `-v/--version` by
13 setting `cli.VersionFlag`, e.g.:
14
15 <!-- {
16 "args": ["&#45;&#45print-version"],
17 "output": "partay version 19\\.99\\.0"
18 } -->
19 ``` go
20 package main
21
22 import (
23 "log"
24 "os"
25
26 "github.com/urfave/cli"
27 )
28
29 func main() {
30 cli.VersionFlag = cli.BoolFlag{
31 Name: "print-version, V",
32 Usage: "print only the version",
33 }
34
35 app := cli.NewApp()
36 app.Name = "partay"
37 app.Version = "19.99.0"
38 err := app.Run(os.Args)
39 if err != nil {
40 log.Fatal(err)
41 }
42 }
43 ```
44
45 Alternatively, the version printer at `cli.VersionPrinter` may be overridden, e.g.:
46
47 <!-- {
48 "args": ["&#45;&#45version"],
49 "output": "version=19\\.99\\.0 revision=fafafaf"
50 } -->
51 ``` go
52 package main
53
54 import (
55 "fmt"
56 "log"
57 "os"
58
59 "github.com/urfave/cli"
60 )
61
62 var (
63 Revision = "fafafaf"
64 )
65
66 func main() {
67 cli.VersionPrinter = func(c *cli.Context) {
68 fmt.Printf("version=%s revision=%s\n", c.App.Version, Revision)
69 }
70
71 app := cli.NewApp()
72 app.Name = "partay"
73 app.Version = "19.99.0"
74 err := app.Run(os.Args)
75 if err != nil {
76 log.Fatal(err)
77 }
78 }
79 ```
80
81 #### Full API Example
82
83 **Notice**: This is a contrived (functioning) example meant strictly for API
84 demonstration purposes. Use of one's imagination is encouraged.
85
86 <!-- {
87 "output": "made it!\nPhew!"
88 } -->
89 ``` go
90 package main
91
92 import (
93 "errors"
94 "flag"
95 "fmt"
96 "io"
97 "io/ioutil"
98 "os"
99 "time"
100
101 "github.com/urfave/cli"
102 )
103
104 func init() {
105 cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n"
106 cli.CommandHelpTemplate += "\nYMMV\n"
107 cli.SubcommandHelpTemplate += "\nor something\n"
108
109 cli.HelpFlag = cli.BoolFlag{Name: "halp"}
110 cli.BashCompletionFlag = cli.BoolFlag{Name: "compgen", Hidden: true}
111 cli.VersionFlag = cli.BoolFlag{Name: "print-version, V"}
112
113 cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
114 fmt.Fprintf(w, "best of luck to you\n")
115 }
116 cli.VersionPrinter = func(c *cli.Context) {
117 fmt.Fprintf(c.App.Writer, "version=%s\n", c.App.Version)
118 }
119 cli.OsExiter = func(c int) {
120 fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", c)
121 }
122 cli.ErrWriter = ioutil.Discard
123 cli.FlagStringer = func(fl cli.Flag) string {
124 return fmt.Sprintf("\t\t%s", fl.GetName())
125 }
126 }
127
128 type hexWriter struct{}
129
130 func (w *hexWriter) Write(p []byte) (int, error) {
131 for _, b := range p {
132 fmt.Printf("%x", b)
133 }
134 fmt.Printf("\n")
135
136 return len(p), nil
137 }
138
139 type genericType struct{
140 s string
141 }
142
143 func (g *genericType) Set(value string) error {
144 g.s = value
145 return nil
146 }
147
148 func (g *genericType) String() string {
149 return g.s
150 }
151
152 func main() {
153 app := cli.NewApp()
154 app.Name = "kənˈtrīv"
155 app.Version = "19.99.0"
156 app.Compiled = time.Now()
157 app.Authors = []cli.Author{
158 cli.Author{
159 Name: "Example Human",
160 Email: "[email protected]",
161 },
162 }
163 app.Copyright = "(c) 1999 Serious Enterprise"
164 app.HelpName = "contrive"
165 app.Usage = "demonstrate available API"
166 app.UsageText = "contrive - demonstrating the available API"
167 app.ArgsUsage = "[args and such]"
168 app.Commands = []cli.Command{
169 cli.Command{
170 Name: "doo",
171 Aliases: []string{"do"},
172 Category: "motion",
173 Usage: "do the doo",
174 UsageText: "doo - does the dooing",
175 Description: "no really, there is a lot of dooing to be done",
176 ArgsUsage: "[arrgh]",
177 Flags: []cli.Flag{
178 cli.BoolFlag{Name: "forever, forevvarr"},
179 },
180 Subcommands: cli.Commands{
181 cli.Command{
182 Name: "wop",
183 Action: wopAction,
184 },
185 },
186 SkipFlagParsing: false,
187 HideHelp: false,
188 Hidden: false,
189 HelpName: "doo!",
190 BashComplete: func(c *cli.Context) {
191 fmt.Fprintf(c.App.Writer, "--better\n")
192 },
193 Before: func(c *cli.Context) error {
194 fmt.Fprintf(c.App.Writer, "brace for impact\n")
195 return nil
196 },
197 After: func(c *cli.Context) error {
198 fmt.Fprintf(c.App.Writer, "did we lose anyone?\n")
199 return nil
200 },
201 Action: func(c *cli.Context) error {
202 c.Command.FullName()
203 c.Command.HasName("wop")
204 c.Command.Names()
205 c.Command.VisibleFlags()
206 fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n")
207 if c.Bool("forever") {
208 c.Command.Run(c)
209 }
210 return nil
211 },
212 OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
213 fmt.Fprintf(c.App.Writer, "for shame\n")
214 return err
215 },
216 },
217 }
218 app.Flags = []cli.Flag{
219 cli.BoolFlag{Name: "fancy"},
220 cli.BoolTFlag{Name: "fancier"},
221 cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3},
222 cli.Float64Flag{Name: "howmuch"},
223 cli.GenericFlag{Name: "wat", Value: &genericType{}},
224 cli.Int64Flag{Name: "longdistance"},
225 cli.Int64SliceFlag{Name: "intervals"},
226 cli.IntFlag{Name: "distance"},
227 cli.IntSliceFlag{Name: "times"},
228 cli.StringFlag{Name: "dance-move, d"},
229 cli.StringSliceFlag{Name: "names, N"},
230 cli.UintFlag{Name: "age"},
231 cli.Uint64Flag{Name: "bigage"},
232 }
233 app.EnableBashCompletion = true
234 app.UseShortOptionHandling = true
235 app.HideHelp = false
236 app.HideVersion = false
237 app.BashComplete = func(c *cli.Context) {
238 fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n")
239 }
240 app.Before = func(c *cli.Context) error {
241 fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n")
242 return nil
243 }
244 app.After = func(c *cli.Context) error {
245 fmt.Fprintf(c.App.Writer, "Phew!\n")
246 return nil
247 }
248 app.CommandNotFound = func(c *cli.Context, command string) {
249 fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command)
250 }
251 app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error {
252 if isSubcommand {
253 return err
254 }
255
256 fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err)
257 return nil
258 }
259 app.Action = func(c *cli.Context) error {
260 cli.DefaultAppComplete(c)
261 cli.HandleExitCoder(errors.New("not an exit coder, though"))
262 cli.ShowAppHelp(c)
263 cli.ShowCommandCompletions(c, "nope")
264 cli.ShowCommandHelp(c, "also-nope")
265 cli.ShowCompletions(c)
266 cli.ShowSubcommandHelp(c)
267 cli.ShowVersion(c)
268
269 categories := c.App.Categories()
270 categories.AddCommand("sounds", cli.Command{
271 Name: "bloop",
272 })
273
274 for _, category := range c.App.Categories() {
275 fmt.Fprintf(c.App.Writer, "%s\n", category.Name)
276 fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands)
277 fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands())
278 }
279
280 fmt.Printf("%#v\n", c.App.Command("doo"))
281 if c.Bool("infinite") {
282 c.App.Run([]string{"app", "doo", "wop"})
283 }
284
285 if c.Bool("forevar") {
286 c.App.RunAsSubcommand(c)
287 }
288 c.App.Setup()
289 fmt.Printf("%#v\n", c.App.VisibleCategories())
290 fmt.Printf("%#v\n", c.App.VisibleCommands())
291 fmt.Printf("%#v\n", c.App.VisibleFlags())
292
293 fmt.Printf("%#v\n", c.Args().First())
294 if len(c.Args()) > 0 {
295 fmt.Printf("%#v\n", c.Args()[1])
296 }
297 fmt.Printf("%#v\n", c.Args().Present())
298 fmt.Printf("%#v\n", c.Args().Tail())
299
300 set := flag.NewFlagSet("contrive", 0)
301 nc := cli.NewContext(c.App, set, c)
302
303 fmt.Printf("%#v\n", nc.Args())
304 fmt.Printf("%#v\n", nc.Bool("nope"))
305 fmt.Printf("%#v\n", nc.BoolT("nerp"))
306 fmt.Printf("%#v\n", nc.Duration("howlong"))
307 fmt.Printf("%#v\n", nc.Float64("hay"))
308 fmt.Printf("%#v\n", nc.Generic("bloop"))
309 fmt.Printf("%#v\n", nc.Int64("bonk"))
310 fmt.Printf("%#v\n", nc.Int64Slice("burnks"))
311 fmt.Printf("%#v\n", nc.Int("bips"))
312 fmt.Printf("%#v\n", nc.IntSlice("blups"))
313 fmt.Printf("%#v\n", nc.String("snurt"))
314 fmt.Printf("%#v\n", nc.StringSlice("snurkles"))
315 fmt.Printf("%#v\n", nc.Uint("flub"))
316 fmt.Printf("%#v\n", nc.Uint64("florb"))
317 fmt.Printf("%#v\n", nc.GlobalBool("global-nope"))
318 fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp"))
319 fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong"))
320 fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay"))
321 fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop"))
322 fmt.Printf("%#v\n", nc.GlobalInt("global-bips"))
323 fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups"))
324 fmt.Printf("%#v\n", nc.GlobalString("global-snurt"))
325 fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles"))
326
327 fmt.Printf("%#v\n", nc.FlagNames())
328 fmt.Printf("%#v\n", nc.GlobalFlagNames())
329 fmt.Printf("%#v\n", nc.GlobalIsSet("wat"))
330 fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope"))
331 fmt.Printf("%#v\n", nc.NArg())
332 fmt.Printf("%#v\n", nc.NumFlags())
333 fmt.Printf("%#v\n", nc.Parent())
334
335 nc.Set("wat", "also-nope")
336
337 ec := cli.NewExitError("ohwell", 86)
338 fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode())
339 fmt.Printf("made it!\n")
340 return nil
341 }
342
343 if os.Getenv("HEXY") != "" {
344 app.Writer = &hexWriter{}
345 app.ErrWriter = &hexWriter{}
346 }
347
348 app.Metadata = map[string]interface{}{
349 "layers": "many",
350 "explicable": false,
351 "whatever-values": 19.99,
352 }
353
354
355 // ignore error so we don't exit non-zero and break gfmrun README example tests
356 _ = app.Run(os.Args)
357 }
358
359 func wopAction(c *cli.Context) error {
360 fmt.Fprintf(c.App.Writer, ":wave: over here, eh\n")
361 return nil
362 }
363 ```