Home

tmpl @main - refs - log -
-
https://git.jolheiser.com/tmpl.git
Template automation
tmpl / env / env.go
- raw
 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
package env

import (
	"encoding/json"
	"errors"
	"os"
	"path/filepath"
)

// Env is tmpl environment variables
type Env map[string]string

// Set sets all environment variables from an Env
func (e Env) Set() error {
	for key, val := range e {
		if err := os.Setenv(key, val); err != nil {
			return err
		}
	}
	return nil
}

// Load loads an env from <path>/env.json
func Load(path string) (Env, error) {
	p := filepath.Join(path, "env.json")
	fi, err := os.Open(p)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return Env{}, nil
		}
		return nil, err
	}
	defer fi.Close()

	var e Env
	if err := json.NewDecoder(fi).Decode(&e); err != nil {
		return nil, err
	}
	return e, nil
}

// Save saves an Env to <path>/env.json
func Save(path string, e Env) error {
	p := filepath.Join(path, "env.json")
	fi, err := os.Create(p)
	if err != nil {
		return err
	}
	return json.NewEncoder(fi).Encode(e)
}