-
Notifications
You must be signed in to change notification settings - Fork 70
/
hcl_gen.go
81 lines (65 loc) · 1.85 KB
/
hcl_gen.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
package terraform
import (
"fmt"
"strings"
)
type HCLGen struct {
strings.Builder
shiftWidth int
i string
}
func NewHCLGen(shiftWidth int) *HCLGen {
return &HCLGen{
Builder: strings.Builder{},
shiftWidth: shiftWidth,
}
}
func (h *HCLGen) WriteMultilineStringAttribute(label string, value string) {
h.WriteString(fmt.Sprintf("%s%s = <<EOT\n%s\nEOT\n", h.i, label, value))
}
func (h *HCLGen) WriteMultilineStringAttributeIfNotEmpty(label string, value string) {
if value != "" {
h.WriteMultilineStringAttribute(label, value)
}
}
func (h *HCLGen) WriteStringAttribute(label string, value string) {
h.WriteString(fmt.Sprintf("%s%s = \"%s\"\n", h.i, label, strings.ReplaceAll(value, "\"", "\\\"")))
}
func (h *HCLGen) WriteStringAttributeIfNotEmpty(label string, value string) {
if value != "" {
h.WriteStringAttribute(label, value)
}
}
func (h *HCLGen) WriteStringSliceAttribute(label string, value []string) {
h.WriteString(fmt.Sprintf("%s%s = [\"%s\"]", h.i, label, strings.Join(value, "\",\"")))
}
func (h *HCLGen) WriteStringSliceAttributeIfNotEmpty(label string, value []string) {
if len(value) > 0 {
h.WriteStringSliceAttribute(label, value)
}
}
func (h *HCLGen) WriteIntAttribute(label string, value int) {
h.WriteString(fmt.Sprintf("%s%s = %d\n", h.i, label, value))
}
func (h *HCLGen) WriteIntAttributeIfNotZero(label string, value int) {
if value != 0 {
h.WriteIntAttribute(label, value)
}
}
func (h *HCLGen) WriteBlock(name string, labels []string, f func()) {
h.WriteString(fmt.Sprintf("\n%s%s ", h.i, name))
for _, l := range labels {
h.WriteString(fmt.Sprintf("\"%s\" ", l))
}
h.WriteString("{\n")
h.indent()
f()
h.unindent()
h.WriteString(fmt.Sprintf("%s}\n", h.i))
}
func (h *HCLGen) indent() {
h.i += strings.Repeat(" ", h.shiftWidth)
}
func (h *HCLGen) unindent() {
h.i = h.i[0 : len(h.i)-h.shiftWidth]
}