From 571abd37009ae907e675f07628121667e184ab2f Mon Sep 17 00:00:00 2001 From: msshin Date: Wed, 5 Aug 2015 16:30:41 +0900 Subject: [PATCH] Initial commit --- README.md | 28 +++++++++++++++++ main.go | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 README.md create mode 100644 main.go diff --git a/README.md b/README.md new file mode 100644 index 0000000..d47f0b7 --- /dev/null +++ b/README.md @@ -0,0 +1,28 @@ +# envconf + +It's simple env based config file transform for docker boot time configuration. + + +``` +$cat a.conf +[servera] +HOST={{ .HOST | default "B" }} + +$export HOST="HOSTA" + +$envconf a.conf + +$cat a.conf +``` + +``` +$envconf a.conf b.conf ... +or +$export ENV_CONF_FILES=a.conf:b.conf:c.conf +$envconf +``` + + + + + diff --git a/main.go b/main.go new file mode 100644 index 0000000..d89bf43 --- /dev/null +++ b/main.go @@ -0,0 +1,90 @@ +package main + +import ( + "github.com/namsral/flag" + "log" + "os" + "strings" + "text/template" +) + +const ( + CONF_FILES = "ENV_CONF_FILES" +) + +var ( + env map[string]string = make(map[string]string) + confPaths []string + templateFuncMap template.FuncMap +) + +func init() { + flag.Parse() + + if len(flag.Args()) >= 0 { + for _, path := range flag.Args() { + confPaths = append(confPaths, path) + } + } + + for _, pair := range os.Environ() { + item := strings.SplitN(pair, "=", 2) + if len(item) < 2 { + log.Fatalf("invalid item from os.Environ %s", pair) + } + env[item[0]] = item[1] + } + + if val, ok := env[CONF_FILES]; ok { + paths := strings.Split(val, ":") + for _, path := range paths { + confPaths = append(confPaths, path) + } + } + + templateFuncMap = template.FuncMap{ + "default": func(args ...string) string { + return args[0] + }, + } +} + +func main() { + for _, path := range confPaths { + err := transformFile(path) + if err != nil { + log.Printf("Err: %s,%s", path, err) + } else { + log.Printf("Transformed %s", path) + } + } +} + +func transformFile(path string) error { + t := template.New(path) + t = t.Funcs(templateFuncMap) + t, err := t.ParseFiles(path) + if err != nil { + log.Printf("Err: Parsing file %s %s", path, err) + return err + } + + t = t.Funcs(templateFuncMap) + + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + log.Printf("Err: Can't open a file %s %s", path, err) + return err + } + defer func() { + if file != nil { + file.Close() + } + }() + + if err = t.Execute(file, env); err != nil { + return err + } + + return nil +}