2017-07-27 18:15:56 -07:00
|
|
|
package include
|
|
|
|
|
|
|
|
import (
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
|
2017-09-11 16:40:37 -07:00
|
|
|
"github.com/hashicorp/hcl2/hcl"
|
2017-09-11 17:22:10 -07:00
|
|
|
"github.com/hashicorp/hcl2/hclparse"
|
2017-07-27 18:15:56 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// FileResolver creates and returns a Resolver that interprets include paths
|
|
|
|
// as filesystem paths relative to the calling configuration file.
|
|
|
|
//
|
|
|
|
// When an include is requested, the source filename of the calling config
|
|
|
|
// file is first interpreted relative to the given basePath, and then the
|
|
|
|
// path given in configuration is interpreted relative to the resulting
|
|
|
|
// absolute caller configuration directory.
|
|
|
|
//
|
|
|
|
// This resolver assumes that all calling bodies are loaded from local files
|
|
|
|
// and that the paths to these files were correctly provided to the parser,
|
|
|
|
// either absolute or relative to the given basePath.
|
|
|
|
//
|
|
|
|
// If the path given in configuration ends with ".json" then the referenced
|
2017-09-11 17:22:10 -07:00
|
|
|
// file is interpreted as JSON. Otherwise, it is interpreted as HCL native
|
2017-07-27 18:15:56 -07:00
|
|
|
// syntax.
|
2017-09-11 16:00:31 -07:00
|
|
|
func FileResolver(baseDir string, parser *hclparse.Parser) Resolver {
|
2017-07-27 18:15:56 -07:00
|
|
|
return &fileResolver{
|
|
|
|
BaseDir: baseDir,
|
|
|
|
Parser: parser,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type fileResolver struct {
|
|
|
|
BaseDir string
|
2017-09-11 16:00:31 -07:00
|
|
|
Parser *hclparse.Parser
|
2017-07-27 18:15:56 -07:00
|
|
|
}
|
|
|
|
|
2017-09-11 16:40:37 -07:00
|
|
|
func (r fileResolver) ResolveBodyPath(path string, refRange hcl.Range) (hcl.Body, hcl.Diagnostics) {
|
2017-07-27 18:15:56 -07:00
|
|
|
callerFile := filepath.Join(r.BaseDir, refRange.Filename)
|
|
|
|
callerDir := filepath.Dir(callerFile)
|
|
|
|
targetFile := filepath.Join(callerDir, path)
|
|
|
|
|
2017-09-11 16:40:37 -07:00
|
|
|
var f *hcl.File
|
|
|
|
var diags hcl.Diagnostics
|
2017-07-27 18:15:56 -07:00
|
|
|
if strings.HasSuffix(targetFile, ".json") {
|
|
|
|
f, diags = r.Parser.ParseJSONFile(targetFile)
|
|
|
|
} else {
|
2017-09-11 17:22:10 -07:00
|
|
|
f, diags = r.Parser.ParseHCLFile(targetFile)
|
2017-07-27 18:15:56 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return f.Body, diags
|
|
|
|
}
|