Skip to content
This repository has been archived by the owner on Nov 17, 2021. It is now read-only.

Import all paths passed on the command line via the VM #308

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,16 @@ func JsonnetVM(cmd *cobra.Command) (*jsonnet.VM, error) {
// won't try to glean from an extVar or TLA reference the context necessary to
// resolve a relative path.
path := kv[1]
if !filepath.IsAbs(path) {
path = filepath.Join(cwd, path)
u, err := url.Parse(path)
if err != nil {
return nil, err
}
if u.Scheme == "" {
if !filepath.IsAbs(u.Path) {
u.Path = filepath.Join(cwd, u.Path)
}
u.Scheme = "file"
}
u := &url.URL{Scheme: "file", Path: path}
var imp string
if spec.isCode {
imp = "import"
Expand Down
94 changes: 17 additions & 77 deletions utils/acquire.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,84 +16,37 @@
package utils

import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strings"

jsonnet "github.com/google/go-jsonnet"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/yaml"
)

// Read fetches and decodes K8s objects by path.
// TODO: Replace this with something supporting more sophisticated
// content negotiation.
func Read(vm *jsonnet.VM, path string) ([]runtime.Object, error) {
ext := filepath.Ext(path)
if ext == ".json" {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return jsonReader(f)
} else if ext == ".yaml" {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return yamlReader(f)
} else if ext == ".jsonnet" {
return jsonnetReader(vm, path)
}

return nil, fmt.Errorf("Unknown file extension: %s", path)
}

func jsonReader(r io.Reader) ([]runtime.Object, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
obj, _, err := unstructured.UnstructuredJSONScheme.Decode(data, nil, nil)
if err != nil {
return nil, err
}
return []runtime.Object{obj}, nil
}

func yamlReader(r io.ReadCloser) ([]runtime.Object, error) {
decoder := yaml.NewYAMLReader(bufio.NewReader(r))
ret := []runtime.Object{}
for {
bytes, err := decoder.Read()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if len(bytes) == 0 {
continue
}
jsondata, err := yaml.ToJSON(bytes)
if err != nil {
return nil, err
}
obj, _, err := unstructured.UnstructuredJSONScheme.Decode(jsondata, nil, nil)
if err != nil {
return nil, err
}
ret = append(ret, obj)
// Double any single quotes in the path so they are quoted in the produced expression
quotedPath := strings.Replace(path, "'", "''", -1)
var expr string
switch ext {
case ".json":
expr = fmt.Sprintf(`(import "internal:///kubecfg.libsonnet").parseJson(importstr @'%s')`, quotedPath)
case ".yaml":
expr = fmt.Sprintf(`(import "internal:///kubecfg.libsonnet").parseYaml(importstr @'%s')`, quotedPath)
case ".jsonnet":
expr = fmt.Sprintf("import @'%s'", quotedPath)
default:
// Keep unquoted path in return error to not confuse anyone
return nil, fmt.Errorf("Unknown file extension: %s", path)
}
return ret, nil
return jsonnetReader(vm, expr)
}

type walkContext struct {
Expand Down Expand Up @@ -149,21 +102,8 @@ func jsonWalk(parentCtx *walkContext, obj interface{}) ([]interface{}, error) {
}
}

func jsonnetReader(vm *jsonnet.VM, path string) ([]runtime.Object, error) {
// TODO: Read via Importer, so we support HTTP, etc for first
// file too.
abs, err := filepath.Abs(path)
if err != nil {
return nil, err
}
pathUrl := &url.URL{Scheme: "file", Path: filepath.ToSlash(abs)}

bytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}

jsonstr, err := vm.EvaluateSnippet(pathUrl.String(), string(bytes))
func jsonnetReader(vm *jsonnet.VM, expr string) ([]runtime.Object, error) {
jsonstr, err := vm.EvaluateSnippet("", expr)
if err != nil {
return nil, err
}
Expand Down
8 changes: 8 additions & 0 deletions utils/importer.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,14 @@ func (importer *universalImporter) expandImportToCandidateURLs(importedFrom, imp
return []*url.URL{importedPathURL}, nil
}

if importedFrom == "" {
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("Could not determine current directory: %v", err)
}
importedFrom = "file://" + cwd + "/."
}

importDirURL, err := url.Parse(importedFrom)
if err != nil {
return nil, fmt.Errorf("Invalid import dir %q: %v", importedFrom, err)
Expand Down