summaryrefslogtreecommitdiff
path: root/env/env.go
blob: e9ab363293a67bba351e9a2982fe16196fd573d8 (plain)
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
// Package env contains functions that retrieve data from the environment
package env

import (
	"io/fs"
	"os"
	"strings"

	osfs "github.com/hack-pad/hackpadfs/os"
	"github.com/hairyhenderson/gomplate/v4/internal/datafs"
)

// Getenv - retrieves the value of the environment variable named by the key.
// If the variable is unset, but the same variable ending in `_FILE` is set, the
// referenced file will be read into the value.
// Otherwise the provided default (or an emptry string) is returned.
func Getenv(key string, def ...string) string {
	fsys := datafs.WrapWdFS(osfs.NewFS())
	return getenvVFS(fsys, key, def...)
}

// ExpandEnv - like os.ExpandEnv, except supports `_FILE` vars as well
func ExpandEnv(s string) string {
	fsys := datafs.WrapWdFS(osfs.NewFS())
	return expandEnvVFS(fsys, s)
}

// expandEnvVFS -
func expandEnvVFS(fsys fs.FS, s string) string {
	return os.Expand(s, func(s string) string {
		return getenvVFS(fsys, s)
	})
}

// getenvVFS - a convenience function intended for internal use only!
func getenvVFS(fsys fs.FS, key string, def ...string) string {
	val := getenvFile(fsys, key)
	if val == "" && len(def) > 0 {
		return def[0]
	}

	return val
}

func getenvFile(fsys fs.FS, key string) string {
	val := os.Getenv(key)
	if val != "" {
		return val
	}

	p := os.Getenv(key + "_FILE")
	if p != "" {
		val, err := readFile(fsys, p)
		if err != nil {
			return ""
		}
		return strings.TrimSpace(val)
	}

	return ""
}

func readFile(fsys fs.FS, p string) (string, error) {
	b, err := fs.ReadFile(fsys, p)
	if err != nil {
		return "", err
	}

	return string(b), nil
}