cfgen/main.go
2022-09-18 19:39:45 +02:00

85 lines
1.7 KiB
Go

package main
import (
"errors"
"flag"
"fmt"
"os"
"text/template"
"git.milar.in/milarin/adverr"
"gopkg.in/yaml.v2"
)
var (
ConfigFile = &Config{}
)
func main() {
flag.Parse()
if err := ReadConfigFile(); err != nil {
fmt.Fprintln(os.Stderr, "no config file provided")
os.Exit(1)
}
tmplMap, err := ParseTemplates(template.New("template"), ConfigFile.TemplateDir)
if err != nil {
adverr.Fatalln(err, 2)
}
if err := os.MkdirAll(ConfigFile.TargetDir, 0755); err != nil {
adverr.Fatalln(ErrDirectoryCreationFailed.Wrap(err, ConfigFile.TargetDir), 3)
}
for _, tmpl := range tmplMap {
if err := HandleTemplate(tmpl); err != nil {
adverr.Fatalln(err, 4)
}
}
}
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
}
RecursiveEnvLookupForMap(ConfigFile.Globals)
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)
}
}
}