-
Notifications
You must be signed in to change notification settings - Fork 73
/
hcl_gen.go
105 lines (86 loc) · 2.55 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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) WriteBooleanAttribute(label string, value bool) {
h.WriteString(fmt.Sprintf("%s%s = %t\n", h.i, label, value))
}
func (h *HCLGen) WriteFloatAttribute(label string, value float64) {
h.WriteString(fmt.Sprintf("%s%s = %g\n", h.i, label, 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))
}
// WriteIntArrayAttribute :function to convert an integer array into a string
func (h *HCLGen) WriteIntArrayAttribute(label string, values []int) {
arrayString := "["
commaFlag := false
for _, value := range values {
if !commaFlag {
arrayString += fmt.Sprintf("%d", value)
commaFlag = true
} else {
arrayString += fmt.Sprintf(", %d", value)
}
}
arrayString += "]"
h.WriteString(fmt.Sprintf("%s%s = %s\n", h.i, label, arrayString))
}
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]
}