diff options
| author | Hugo Hromic <[email protected]> | 2024-07-01 23:07:32 +0100 |
|---|---|---|
| committer | Hugo Hromic <[email protected]> | 2024-09-07 12:19:10 +0100 |
| commit | 9b5c76b1c4eda926cbec2442dd24021653178b6b (patch) | |
| tree | b1a01f3ae7ac2d658a6cfcc2fbfd14ea83ec2343 /parse.go | |
| parent | b218ad854d6817efffffa7f3d2cd3897498b28f6 (diff) | |
Add support for setting a global env var prefix
Diffstat (limited to 'parse.go')
| -rw-r--r-- | parse.go | 13 |
1 files changed, 8 insertions, 5 deletions
@@ -131,6 +131,9 @@ type Config struct { // subcommand StrictSubcommands bool + // EnvPrefix instructs the library to use a name prefix when reading environment variables. + EnvPrefix string + // Exit is called to terminate the process with an error code (defaults to os.Exit) Exit func(int) @@ -235,7 +238,7 @@ func NewParser(config Config, dests ...interface{}) (*Parser, error) { panic(fmt.Sprintf("%s is not a pointer (did you forget an ampersand?)", t)) } - cmd, err := cmdFromStruct(name, path{root: i}, t) + cmd, err := cmdFromStruct(name, path{root: i}, t, config.EnvPrefix) if err != nil { return nil, err } @@ -285,7 +288,7 @@ func NewParser(config Config, dests ...interface{}) (*Parser, error) { return &p, nil } -func cmdFromStruct(name string, dest path, t reflect.Type) (*command, error) { +func cmdFromStruct(name string, dest path, t reflect.Type, envPrefix string) (*command, error) { // commands can only be created from pointers to structs if t.Kind() != reflect.Ptr { return nil, fmt.Errorf("subcommands must be pointers to structs but %s is a %s", @@ -372,9 +375,9 @@ func cmdFromStruct(name string, dest path, t reflect.Type) (*command, error) { case key == "env": // Use override name if provided if value != "" { - spec.env = value + spec.env = envPrefix + value } else { - spec.env = strings.ToUpper(field.Name) + spec.env = envPrefix + strings.ToUpper(field.Name) } case key == "subcommand": // decide on a name for the subcommand @@ -389,7 +392,7 @@ func cmdFromStruct(name string, dest path, t reflect.Type) (*command, error) { } // parse the subcommand recursively - subcmd, err := cmdFromStruct(cmdnames[0], subdest, field.Type) + subcmd, err := cmdFromStruct(cmdnames[0], subdest, field.Type, envPrefix) if err != nil { errs = append(errs, err.Error()) return false |
