-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.go
289 lines (255 loc) · 6.44 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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"text/template"
"github.com/BurntSushi/toml"
"github.com/go-yaml/yaml"
"github.com/subchen/go-cli"
)
// version
var (
BuildVersion string
BuildGitBranch string
BuildGitRev string
BuildGitCommit string
BuildDate string
)
// flags
var (
EnvironList []string
JsonStr string
LoadFileList []string
Overwrite bool
Dryrun bool
NoSysEnv bool
Delims string
Strict bool
Missing string
)
// template shared context
var (
delims []string
ctx interface{}
)
// create template context
func newTemplateVariables() map[string]interface{} {
var vars = make(map[string]interface{})
// Env
if !NoSysEnv {
envs := make(map[string]interface{})
for _, env := range os.Environ() {
kv := strings.SplitN(env, "=", 2)
envs[kv[0]] = kv[1] // .Env.name
vars[kv[0]] = kv[1] // override using system env in root scope
}
vars["Env"] = envs
}
// --json
if JsonStr != "" {
var obj map[string]interface{}
if err := json.Unmarshal([]byte(JsonStr), &obj); err != nil {
panic(fmt.Errorf("bad json format: %v", err))
}
for k, v := range obj {
vars[k] = v
}
}
// --load
for _, file := range LoadFileList {
if bytes, err := ioutil.ReadFile(file); err != nil {
panic(fmt.Errorf("cannot load file, caused:\n\n %v\n", err))
} else {
var obj map[string]interface{}
if strings.HasSuffix(file, ".json") {
if err := json.Unmarshal(bytes, &obj); err != nil {
panic(fmt.Errorf("bad json format, caused:\n\n %v\n", err))
}
} else if strings.HasSuffix(file, ".yaml") || strings.HasSuffix(file, ".yml") {
if err := yaml.Unmarshal(bytes, &obj); err != nil {
panic(fmt.Errorf("bad yaml format, caused:\n\n %v\n", err))
}
} else if strings.HasSuffix(file, ".toml") {
if err := toml.Unmarshal(bytes, &obj); err != nil {
panic(fmt.Errorf("bad toml format, caused:\n\n %v\n", err))
}
} else {
panic(fmt.Errorf("bad file type: %s", file))
}
for k, v := range obj {
vars[k] = v
}
}
}
// --env
for _, env := range EnvironList {
kv := strings.SplitN(env, "=", 2)
// remove quotes for key="value"
v := kv[1]
if strings.HasPrefix(v, "\"") && strings.HasSuffix(v, "\"") {
v = v[1 : len(v)-1]
} else if strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'") {
v = v[1 : len(v)-1]
}
vars[kv[0]] = v
}
return vars
}
func templateExecute(t *template.Template, file string) {
filePair := strings.SplitN(file, ":", 2)
srcFile := filePair[0]
destFile := ""
if len(filePair) == 2 {
destFile = filePair[1]
} else {
if srcFile == "-" {
destFile = srcFile
} else if pos := strings.LastIndex(srcFile, "."); pos == -1 {
destFile = srcFile
} else {
destFile = srcFile[0:pos]
}
}
var err error
var templateBytes []byte
if srcFile == "-" {
templateBytes, err = ioutil.ReadAll(os.Stdin)
} else {
templateBytes, err = ioutil.ReadFile(srcFile)
}
if err != nil {
panic(fmt.Errorf("unable to read from %v, caused:\n\n %v\n", srcFile, err))
}
tmpl, err := t.Parse(string(templateBytes))
if err != nil {
panic(fmt.Errorf("unable to parse template file, caused:\n\n %v\n", err))
}
var output bytes.Buffer
err = tmpl.Execute(&output, ctx)
if err != nil {
panic(fmt.Errorf("render template error, caused:\n\n %v\n", err))
}
dest := os.Stdout
if Dryrun || destFile == "-" {
dest.Write(output.Bytes())
return
}
if !Overwrite {
if _, err := os.Stat(destFile); err == nil {
panic(fmt.Errorf("unable to overwrite destination file: %s", destFile))
}
}
dest, err = os.Create(destFile)
if err != nil {
panic(fmt.Errorf("unable to create file, caused:\n\n %v\n", err))
}
defer dest.Close()
_, err = dest.Write(output.Bytes())
if err != nil {
panic(fmt.Errorf("unable to write file, caused:\n\n %v\n", err))
}
}
func main() {
app := cli.NewApp()
app.Name = "frep"
app.Usage = "Generate file using template"
app.UsageText = "[options] input-file[:output-file] ..."
app.Authors = "Guoqiang Chen <[email protected]>"
app.Flags = []*cli.Flag{
{
Name: "e, env",
Usage: "set variable name=value, can be passed multiple times",
Placeholder: "name=value",
Value: &EnvironList,
},
{
Name: "json",
Usage: "load variables from json object string",
Placeholder: "jsonstring",
Value: &JsonStr,
},
{
Name: "load",
Usage: "load variables from json/yaml/toml file",
Placeholder: "file",
Value: &LoadFileList,
},
{
Name: "no-sys-env",
Usage: "exclude system environments, default false",
Value: &NoSysEnv,
},
{
Name: "overwrite",
Usage: "overwrite if destination file exists",
Value: &Overwrite,
},
{
Name: "dryrun",
Usage: "just output result to console instead of file",
Value: &Dryrun,
},
{
Name: "strict",
Usage: "exit on any error during template processing",
Value: &Strict,
},
{
Name: "delims",
Usage: "template tag delimiters",
DefValue: "{{:}}",
Value: &Delims,
},
{
Name: "missing",
Usage: "handling of missing vars, one of: default/invalid, zero, error",
DefValue: "default",
Value: &Missing,
},
}
app.Examples = strings.TrimSpace(`
frep nginx.conf.in -e webroot=/usr/share/nginx/html -e port=8080
frep nginx.conf.in:/etc/nginx.conf -e webroot=/usr/share/nginx/html -e port=8080
frep nginx.conf.in --json '{"webroot": "/usr/share/nginx/html", "port": 8080}'
frep nginx.conf.in --load config.json --overwrite
echo "{{ .Env.PATH }}" | frep -
`)
app.Version = BuildVersion
app.BuildInfo = &cli.BuildInfo{
GitBranch: BuildGitBranch,
GitCommit: BuildGitCommit,
GitRevCount: BuildGitRev,
Timestamp: BuildDate,
}
app.Action = func(c *cli.Context) {
if c.NArg() == 0 {
c.ShowHelp()
return
}
defer func() {
if err := recover(); err != nil {
os.Stderr.WriteString(fmt.Sprintf("fatal: %v\n", err))
os.Exit(1)
}
}()
delims = strings.Split(Delims, ":")
if len(Delims) < 3 || len(delims) != 2 {
panic(fmt.Errorf("bad delimiters argument: %s. expected \"left:right\"", Delims))
}
ctx = newTemplateVariables()
for _, file := range c.Args() {
filePair := strings.SplitN(file, ":", 2)
srcFile := filePair[0]
t := template.New(srcFile)
t.Option(fmt.Sprintf("missingkey=%s", Missing))
t.Delims(delims[0], delims[1])
t.Funcs(FuncMap(file))
templateExecute(t, file)
}
}
app.Run(os.Args)
}