forked from subchen/frep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
195 lines (166 loc) · 4.87 KB
/
main.go
File metadata and controls
195 lines (166 loc) · 4.87 KB
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"text/template"
"github.com/go-yaml/yaml"
"github.com/subchen/goutils/cli"
"github.com/Masterminds/sprig"
)
const VERSION = "1.0.1"
var (
BuildVersion string
BuildGitCommit string
BuildDate string
)
// create template context
func newTemplateVariables(ctx *cli.Context) map[string]interface{} {
// ENV
vars := make(map[string]interface{})
for _, env := range os.Environ() {
kv := strings.SplitN(env, "=", 2)
vars[kv[0]] = kv[1]
}
// --json
if jsonStr := ctx.String("--json"); jsonStr != "" {
var obj map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &obj); err != nil {
cli.Fatalf("fatal: bad json format: %v", err)
}
for k, v := range obj {
vars[k] = v
}
}
// --load
for _, file := range ctx.StringList("--load") {
if bytes, err := ioutil.ReadFile(file); err != nil {
cli.Fatalf("fatal: cannot load file: %s", file)
} else {
var obj map[string]interface{}
if strings.HasSuffix(file, ".json") {
if err := json.Unmarshal(bytes, &obj); err != nil {
cli.Fatalf("fatal: bad json format: %v", err)
}
} else if strings.HasSuffix(file, ".yaml") || strings.HasSuffix(file, ".yml") {
if err := yaml.Unmarshal(bytes, &obj); err != nil {
cli.Fatalf("fatal: bad yaml format: %v", err)
}
} else {
cli.Fatalf("fatal: bad file type: %s", file)
}
for k, v := range obj {
vars[k] = v
}
}
}
// --env
for _, env := range ctx.StringList("--env") {
kv := strings.SplitN(env, "=", 2)
vars[kv[0]] = kv[1]
}
return vars
}
// builtin template function
func defaultValue(a, b interface{}) interface{} {
if a == nil {
return b
}
if s, ok := a.(string); ok && s == "" {
return b
}
return a
}
func templateExecute(t *template.Template, file string, ctx interface{}, testing bool, overwrite bool) {
filePair := strings.SplitN(file, ":", 2)
srcFile := filePair[0]
destFile := ""
if len(filePair) == 2 {
destFile = filePair[1]
} else {
if pos := strings.LastIndex(srcFile, "."); pos == -1 {
destFile = srcFile
} else {
destFile = srcFile[0:pos]
}
}
tmpl, err := t.ParseFiles(srcFile)
if err != nil {
cli.Fatalf("fatal: unable to parse template: %v", err)
}
dest := os.Stdout
if !testing {
if !overwrite {
if _, err := os.Stat(destFile); err == nil {
cli.Fatalf("fatal: unable overwrite destination file: %s", destFile)
}
}
dest, err = os.Create(destFile)
if err != nil {
cli.Fatalf("fatal: unable to create file: %v", err)
}
defer dest.Close()
}
err = tmpl.ExecuteTemplate(dest, filepath.Base(srcFile), ctx)
if err != nil {
cli.Fatalf("fatal: transform template error: %v", err)
}
}
func cliExecute(ctx *cli.Context) {
funcMap := template.FuncMap{
"split": strings.Split,
"default": defaultValue,
}
t := template.New("noname").Funcs(funcMap).Funcs(sprig.TxtFuncMap())
if delimsStr := ctx.String("--delims"); delimsStr != "" {
delims := strings.Split(delimsStr, ":")
if len(delims) != 2 {
cli.Fatalf("fatal: bad delimiters argument: %s. expected \"left:right\"", delimsStr)
}
t = t.Delims(delims[0], delims[1])
}
vars := newTemplateVariables(ctx)
for _, file := range ctx.Args() {
testing := ctx.Bool("--testing")
overwrite := ctx.Bool("--overwrite")
templateExecute(t, file, vars, testing, overwrite)
}
}
func main() {
app := cli.NewApp("frep", "Transform template file using environment, arguments, json/yaml files")
app.Flag("-e, --env", "set variable name=value, can be passed multiple times").Multiple()
app.Flag("--json", "load variables from json object").Placeholder("string")
app.Flag("--load", "load variables from json/yaml files").Multiple()
app.Flag("--overwrite", "overwrite if destination file exists").Bool()
app.Flag("--testing", "test mode, output transform result to console").Bool()
app.Flag("--delims", `template tag delimiters`).Default("{{:}}")
if BuildVersion == "" {
app.Version = VERSION
} else {
app.Version = func() {
fmt.Printf("Version: %s-%s\n", VERSION, BuildVersion)
fmt.Printf("Go version: %s\n", runtime.Version())
fmt.Printf("Git commit: %s\n", BuildGitCommit)
fmt.Printf("Built: %s\n", BuildDate)
fmt.Printf("OS/Arch: %s-%s\n", runtime.GOOS, runtime.GOARCH)
}
}
app.Usage = func() {
fmt.Println("Usage: frep [OPTIONS] input-file:[output-file] ...")
fmt.Println(" or: frep [ --version | --help ]")
}
app.MoreHelp = func() {
fmt.Println("Examples:")
fmt.Println(" frep nginx.conf.in -e webroot=/usr/share/nginx/html -e port=8080")
fmt.Println(" frep nginx.conf.in:/etc/nginx.conf -e webroot=/usr/share/nginx/html -e port=8080")
fmt.Println(" frep nginx.conf.in --json '{\"webroot\": \"/usr/share/nginx/html\", \"port\": 8080}'")
fmt.Println(" frep nginx.conf.in --load context.json --overwrite")
}
app.AllowArgumentCount(1, -1)
app.Execute = cliExecute
app.Run()
}