Skip to content

Commit

Permalink
Merge pull request #208 from mkmik/jsonnet-imports
Browse files Browse the repository at this point in the history
feat: Add ability to address import's file node from jsonnet lens
  • Loading branch information
mkmik committed Aug 31, 2023
2 parents 4c311c9 + bdf6274 commit b488a69
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
24 changes: 24 additions & 0 deletions pkg/lensed/jsonnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ func (Jsonnet) Apply(src []byte, vals []Setter) ([]byte, error) {
switch n := n.(type) {
case *ast.LiteralString:
oldval = []byte(n.Value)
case *ast.Import:
return nil, fmt.Errorf("cannot directly address an import node. Please use .../~file")
default:
return nil, fmt.Errorf("unhandled node type %T", n)
}
Expand All @@ -72,6 +74,13 @@ func (Jsonnet) Apply(src []byte, vals []Setter) ([]byte, error) {
return b, err
}

func checkImportFile(path []string) error {
if len(path) == 1 && path[0] == "~file" {
return nil
}
return fmt.Errorf("import nodes only support the ~file field, found %q", path)
}

func findJsonnetNode(root ast.Node, path []string) (ast.Node, error) {
if len(path) == 0 {
return root, nil
Expand Down Expand Up @@ -100,6 +109,21 @@ func findJsonnetNode(root ast.Node, path []string) (ast.Node, error) {
return findJsonnetNode(e, path[1:])
case *ast.Local:
return findJsonnetNode(n.Body, path)
case *ast.Import:
if err := checkImportFile(path); err != nil {
return nil, err
}
return n.File, nil
case *ast.ImportStr:
if err := checkImportFile(path); err != nil {
return nil, err
}
return n.File, nil
case *ast.ImportBin:
if err := checkImportFile(path); err != nil {
return nil, err
}
return n.File, nil
default:
return nil, fmt.Errorf("unsupported jsonnet node type: %T", n)
}
Expand Down
21 changes: 21 additions & 0 deletions pkg/lensed/jsonnet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,27 @@ func TestJsonnet(t *testing.T) {
},
`local a=1; {foo:{bar:"abc"}}`,
},
{
`{foo:{bar:import "xyz"}}`,
[]Mapping{
{"~(jsonnet)/foo/bar/~file", "abc"},
},
`{foo:{bar:import "abc"}}`,
},
{
`{foo:{bar:importstr "xyz"}}`,
[]Mapping{
{"~(jsonnet)/foo/bar/~file", "abc"},
},
`{foo:{bar:importstr "abc"}}`,
},
{
`{foo:{bar:importbin "xyz"}}`,
[]Mapping{
{"~(jsonnet)/foo/bar/~file", "abc"},
},
`{foo:{bar:importbin "abc"}}`,
},
}

for i, tc := range testCases {
Expand Down

0 comments on commit b488a69

Please sign in to comment.