forked from watsonwanda/oracle-suite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
include.go
92 lines (80 loc) · 2.5 KB
/
include.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
package include
import (
"fmt"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2"
utilHCL "github.com/orcfax/oracle-suite/pkg/util/hcl"
)
// Include merges the contents of multiple HCL files specified in the "include"
// attribute using glob patterns.
func Include(ctx *hcl.EvalContext, body hcl.Body, wd string, maxDeep int) (hcl.Body, hcl.Diagnostics) {
// Decode the "include" attribute.
content, remain, diags := body.PartialContent(&hcl.BodySchema{
Attributes: []hcl.AttributeSchema{{Name: "include"}},
})
attr := content.Attributes["include"]
if diags.HasErrors() || attr == nil {
return body, diags
}
var include []string
if diags = utilHCL.DecodeExpression(ctx, attr.Expr, &include); diags.HasErrors() {
return nil, diags
}
// Check for too many nested includes.
if maxDeep <= 0 {
return nil, hcl.Diagnostics{{
Severity: hcl.DiagError,
Summary: "Too many nested includes",
Detail: "Too many nested includes. Possible circular include.",
Subject: attr.Expr.Range().Ptr(),
}}
}
// Iterate over the glob patterns.
var bodies []hcl.Body
for _, pattern := range include {
// Find all files matching the glob pattern.
paths, err := glob(pattern)
if err != nil {
return nil, hcl.Diagnostics{{
Severity: hcl.DiagError,
Summary: "Invalid glob pattern",
Detail: fmt.Sprintf("Invalid glob pattern %s: %s.", pattern, err),
Subject: attr.Expr.Range().Ptr(),
}}
}
// Iterate over the files from the glob pattern.
for _, path := range paths {
path = relativePath(wd, path)
// Parse the file.
fileBody, diags := utilHCL.ParseFile(path, attr.Expr.Range().Ptr())
if diags.HasErrors() {
return nil, diags
}
// Recursively include files.
body, diags := Include(ctx, fileBody, filepath.Dir(path), maxDeep-1)
if diags.HasErrors() {
return nil, diags
}
bodies = append(bodies, body)
}
}
// Merge the body of the main file with the bodies of the included files.
return hcl.MergeBodies([]hcl.Body{remain, hcl.MergeBodies(bodies)}), diags
}
// relativePath returns an absolute path for the given path relative to the
// given working directory.
func relativePath(wd, path string) string {
if filepath.IsAbs(path) {
return path
}
return filepath.Join(wd, path)
}
// glob is a wrapper around filepath.Glob that returns the given pattern
// if it does not contain any glob characters.
func glob(pattern string) ([]string, error) {
if !strings.Contains(pattern, "*") {
return []string{pattern}, nil
}
return filepath.Glob(pattern)
}