diff --git a/pkg/env/env.go b/pkg/env/env.go index 88ad4ab..d8a1049 100644 --- a/pkg/env/env.go +++ b/pkg/env/env.go @@ -4,6 +4,7 @@ package env import ( + "bufio" "fmt" "os" "path/filepath" @@ -25,10 +26,11 @@ var managed = []string{ "SUPERPOWERD_SOCKET_DIR", } -// EnsureDefaults sets default values for any OLLIE_* vars not already present -// in the process environment. +// EnsureDefaults loads ~/.config/ollie/env and sets default values for any +// OLLIE_* vars not already present in the process environment. func EnsureDefaults() { home, _ := os.UserHomeDir() + LoadFile(filepath.Join(home, ".config", "ollie", "env")) xdgRuntime := os.Getenv("XDG_RUNTIME_DIR") if xdgRuntime == "" { xdgRuntime = fmt.Sprintf("/run/user/%d", os.Getuid()) @@ -54,6 +56,37 @@ func EnsureDefaults() { // Set sets a variable in the process environment. func Set(k, v string) { os.Setenv(k, v) } //nolint:errcheck +// LoadFile reads KEY=VALUE pairs from path and sets any key not already +// present in the environment. Lines beginning with # and blank lines are +// ignored. Missing file is silently ignored. +func LoadFile(path string) { + f, err := os.Open(path) + if err != nil { + return + } + defer f.Close() + + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + k, v, ok := strings.Cut(line, "=") + if !ok { + continue + } + k = strings.TrimSpace(k) + if i := strings.Index(v, " #"); i >= 0 { + v = v[:i] + } + v = strings.TrimSpace(v) + if k != "" && os.Getenv(k) == "" { + os.Setenv(k, v) //nolint:errcheck + } + } +} + // Get returns a variable from the process environment. func Get(k string) string { return os.Getenv(k) }