-
Notifications
You must be signed in to change notification settings - Fork 2
/
env_sourcer.go
83 lines (66 loc) · 1.67 KB
/
env_sourcer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package config
import (
"fmt"
"os"
"regexp"
"strings"
)
type envSourcer struct {
prefix string
}
var _ Sourcer = &envSourcer{}
var replacePattern = regexp.MustCompile(`[^A-Za-z0-9_]+`)
// NewEnvSourcer creates a Sourcer that pulls values from the environment.
// The environment variable {PREFIX}_{NAME} is read before and, if empty,
// the environment variable {NAME} is read as a fallback. The prefix is
// normalized by replacing all non-alpha characters with an underscore,
// removing leading and trailing underscores, and collapsing consecutive
// underscores with a single character.
func NewEnvSourcer(prefix string) Sourcer {
prefix = strings.Trim(
string(replacePattern.ReplaceAll(
[]byte(prefix),
[]byte("_"),
)),
"_",
)
return &envSourcer{prefix: prefix}
}
func (s *envSourcer) Init() error {
return nil
}
func (s *envSourcer) Tags() []string {
return []string{EnvTag}
}
func (s *envSourcer) Get(values []string) (string, SourcerFlag, error) {
if values[0] == "" {
return "", FlagSkip, nil
}
envvars := []string{
strings.ToUpper(fmt.Sprintf("%s_%s", s.prefix, values[0])),
strings.ToUpper(values[0]),
}
for _, envvar := range envvars {
if val, ok := os.LookupEnv(envvar); ok {
return val, FlagFound, nil
}
}
return "", FlagMissing, nil
}
func (s *envSourcer) Assets() []string {
return []string{"<os environment>"}
}
func (s *envSourcer) Dump() map[string]string {
values := map[string]string{}
for _, name := range getNames() {
values[name] = os.Getenv(name)
}
return values
}
func getNames() []string {
names := []string{}
for _, pair := range os.Environ() {
names = append(names, strings.Split(pair, "=")[0])
}
return names
}