cli
cli copied to clipboard
Flag with no name, only for environment variables parsing
Checklist
- [x] Are you running the latest v2 release? The list of releases is here.
- [x] Did you check the manual for your release? The v2 manual is here
- [x] Did you perform a search about this feature? Here's the Github guide about searching.
What problem does this solve?
I would like to use cli.Flag only to parse environment variables, without a flag.
Example:
package main
import (
"log"
"os"
"github.com/urfave/cli/v2"
)
func main() {
app := &cli.App{
Flags: []cli.Flag{
&cli.StringFlag{
EnvVars: []string{"DEV_VAR"},
},
&cli.StringFlag{
EnvVars: []string{"ANOTHER_DEV_VAR"},
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
Output:
$ ./foo
foo flag redefined:
panic: foo flag redefined:
goroutine 1 [running]:
[...]
Solution description
A detailed description of what you want to happen.
Describe alternatives you've considered
Alternative is to set the flag as hidden, but I dont want a flag at all.
AFAIK what you want to do isn't possible—there a lot of assumptions in the code base about flags being command-line flags, and those are unlikely to change. For example, the primary way of accessing a variable through a *cli.Context
is through it's name, which is the same as the name of the CLI flag.
I'd personally recommend using hidden—you can use a nonsense name so that users are unlikely to conflict with it, but you still have a unique identifier. Type one out, or for a higher level of obscurity, do something like generate a UUID at runtime:
// first library I found on Google, but there are others
import "github.com/google/uuid"
var (
keyDevVar = uuid.New().String()
keyAnotherVar = uuid.New().String()
)
// ...
app := &cli.App{
Flags: []cli.Flag{
&cli.StringFlag{
Name: keyDevVar,
EnvVars: []string{"DEV_VAR"},
},
&cli.StringFlag{
Name: keyAnotherDevVar,
EnvVars: []string{"ANOTHER_DEV_VAR"},
},
},
}
If you never need flags and only need env vars, there might be better tools to accomplish what you're looking for. https://github.com/kelseyhightower/envconfig is a wonderful tool that just does env vars, not CLI flags or args.
It would be handy if this cli package automatically handles this (either internally generate a uuid, or just dont have any flag). Maybe for v3?
@WestleyK I agree with @rliebz . You are using the incorrect tools for your use case. envconfig will better serve you well.
Not a good use case to implement directly in urfave/cli. User could use alternative mechanisms.