Debian Codegraph @

parsers/hcl/hcl.go

raw
1 // Package hcl implements a koanf.Parser that parses Hashicorp
2 // HCL bytes as conf maps.
3 package hcl
4
5 import (
6 "errors"
7
8 "github.com/hashicorp/hcl"
9 )
10
11 // HCL implements a Hashicorp HCL parser.
12 type HCL struct{ flattenSlices bool }
13
14 // Parser returns an HCL Parser.
15 // flattenSlices flattens HCL structures where maps turn into
16 // lists of maps. Read more here: https://github.com/hashicorp/hcl/issues/162
17 // It's recommended to turn this setting on.
18 func Parser(flattenSlices bool) *HCL {
19 return &HCL{flattenSlices: flattenSlices}
20 }
21
22 // Unmarshal parses the given HCL bytes.
23 func (p *HCL) Unmarshal(b []byte) (map[string]any, error) {
24 o, err := hcl.Parse(string(b))
25 if err != nil {
26 return nil, err
27 }
28
29 var out map[string]any
30 if err := hcl.DecodeObject(&out, o); err != nil {
31 return nil, err
32 }
33 if p.flattenSlices {
34 flattenHCL(out)
35 }
36 return out, nil
37 }
38
39 // Marshal marshals the given config map to HCL bytes.
40 func (p *HCL) Marshal(o map[string]any) ([]byte, error) {
41 return nil, errors.New("HCL marshalling is not supported")
42 // TODO: Although this is the only way to do it, it's producing empty bytes.
43 // Needs investigation.
44 // The only way to generate HCL is from the HCL node structure.
45 // Turn the map into JSON, then parse it with the HCL lib to create its
46 // structure, and then, encode to HCL.
47 // j, err := json.Marshal(o)
48 // if err != nil {
49 // return nil, err
50 // }
51 // tree, err := hcl.Parse(string(j))
52 // if err != nil {
53 // return nil, err
54 // }
55
56 // var buf bytes.Buffer
57 // out := bufio.NewWriter(&buf)
58 // if err := printer.Fprint(out, tree.Node); err != nil {
59 // return nil, err
60 // }
61 // return buf.Bytes(), err
62 }
63
64 // flattenHCL flattens an unmarshalled HCL structure where maps
65 // turn into slices -- https://github.com/hashicorp/hcl/issues/162.
66 func flattenHCL(mp map[string]any) {
67 for k, val := range mp {
68 if v, ok := val.([]map[string]any); ok {
69 if len(v) == 1 {
70 mp[k] = v[0]
71 }
72 }
73 }
74 for _, val := range mp {
75 if v, ok := val.(map[string]any); ok {
76 flattenHCL(v)
77 }
78 }
79 }