forked from dayleader/app-yaml-env-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (68 loc) · 1.73 KB
/
main.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
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/kelseyhightower/envconfig"
"gopkg.in/yaml.v2"
)
type Input struct {
Path string `envconfig:"PATH" required:"true"`
}
func main() {
fmt.Println("Ready to compile ...")
cfg := Input{}
if err := envconfig.Process("input", &cfg); err != nil {
fmt.Printf("process env var: %s", err)
os.Exit(1)
}
filename, _ := filepath.Abs(cfg.Path)
yamlFile, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
var mapResult map[interface{}]interface{}
err = yaml.Unmarshal(yamlFile, &mapResult)
if err != nil {
panic(err)
}
fmt.Println(fmt.Sprintf("Env variables will be replaced: %v", mapResult["env_variables"]))
for k, any := range mapResult {
if k == "env_variables" {
err := checkIsPointer(&any)
if err != nil {
panic(err)
}
valueOf := reflect.ValueOf(any)
val := reflect.Indirect(valueOf)
switch val.Type().Kind() {
case reflect.Map:
envMap := any.(map[interface{}]interface{})
for in, iv := range envMap {
envName := in.(string)
envVal := iv.(string)
env := strings.Replace(strings.TrimSpace(envVal), "$", "", -1)
envMap[envName] = os.Getenv(env)
}
default:
panic(fmt.Sprintf("This is not supposed to happen, but if it does, good luck"))
}
}
}
fmt.Println(fmt.Sprintf("Compiled env variables: %v", mapResult["env_variables"]))
out, err := yaml.Marshal(mapResult)
// write the whole body at once
err = ioutil.WriteFile(cfg.Path, out, 0644)
if err != nil {
panic(err)
}
}
func checkIsPointer(any interface{}) error {
if reflect.ValueOf(any).Kind() != reflect.Ptr {
return fmt.Errorf("You passed something that was not a pointer: %s", any)
}
return nil
}