-
Notifications
You must be signed in to change notification settings - Fork 9
/
module.go
382 lines (319 loc) · 10.2 KB
/
module.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cuefrontend
import (
"context"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/format"
"golang.org/x/exp/slices"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/fnfs"
"namespacelabs.dev/foundation/internal/fnfs/memfs"
"namespacelabs.dev/foundation/internal/frontend/fncue"
"namespacelabs.dev/foundation/internal/parsing"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/pkggraph"
"namespacelabs.dev/foundation/std/tasks"
)
const (
WorkspaceFile = "ns-workspace.cue"
LegacyWorkspaceFile = "fn-workspace.cue"
)
var ModuleLoader moduleLoader
type moduleLoader struct{}
func (moduleLoader) FindModuleRoot(dir string) (string, error) {
return parsing.RawFindModuleRoot(dir, WorkspaceFile, LegacyWorkspaceFile)
}
func (moduleLoader) ModuleAt(ctx context.Context, dir string) (pkggraph.WorkspaceData, error) {
return tasks.Return(ctx, tasks.Action("workspace.load-workspace").Arg("dir", dir), func(ctx context.Context) (pkggraph.WorkspaceData, error) {
wfile := WorkspaceFile
data, err := os.ReadFile(filepath.Join(dir, WorkspaceFile))
if err != nil {
if os.IsNotExist(err) {
wfile = LegacyWorkspaceFile
data, err = os.ReadFile(filepath.Join(dir, LegacyWorkspaceFile))
}
}
if err != nil {
if os.IsNotExist(err) {
wd, werr := parsing.RawModuleAt(ctx, dir)
if werr != nil {
if os.IsNotExist(werr) {
return nil, fnerrors.New("%s: failed to load workspace", dir)
}
}
return wd, werr
}
return nil, err
}
return moduleFrom(ctx, dir, wfile, data)
})
}
func moduleFrom(ctx context.Context, dir, workspaceFile string, data []byte) (pkggraph.WorkspaceData, error) {
var memfs memfs.FS
memfs.Add(workspaceFile, data)
p, err := fncue.EvalWorkspace(ctx, &memfs, dir, []string{workspaceFile})
if err != nil {
return nil, err
}
w, err := parseWorkspaceValue(p.Val)
if err != nil {
return nil, err
}
return workspaceData{
absPath: dir,
definitionFile: workspaceFile,
data: data,
parsed: w,
source: p.Val,
}, nil
}
func parseWorkspaceValue(val cue.Value) (*schema.Workspace, error) {
var m cueModule
if err := val.Decode(&m); err != nil {
return nil, fnerrors.New("failed to decode workspace contents: %w", err)
}
w := &schema.Workspace{
ModuleName: m.ModuleName,
}
if m.Foundation != nil {
w.Foundation = &schema.Workspace_FoundationRequirements{
MinimumApi: int32(m.Foundation.MinimumAPI),
ToolsVersion: int32(m.Foundation.ToolsVersion),
}
}
for moduleName, relPath := range m.Replaces {
w.Replace = append(w.Replace, &schema.Workspace_Replace{
ModuleName: moduleName,
Path: relPath,
})
}
slices.SortFunc(w.Replace, func(a, b *schema.Workspace_Replace) bool {
if a.ModuleName == b.ModuleName {
return strings.Compare(a.Path, b.Path) < 0
}
return strings.Compare(a.ModuleName, b.ModuleName) < 0
})
for moduleName, dep := range m.Dependencies {
w.Dep = append(w.Dep, &schema.Workspace_Dependency{
ModuleName: moduleName,
Version: dep.Version,
})
}
slices.SortFunc(w.Dep, func(a, b *schema.Workspace_Dependency) bool {
if a.ModuleName == b.ModuleName {
return strings.Compare(a.Version, b.Version) < 0
}
return strings.Compare(a.ModuleName, b.ModuleName) < 0
})
if m.Prebuilts != nil {
w.PrebuiltBaseRepository = m.Prebuilts.BaseRepository
for packageName, digest := range m.Prebuilts.Digests {
w.PrebuiltBinary = append(w.PrebuiltBinary, &schema.Workspace_BinaryDigest{
PackageName: packageName,
Digest: digest,
})
}
slices.SortFunc(w.PrebuiltBinary, func(a, b *schema.Workspace_BinaryDigest) bool {
if a.PackageName == b.PackageName {
return strings.Compare(a.Digest, b.Digest) < 0
}
return strings.Compare(a.PackageName, b.PackageName) < 0
})
}
for name, env := range m.Environments {
purpose, ok := schema.Environment_Purpose_value[strings.ToUpper(env.Purpose)]
if !ok || purpose == 0 {
return nil, fnerrors.New("%s: no such environment purpose %q", name, env.Purpose)
}
out := &schema.Workspace_EnvironmentSpec{
Name: name,
Runtime: env.Runtime,
Purpose: schema.Environment_Purpose(purpose),
}
for k, v := range env.Labels {
out.Labels = append(out.Labels, &schema.Label{Name: k, Value: v})
}
slices.SortFunc(out.Labels, func(a, b *schema.Label) bool {
if a.GetName() == b.GetName() {
return strings.Compare(a.GetValue(), b.GetValue()) < 0
}
return strings.Compare(a.GetName(), b.GetName()) < 0
})
w.EnvSpec = append(w.EnvSpec, out)
}
slices.SortFunc(w.EnvSpec, func(a, b *schema.Workspace_EnvironmentSpec) bool {
return strings.Compare(a.Name, b.Name) < 0
})
w.ExperimentalProtoModuleImports = m.ProtoModuleImports
return w, nil
}
type workspaceData struct {
absPath, definitionFile string
data []byte
parsed *schema.Workspace
source cue.Value
}
func (r workspaceData) ErrorLocation() string { return r.absPath }
func (r workspaceData) ModuleName() string { return r.parsed.ModuleName }
func (r workspaceData) Proto() *schema.Workspace { return r.parsed }
func (r workspaceData) AbsPath() string { return r.absPath }
func (r workspaceData) ReadOnlyFS() fs.FS { return fnfs.Local(r.absPath) }
func (r workspaceData) DefinitionFile() string { return r.definitionFile }
func (r workspaceData) RawData() []byte { return r.data }
func (r workspaceData) structLit() *ast.StructLit { return r.source.Syntax().(*ast.StructLit) }
func (r workspaceData) LoadedFrom() *schema.Workspace_LoadedFrom {
return &schema.Workspace_LoadedFrom{
AbsPath: r.absPath,
DefinitionFile: r.definitionFile,
Contents: r.data,
}
}
func (r workspaceData) FormatTo(w io.Writer) error {
formatted, err := format.Node(&ast.File{Decls: r.structLit().Elts})
if err != nil {
return fnerrors.New("failed to produce cue syntax: %w", err)
}
_, err = w.Write(formatted)
return err
}
func (r workspaceData) WithSetDependency(deps ...*schema.Workspace_Dependency) pkggraph.WorkspaceData {
var add, update []*schema.Workspace_Dependency
for _, dep := range deps {
updated := false
for _, x := range r.parsed.Dep {
if x.ModuleName == dep.ModuleName {
update = append(update, dep)
updated = true
}
}
if !updated {
add = append(add, dep)
}
}
return r.updateDependencies(add, update, nil)
}
func (r workspaceData) WithReplacedDependencies(deps []*schema.Workspace_Dependency) pkggraph.WorkspaceData {
var add, update []*schema.Workspace_Dependency
var toremove []string
observed := map[string]struct{}{}
for _, dep := range deps {
updated := false
for _, x := range r.parsed.Dep {
if x.ModuleName == dep.ModuleName {
update = append(update, dep)
updated = true
}
}
if !updated {
add = append(add, dep)
}
observed[dep.ModuleName] = struct{}{}
}
for _, dep := range r.parsed.Dep {
if _, ok := observed[dep.ModuleName]; !ok {
toremove = append(toremove, dep.ModuleName)
}
}
return r.updateDependencies(add, update, toremove)
}
func (r workspaceData) updateDependencies(add, update []*schema.Workspace_Dependency, remove []string) workspaceData {
syntax := r.structLit()
hasDependencyBlock := false
for _, decl := range syntax.Elts {
switch z := decl.(type) {
case *ast.Field:
if lbl, _, _ := ast.LabelName(z.Label); lbl == "dependency" {
switch st := z.Value.(type) {
case *ast.StructLit:
hasDependencyBlock = true
for _, update := range update {
// XXX O(n^2)
for _, stdecl := range st.Elts {
switch z := stdecl.(type) {
case *ast.Field:
name, _, _ := ast.LabelName(z.Label)
if update.ModuleName == name {
z.Value = makeVersion(update.Version)
}
}
}
}
for _, add := range add {
st.Elts = append(st.Elts, &ast.Field{
Label: ast.NewIdent(add.ModuleName),
Value: makeVersion(add.Version),
})
}
for _, name := range remove {
index := slices.IndexFunc(st.Elts, func(decl ast.Decl) bool {
switch x := decl.(type) {
case *ast.Field:
lbl, _, _ := ast.LabelName(x.Label)
if lbl == name {
return true
}
}
return false
})
st.Elts = slices.Delete(st.Elts, index, index+1)
}
}
}
}
}
if !hasDependencyBlock && len(add) > 0 {
var d []interface{}
for _, add := range add {
d = append(d, &ast.Field{
Label: ast.NewIdent(add.ModuleName),
Value: makeVersion(add.Version),
})
}
syntax.Elts = append(syntax.Elts, &ast.Field{
Label: ast.NewIdent("dependency"),
Value: ast.NewStruct(d...),
})
}
copy := r
copy.source = r.source.Context().BuildExpr(syntax)
return copy
}
func makeVersion(v string) *ast.StructLit {
return ast.NewStruct(&ast.Field{
Label: ast.NewIdent("version"),
Value: ast.NewString(v),
})
}
type cueModule struct {
ModuleName string `json:"module"`
Foundation *cueModuleFoundation `json:"requirements"`
Replaces map[string]string `json:"replace"` // Map: module name -> relative path.
Dependencies map[string]cueModuleVersion `json:"dependency"`
Prebuilts *cueWorkspacePrebuilts `json:"prebuilts"`
Environments map[string]cueEnvironment `json:"environment"`
ProtoModuleImports []*schema.Workspace_ProtoModuleImports `json:"experimentalProtoModuleImports"`
}
type cueModuleFoundation struct {
MinimumAPI int `json:"api"`
ToolsVersion int `json:"toolsVersion"`
}
type cueModuleVersion struct {
Version string `json:"version"`
}
type cueWorkspacePrebuilts struct {
Digests map[string]string `json:"digest"` // Map: package name -> digest.
BaseRepository string `json:"baseRepository"`
}
type cueEnvironment struct {
Runtime string `json:"runtime"`
Purpose string `json:"purpose"`
Labels map[string]string `json:"labels"`
}