Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/operator/config/fs_importer.go
4095 views
1
package config
2
3
import (
4
"bytes"
5
"fmt"
6
"io"
7
"io/fs"
8
"path"
9
"strings"
10
11
jsonnet "github.com/google/go-jsonnet"
12
)
13
14
// FSImporter implements jsonnet.Importer for a fs.FS.
15
type FSImporter struct {
16
fs fs.FS
17
18
cache map[string]jsonnet.Contents
19
paths []string
20
}
21
22
// NewFSImporter creates a new jsonnet VM Importer that uses the given fs.
23
func NewFSImporter(f fs.FS, paths []string) *FSImporter {
24
return &FSImporter{
25
fs: f,
26
cache: make(map[string]jsonnet.Contents),
27
paths: paths,
28
}
29
}
30
31
// Import implements jsonnet.Importer.
32
func (i *FSImporter) Import(importedFrom, importedPath string) (contents jsonnet.Contents, foundAt string, err error) {
33
tryPaths := append([]string{importedFrom}, i.paths...)
34
for _, p := range tryPaths {
35
cleanedPath := path.Clean(
36
path.Join(path.Dir(p), importedPath),
37
)
38
cleanedPath = strings.TrimPrefix(cleanedPath, "./")
39
40
c, fa, err := i.tryImport(cleanedPath)
41
if err == nil {
42
return c, fa, err
43
}
44
}
45
46
return jsonnet.Contents{}, "", fmt.Errorf("no such file: %s", importedPath)
47
}
48
49
func (i *FSImporter) tryImport(path string) (contents jsonnet.Contents, foundAt string, err error) {
50
// jsonnet expects the same "foundAt" to always return the same instance of
51
// contents, so we need to return a cache here.
52
if c, ok := i.cache[path]; ok {
53
return c, path, nil
54
}
55
56
f, err := i.fs.Open(path)
57
if err != nil {
58
err = jsonnet.RuntimeError{Msg: err.Error()}
59
return
60
}
61
62
var buf bytes.Buffer
63
if _, copyErr := io.Copy(&buf, f); copyErr != nil {
64
err = jsonnet.RuntimeError{Msg: copyErr.Error()}
65
return
66
}
67
68
contents = jsonnet.MakeContents(buf.String())
69
i.cache[path] = contents
70
return contents, path, nil
71
}
72
73