Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add required flags documentation #1008

Merged
merged 18 commits into from Dec 25, 2019
Merged
Changes from 17 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
58 changes: 58 additions & 0 deletions docs/v2/manual.md
Expand Up @@ -13,6 +13,7 @@ cli v2 manual
+ [Values from the Environment](#values-from-the-environment)
+ [Values from files](#values-from-files)
+ [Values from alternate input sources (YAML, TOML, and others)](#values-from-alternate-input-sources-yaml-toml-and-others)
+ [Required Flags](#required-flags)
+ [Default Values for help output](#default-values-for-help-output)
+ [Precedence](#precedence)
* [Subcommands](#subcommands)
Expand Down Expand Up @@ -641,6 +642,63 @@ func main() {
}
```

#### Required Flags

You can make a flag required by setting the `Required` field to `true`. If a user
does not provide a required flag, they will be shown an error message.

Take for example this app that reqiures the `lang` flag:

<!-- {
"error": "Required flag \"lang\" not set"
} -->
```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,
},
}

app.Action = func(c *cli.Context) error {
var output string
if c.String("lang") == "spanish" {
output = "Hola"
} else {
output = "Hello"
}
fmt.Println(output)
return nil
}

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

If the app is run without the `lang` flag, the user will see the following message

```
Required flag "lang" not set
```

#### 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