-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhcl.go
67 lines (60 loc) · 1.68 KB
/
hcl.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
package kanvas
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/json"
)
func Decode(filename string, src []byte, ctx *hcl.EvalContext, target interface{}) error {
var file *hcl.File
var diags hcl.Diagnostics
switch suffix := strings.ToLower(filepath.Ext(filename)); suffix {
case ".hcl", ".tf":
file, diags = hclsyntax.ParseConfig(src, filename, hcl.Pos{Line: 1, Column: 1})
case ".json":
file, diags = json.Parse(src, filename)
default:
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Unsupported file format",
Detail: fmt.Sprintf("Cannot read from %s: unrecognized file format suffix %q.", filename, suffix),
})
return diags
}
if diags.HasErrors() {
return diags
}
diags = gohcl.DecodeBody(file.Body, ctx, target)
if diags.HasErrors() {
return diags
}
return nil
}
// decodeHCLFile is a wrapper around Decode that first reads the given filename
// from disk. See the Decode documentation for more information.
func decodeHCLFile(filename string, ctx *hcl.EvalContext, target interface{}) error {
src, err := os.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Configuration file not found",
Detail: fmt.Sprintf("The configuration file %s does not exist.", filename),
},
}
}
return hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Failed to read configuration",
Detail: fmt.Sprintf("Can't read %s: %s.", filename, err),
},
}
}
return Decode(filename, src, ctx, target)
}