Skip to content

Commit

Permalink
Add general purpose config env var getter
Browse files Browse the repository at this point in the history
Similar to the existing one for active help, but generalized.
  • Loading branch information
scop committed Oct 29, 2023
1 parent 22953d8 commit 51693c9
Show file tree
Hide file tree
Showing 2 changed files with 405 additions and 151 deletions.
29 changes: 29 additions & 0 deletions completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package cobra
import (
"fmt"
"os"
"regexp"
"strings"
"sync"

Expand Down Expand Up @@ -904,3 +905,31 @@ func CompError(msg string) {
func CompErrorln(msg string) {
CompError(fmt.Sprintf("%s\n", msg))
}

// configEnvVarGlobalPrefix should not be changed: users will be using it explicitly.
const configEnvVarGlobalPrefix = "COBRA"

var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)

// configEnvVar returns the name of the program-specific configuration environment
// variable. It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
func configEnvVar(name, suffix string) string {
// This format should not be changed: users will be using it explicitly.
v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix))
v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_")
return v
}

// GetEnvConfig returns the value of the configuration environment variable
// <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper
// case, with all non-ASCII-alphanumeric characters replaced by `_`.
// If the value is empty or not set, the value of the environment variable
// COBRA_<SUFFIX> is returned instead.
func GetEnvConfig(cmd *Command, suffix string) string {
v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))
if v == "" {
v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))
}
return v
}
Loading

0 comments on commit 51693c9

Please sign in to comment.