-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
142 lines (122 loc) · 2.5 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package main
import (
"fmt"
"github.com/namsral/flag"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
const (
CONF_FILES = "ENV_CONF_FILES"
)
var (
templateFuncMap template.FuncMap
)
func init() {
flag.Usage = func() {
fmt.Printf("Usage: envconv [options] file [files...]\n\n")
flag.PrintDefaults()
}
version := flag.Bool("v", false, "Prints current version")
flag.Parse()
if *version {
fmt.Println("envconf version " + VERSION)
os.Exit(0)
}
templateFuncMap = template.FuncMap{
"default": func(args ...string) string {
defer recovery()
if len(args) <= 0 {
return ""
}
return args[len(args)-1]
},
"in": func(arg string, slice []string) bool {
defer recovery()
for _, i := range slice {
if arg == i {
return true
}
}
return false
},
}
}
func main() {
paths := confFilePaths()
env := environ()
for _, path := range paths {
err := transformFile(path, env)
if err != nil {
log.Printf("Err: %s,%s", path, err)
} else {
log.Printf("Transformed %s", path)
}
}
}
func environ() map[string]interface{} {
env := make(map[string]interface{})
for _, pair := range os.Environ() {
item := strings.SplitN(pair, "=", 2)
if len(item) < 2 {
log.Fatalf("invalid item from os.Environ %s", pair)
}
if strings.Contains(item[1], ",") {
val := strings.Split(item[1], ",")
env[item[0]] = val
} else {
env[item[0]] = item[1]
}
}
return env
}
func confFilePaths() []string {
var paths []string
if len(flag.Args()) >= 0 {
for _, path := range flag.Args() {
paths = append(paths, path)
}
}
if val := os.Getenv(CONF_FILES); val != "" {
for _, path := range strings.Split(val, ":") {
paths = append(paths, path)
}
}
return paths
}
func transformFile(path string, env map[string]interface{}) error {
tname := filepath.Base(path)
t := template.New(tname).Funcs(templateFuncMap)
t, err := t.ParseFiles(path)
if err != nil {
log.Printf("Err: Parsing file %s %s", path, err)
return err
}
var fileMode os.FileMode = 0644 //default
if fi, err := os.Stat(path); err == nil {
fileMode = fi.Mode()
} else {
log.Printf("Err: %s", err)
}
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode)
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
}
func recovery() {
if r := recover(); r != nil {
log.Println("Panic in", r)
}
}