-
Notifications
You must be signed in to change notification settings - Fork 15
/
env.go
57 lines (45 loc) · 1.62 KB
/
env.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
package ejson2env
import (
"errors"
"fmt"
"regexp"
)
var errNoEnv = errors.New("environment is not set in ejson")
var errEnvNotMap = errors.New("environment is not a map[string]interface{}")
var validIdentifierPattern = regexp.MustCompile(`\A[a-zA-Z_][a-zA-Z0-9_]*\z`)
// ExtractEnv extracts the environment values from the map[string]interface{}
// containing all secrets, and returns a map[string]string containing the
// key value pairs. If there's an issue (the environment key doesn't exist, for
// example), returns an error.
func ExtractEnv(secrets map[string]interface{}) (map[string]string, error) {
rawEnv, ok := secrets["environment"]
if !ok {
return nil, errNoEnv
}
envMap, ok := rawEnv.(map[string]interface{})
if !ok {
return nil, errEnvNotMap
}
envSecrets := make(map[string]string, len(envMap))
for key, rawValue := range envMap {
// Reject keys that would be invalid environment variable identifiers
if !validIdentifierPattern.MatchString(key) {
err := fmt.Errorf("invalid identifier as key in environment: %q", key)
return nil, err
}
// Only export values that convert to strings properly.
if value, ok := rawValue.(string); ok {
envSecrets[key] = value
}
}
return envSecrets, nil
}
// ReadAndExtractEnv wraps the read and extract steps. Returns
// a map[string]string containing the environment secrets to export.
func ReadAndExtractEnv(filename, keyDir, privateKey string) (map[string]string, error) {
secrets, err := readSecrets(filename, keyDir, privateKey)
if nil != err {
return map[string]string{}, fmt.Errorf("could not load ejson file: %s", err)
}
return ExtractEnv(secrets)
}