2022-09-18 19:28:34 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"flag"
|
2022-09-18 19:39:45 +02:00
|
|
|
"fmt"
|
2022-09-18 19:28:34 +02:00
|
|
|
"os"
|
|
|
|
"text/template"
|
|
|
|
|
2022-09-18 19:39:45 +02:00
|
|
|
"git.milar.in/milarin/adverr"
|
2022-09-18 19:28:34 +02:00
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ConfigFile = &Config{}
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
flag.Parse()
|
|
|
|
|
|
|
|
if err := ReadConfigFile(); err != nil {
|
2022-09-18 19:39:45 +02:00
|
|
|
fmt.Fprintln(os.Stderr, "no config file provided")
|
|
|
|
os.Exit(1)
|
2022-09-18 19:28:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
tmplMap, err := ParseTemplates(template.New("template"), ConfigFile.TemplateDir)
|
|
|
|
if err != nil {
|
2022-09-18 19:39:45 +02:00
|
|
|
adverr.Fatalln(err, 2)
|
2022-09-18 19:28:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.MkdirAll(ConfigFile.TargetDir, 0755); err != nil {
|
2022-09-18 19:39:45 +02:00
|
|
|
adverr.Fatalln(ErrDirectoryCreationFailed.Wrap(err, ConfigFile.TargetDir), 3)
|
2022-09-18 19:28:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, tmpl := range tmplMap {
|
|
|
|
if err := HandleTemplate(tmpl); err != nil {
|
2022-09-18 19:39:45 +02:00
|
|
|
adverr.Fatalln(err, 4)
|
2022-09-18 19:28:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func ReadConfigFile() error {
|
|
|
|
filename := flag.Arg(0)
|
|
|
|
if filename == "" {
|
|
|
|
return errors.New("no config file provided")
|
|
|
|
}
|
|
|
|
|
|
|
|
file, err := os.Open(filename)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
if err := yaml.NewDecoder(file).Decode(ConfigFile); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-09-18 19:55:09 +02:00
|
|
|
ConfigFile.TemplateDir = os.ExpandEnv(ConfigFile.TemplateDir)
|
|
|
|
ConfigFile.TargetDir = os.ExpandEnv(ConfigFile.TargetDir)
|
2022-09-18 19:28:34 +02:00
|
|
|
RecursiveEnvLookupForMap(ConfigFile.Globals)
|
2022-09-18 19:55:09 +02:00
|
|
|
|
2022-09-18 19:28:34 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func RecursiveEnvLookupForMap(m map[interface{}]interface{}) {
|
|
|
|
for k, v := range m {
|
|
|
|
if str, ok := v.(string); ok {
|
|
|
|
m[k] = os.ExpandEnv(str)
|
|
|
|
} else if m2, ok := v.(map[interface{}]interface{}); ok {
|
|
|
|
RecursiveEnvLookupForMap(m2)
|
|
|
|
} else if arr, ok := v.([]interface{}); ok {
|
|
|
|
RecursiveEnvLookupForSlice(arr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func RecursiveEnvLookupForSlice(s []interface{}) {
|
|
|
|
for i, v := range s {
|
|
|
|
if str, ok := v.(string); ok {
|
|
|
|
s[i] = os.ExpandEnv(str)
|
|
|
|
} else if m, ok := v.(map[interface{}]interface{}); ok {
|
|
|
|
RecursiveEnvLookupForMap(m)
|
|
|
|
} else if arr, ok := v.([]interface{}); ok {
|
|
|
|
RecursiveEnvLookupForSlice(arr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|