Skip to content

Commit

Permalink
feat(jsonnet): import .yaml (#106)
Browse files Browse the repository at this point in the history
Allows to directly import `.yaml` files from `.jsonnet`, as if they were JSON:

   local whatever = import "foo.yaml"
  • Loading branch information
sh0rez authored Nov 10, 2019
1 parent c15cfad commit 8029efa
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 9 deletions.
6 changes: 1 addition & 5 deletions pkg/jsonnet/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
50 changes: 50 additions & 0 deletions pkg/jsonnet/importer.go
Original file line number Diff line number Diff line change
@@ -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
}
5 changes: 1 addition & 4 deletions pkg/jsonnet/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down

0 comments on commit 8029efa

Please sign in to comment.