forked from nginxinc/nginx-go-crossplane
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.go
290 lines (242 loc) · 5.95 KB
/
build.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
290
/**
* Copyright (c) F5, Inc.
*
* This source code is licensed under the Apache License, Version 2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
package crossplane
import (
"bytes"
"io"
"os"
"path/filepath"
"strings"
"unicode"
"unicode/utf8"
)
type BuildOptions struct {
Indent int
Tabs bool
Header bool
}
const MaxIndent = 100
//nolint:gochecknoglobals
var (
marginSpaces = strings.Repeat(" ", MaxIndent)
marginTabs = strings.Repeat("\t", MaxIndent)
)
const header = `# This config was built from JSON using NGINX crossplane.
# If you encounter any bugs please report them here:
# https://github.com/nginxinc/crossplane/issues
`
// BuildFiles builds all of the config files in a crossplane.Payload and
// writes them to disk.
func BuildFiles(payload Payload, dir string, options *BuildOptions) error {
if dir == "" {
cwd, err := os.Getwd()
if err != nil {
return err
}
dir = cwd
}
for _, config := range payload.Config {
path := config.File
if !filepath.IsAbs(path) {
path = filepath.Join(dir, path)
}
// make directories that need to be made for the config to be built
dirpath := filepath.Dir(path)
if err := os.MkdirAll(dirpath, os.ModeDir|os.ModePerm); err != nil {
return err
}
// build then create the nginx config file using the json payload
var buf bytes.Buffer
if err := Build(&buf, config, options); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
output := append(bytes.TrimRightFunc(buf.Bytes(), unicode.IsSpace), '\n')
if _, err := f.Write(output); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
}
return nil
}
// Build creates an NGINX config from a crossplane.Config.
func Build(w io.Writer, config Config, options *BuildOptions) error {
if options.Indent == 0 {
options.Indent = 4
}
if options.Header {
_, err := w.Write([]byte(header))
if err != nil {
return err
}
}
body := strings.Builder{}
buildBlock(&body, nil, config.Parsed, 0, 0, options)
bodyStr := body.String()
if len(bodyStr) > 0 && bodyStr[len(bodyStr)-1] == '\n' {
bodyStr = bodyStr[:len(bodyStr)-1]
}
_, err := w.Write([]byte(bodyStr))
return err
}
func buildBlock(sb io.StringWriter, parent *Directive, block Directives, depth int, lastLine int, options *BuildOptions) {
for i, stmt := range block {
// if the this statement is a comment on the same line as the preview, do not emit EOL for this stmt
if stmt.Line == lastLine && stmt.IsComment() {
_, _ = sb.WriteString(" #")
_, _ = sb.WriteString(*stmt.Comment)
// sb.WriteString("\n")
continue
}
if i != 0 || parent != nil {
_, _ = sb.WriteString("\n")
}
_, _ = sb.WriteString(margin(options, depth))
if stmt.IsComment() {
_, _ = sb.WriteString("#")
_, _ = sb.WriteString(*stmt.Comment)
} else {
directive := Enquote(stmt.Directive)
_, _ = sb.WriteString(directive)
// special handling for if statements
if directive == "if" {
_, _ = sb.WriteString(" (")
for i, arg := range stmt.Args {
if i > 0 {
_, _ = sb.WriteString(" ")
}
_, _ = sb.WriteString(Enquote(arg))
}
_, _ = sb.WriteString(")")
} else {
for _, arg := range stmt.Args {
_, _ = sb.WriteString(" ")
_, _ = sb.WriteString(Enquote(arg))
}
}
if !stmt.IsBlock() {
_, _ = sb.WriteString(";")
} else {
_, _ = sb.WriteString(" {")
stmt := stmt
buildBlock(sb, stmt, stmt.Block, depth+1, stmt.Line, options)
_, _ = sb.WriteString("\n")
_, _ = sb.WriteString(margin(options, depth))
_, _ = sb.WriteString("}")
}
}
lastLine = stmt.Line
}
}
func margin(options *BuildOptions, depth int) string {
indent := depth * options.Indent
if indent < MaxIndent {
if options.Tabs {
return marginTabs[:depth]
}
return marginSpaces[:indent]
}
if options.Tabs {
return strings.Repeat("\t", depth)
}
return strings.Repeat(" ", options.Indent*depth)
}
func Enquote(arg string) string {
if !needsQuote(arg) {
return arg
}
return strings.ReplaceAll(repr(arg), `\\`, `\`)
}
//nolint:gocyclo
func needsQuote(s string) bool {
if s == "" {
return true
}
// lexer should throw an error when variable expansion syntax
// is messed up, but just wrap it in quotes for now I guess
var char rune
chars := escape(s)
if len(chars) == 0 {
return true
}
// get first rune
char, off := utf8.DecodeRuneInString(chars)
// arguments can't start with variable expansion syntax
if unicode.IsSpace(char) || strings.ContainsRune("{};\"'", char) || strings.HasPrefix(chars, "${") {
return true
}
chars = chars[off:]
expanding := false
var prev rune
for _, c := range chars {
char = c
if prev == '\\' {
prev = 0
continue
}
if unicode.IsSpace(char) || strings.ContainsRune("{;\"'", char) {
return true
}
if (expanding && (prev == '$' && char == '{')) || (!expanding && char == '}') {
return true
}
if (expanding && char == '}') || (!expanding && (prev == '$' && char == '{')) {
expanding = !expanding
}
prev = char
}
return expanding || char == '\\' || char == '$'
}
func escape(s string) string {
if !strings.ContainsAny(s, "{}$;\\") {
return s
}
sb := strings.Builder{}
var pc, cc rune
for _, r := range s {
cc = r
if pc == '\\' || (pc == '$' && cc == '{') {
sb.WriteRune(pc)
sb.WriteRune(cc)
pc = 0
continue
}
if pc == '$' {
sb.WriteRune(pc)
}
if cc != '\\' && cc != '$' {
sb.WriteRune(cc)
}
pc = cc
}
if cc == '\\' || cc == '$' {
sb.WriteRune(cc)
}
return sb.String()
}
// BuildInto builds all of the config files in a crossplane.Payload and
// writes them to the Creator.
func BuildInto(payload *Payload, into Creator, options *BuildOptions) error {
for _, config := range payload.Config {
wc, err := into.Create(config.File)
if err != nil {
return err
}
if err := Build(wc, config, options); err != nil {
return err
}
if err := wc.Close(); err != nil {
return err
}
}
return nil
}