Skip to content

Commit

Permalink
Merge remote-tracking branch 'anberns/feature-add-flag-error-interfac…
Browse files Browse the repository at this point in the history
…e' into lynncyrin-patch-8

Co-authored-by: Aaron Berns <anberns@gmail.com>
  • Loading branch information
coilysiren and anberns committed Dec 21, 2019
2 parents 90a3499 + ee2dd88 commit bff6ec5
Showing 1 changed file with 79 additions and 0 deletions.
79 changes: 79 additions & 0 deletions docs/v2/manual.md
Expand Up @@ -641,6 +641,85 @@ func main() {
}
```

#### Required Flags

You can make a flag required by setting the `Required` field to `true`. If an end-user
fails to provide a required flag, they will be shown a default error message, or a
custom message if one is defined. To define a custom error message for a required flag,
set the `RequiredFlagErr` field equal to a `cli.FlagErr` struct with a `Custom` field of `true`
and a `Message` field containing the custom error message. Default and custom error messages
can be mixed with default messages displayed before custom messages.

For example this:

```go
package main

import (
"log"
"os"
"strings"

"github.com/urfave/cli"
)

func main() {
app := cli.NewApp()

app.Flags = []cli.Flag {
cli.StringFlag{
Name: "lang",
Value: "english",
Usage: "language for the greeting",
Required: true,
RequiredFlagErr: cli.FlagErr{
Custom: true,
Message: `There's a problem: "lang" is a required flag` ,
},
},
cli.StringFlag{
Name: "mood",
Value: "normal",
Usage: "emphasis for the greeting",
Required: true,
},
}

app.Action = func(c *cli.Context) error {
name := "Nefertiti"
if c.NArg() > 0 {
name = c.Args().Get(0)
}
var output string
if c.String("lang") == "spanish" {
output = "Hola " + name
} else {
output = "Hello " + name
}

if c.String("mood") == "excited" {
output = strings.ToUpper(output)
}

return nil
}

err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
```

Creates an app that requires both `lang` and `mood` flags. If an attempt
to run the app is made without either, the end-user will see the following
prompts:

```
Required flag "mood" not set
There's a problem: "lang" is a required flag
```

#### Default Values for help output

Sometimes it's useful to specify a flag's default help-text value within the flag declaration. This can be useful if the default value for a flag is a computed value. The default value can be set via the `DefaultText` struct field.
Expand Down

0 comments on commit bff6ec5

Please sign in to comment.