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
|
# File 'lib/hcl2-rb/formatter.rb', line 12
def to_hcl2(spaces: 2, tab: 0)
hcl2 = []
each do |k, v|
case v
when Numeric, String, TrueClass, FalseClass
hcl2.push("#{k} = #{v.to_hcl2}\n")
when Array
if v.has_child?
v.each do |child|
hcl2.push({ "#{k}": child }.to_hcl2)
end
else
hcl2.push("#{k} = #{v.to_hcl2}")
end
when Hash
labels = HCL2::Helpers.dfs(v)
labels.each do |label|
n = label.empty? ? nil : label.map { |l| l&.to_hcl2 }.join(' ').prepend(' ')
c = label.empty? ? v : v.dig(*label)
hcl2.push("#{k}#{n} {")
hcl2.push(c.to_hcl2(spaces: spaces, tab: 1))
hcl2.push("}\n")
end
else
raise "#{v.class.name} can't be formatted to HCL2"
end
end
hcl2.map { |v| v.prepend(' ' * spaces * tab) }.join("\n")
end
|