diff --git a/pkg/jsonnet/eval.go b/pkg/jsonnet/eval.go index 7b5ac3cef..5c85ffb89 100644 --- a/pkg/jsonnet/eval.go +++ b/pkg/jsonnet/eval.go @@ -27,12 +27,8 @@ func EvaluateFile(jsonnetFile string) (string, error) { // Evaluate renders the given jsonnet into a string func Evaluate(sonnet string, jpath []string) (string, error) { - importer := jsonnet.FileImporter{ - JPaths: jpath, - } - vm := jsonnet.MakeVM() - vm.Importer(&importer) + vm.Importer(NewExtendedImporter(jpath)) for _, nf := range native.Funcs() { vm.NativeFunction(nf) } diff --git a/pkg/jsonnet/importer.go b/pkg/jsonnet/importer.go new file mode 100644 index 000000000..59285ffc6 --- /dev/null +++ b/pkg/jsonnet/importer.go @@ -0,0 +1,50 @@ +package jsonnet + +import ( + "encoding/json" + "path/filepath" + + jsonnet "github.com/google/go-jsonnet" + "github.com/pkg/errors" + "gopkg.in/yaml.v3" +) + +// ExtendedImporter wraps jsonnet.FileImporter to add additional functionality: +// - `import "file.yaml"` +type ExtendedImporter struct { + fi *jsonnet.FileImporter +} + +// NewExtendedImporter returns a new instance of ExtendedImporter with the +// correct jpaths set up +func NewExtendedImporter(jpath []string) *ExtendedImporter { + return &ExtendedImporter{ + fi: &jsonnet.FileImporter{ + JPaths: jpath, + }, + } +} + +func (i *ExtendedImporter) Import(importedFrom, importedPath string) (contents jsonnet.Contents, foundAt string, err error) { + // regularly import + contents, foundAt, err = i.fi.Import(importedFrom, importedPath) + if err != nil { + return jsonnet.Contents{}, "", err + } + + // if yaml -> convert to json + ext := filepath.Ext(foundAt) + if ext == ".yaml" || ext == ".yml" { + var data map[string]interface{} + if err := yaml.Unmarshal([]byte(contents.String()), &data); err != nil { + return jsonnet.Contents{}, "", errors.Wrapf(err, "unmarshalling yaml import '%s'", foundAt) + } + out, err := json.Marshal(data) + if err != nil { + return jsonnet.Contents{}, "", errors.Wrapf(err, "converting '%s' to json", foundAt) + } + contents = jsonnet.MakeContents(string(out)) + } + + return +} diff --git a/pkg/jsonnet/imports.go b/pkg/jsonnet/imports.go index adf507140..f447196a9 100644 --- a/pkg/jsonnet/imports.go +++ b/pkg/jsonnet/imports.go @@ -24,12 +24,9 @@ func TransitiveImports(filename string) ([]string, error) { if err != nil { return nil, errors.Wrap(err, "resolving JPATH") } - importer := jsonnet.FileImporter{ - JPaths: jpath, - } vm := jsonnet.MakeVM() - vm.Importer(&importer) + vm.Importer(NewExtendedImporter(jpath)) for _, nf := range native.Funcs() { vm.NativeFunction(nf) }