-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.go
71 lines (59 loc) · 1.35 KB
/
build.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package compiler
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
cueload "cuelang.org/go/cue/load"
)
// Build a cue configuration tree from the files
func Build(ctx context.Context, src string, args ...string) (*cue.Value, error) {
buildConfig := &cueload.Config{
Dir: src,
Overlay: map[string]cueload.Source{},
}
fileSystem := os.DirFS(src)
err := fs.WalkDir(fileSystem, ".", func(p string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if !entry.Type().IsRegular() {
return nil
}
if filepath.Ext(entry.Name()) != ".cue" {
return nil
}
contents, err := fs.ReadFile(fileSystem, p)
if err != nil {
return fmt.Errorf("%s: %w", p, err)
}
overlayPath := path.Join(buildConfig.Dir, p)
buildConfig.Overlay[overlayPath] = cueload.FromBytes(contents)
return nil
})
if err != nil {
return nil, err
}
instances := cueload.Instances(args, buildConfig)
if len(instances) != 1 {
return nil, errors.New("only one package is supported at a time")
}
instance := instances[0]
if err := instance.Err; err != nil {
return nil, err
}
c := cuecontext.New()
v := c.BuildInstance(instance)
if err := v.Err(); err != nil {
return nil, err
}
if err := v.Validate(); err != nil {
return nil, err
}
return &v, nil
}