-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgo-sdk.dang
More file actions
497 lines (447 loc) · 16.8 KB
/
Copy pathgo-sdk.dang
File metadata and controls
497 lines (447 loc) · 16.8 KB
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
"""
Manage Dagger modules that use the Go SDK.
"""
type GoSdk {
"""
Marker filename that skips generate when found at or above a Go SDK module root.
"""
skipGenerateFilename: String! = ".dagger-go-sdk-skip-generate"
"""
Runtime source to write into modules created by this SDK.
"""
targetRuntime: String! { "go" }
"""
Config filenames that mark a Dagger module root: the CLI 1.0
`dagger-module.toml` (workspace-managed modules) and the legacy `dagger.json`.
A managed module is discovered by whichever it uses.
"""
let moduleConfigFilenames: [String!]! = ["dagger-module.toml", "dagger.json"]
"""
Starter used by init when none is named.
"""
let defaultTemplate: String! = "default"
"""
Return every Go SDK module this workspace manages that is visible from the
client's current location.
Discovery is anchored at the client's cwd, not the workspace root: the
nearest enclosing module plus every managed module at or below the cwd.
Running from a subdirectory acts on the project you're in — and the projects
beneath it — not the whole workspace.
"""
modules(ws: Workspace!): [Mod!]! {
let managed = currentModule.asSDK(workspace: ws).modules.{{path}}
let cwd = ws.cwd.trimPrefix("/").trimSuffix("/")
polyfill
.workspace(ws)
.findConfigDirs(moduleConfigFilenames, exclude: ["**/vendor/**"])
.map { dir => moduleRelPath(cwd, dir) }
.uniq
.filter { path => managed.filter { m => m.path == path }.length > 0 }
.map { path => Mod(rootPath: path, ws: ws, skipGenerateFilename: skipGenerateFilename) }
}
"""
Resolve a cwd-relative path — at or below the cwd ("." , "sub/dir") or a
strict ancestor (".." , "../..") — against the cwd into a
workspace-root-relative path.
"""
let moduleRelPath(cwd: String!, dir: String!): String! {
let base = if (cwd == "" or cwd == ".") { [] } else { cwd.split("/") }
let segs = dir.split("/").reduce(base) { acc, seg =>
if (seg == "..") {
acc.dropLast(1)
} else if (seg == "." or seg == "") {
acc
} else {
acc + [seg]
}
}
if (segs.length == 0) { "." } else { segs.join("/") }
}
"""
Return init templates tracked by this module.
Templates live under templates/<name> and are materialized into the new
module. Init picks one by name, or the module default when none is named.
"""
templates: [Template!]! {
if (currentModule.source.exists("templates")) {
let root = currentModule.source.directory("templates")
root.entries.map { name =>
Template(
name: name.trimSuffix("/"),
source: root.directory(name),
)
}
} else {
directory.entries.map { name =>
Template(
name: name,
source: directory,
)
}
}
}
let normalizePath(p: String!): String! {
let trimmed = p.trimPrefix("./").trimPrefix("/").trimSuffix("/")
if (trimmed == "") { "." } else { trimmed }
}
let pathDepth(p: String!): Int! {
if (p == ".") { 0 } else { p.split("/").length }
}
let pathContains(base: String!, p: String!): Boolean! {
base == "." or p == base or p.hasPrefix(base + "/")
}
let configDir(foundPath: String!, marker: String!): String! {
normalizePath(foundPath.trimPrefix("/").trimSuffix(marker))
}
"""
Return the deepest workspace-managed module containing `path`, or null when
this SDK manages none of its ancestors.
The workspace's [[modules.<sdk>.as-sdk.modules]] entries are the source of
truth for SDK-managed modules, so membership needs no config sniffing.
"""
let managedBase(ws: Workspace!, path: String!): String {
# asSDK raises when this module is not installed as an SDK in the active
# workspace, which is the normal case for a legacy dagger.json-only repo.
# The `.{{path}}` selection is what executes the query, so it must sit
# inside the guard.
let managed = currentModule.asSDK(workspace: ws).modules.{{path}} rescue []
managed
.map { m => normalizePath(m.path) }
.filter { base => pathContains(base, path) }
.reduce(null) { best, base =>
if (best == null) {
base
} else if (pathDepth(base) > pathDepth(best)) {
base
} else {
best
}
}
}
"""
Return the Go SDK module at or above a workspace path.
When `findUp` is true, `path` may point inside the module.
"""
mod(ws: Workspace!, path: String! = ".", findUp: Boolean! = true): Mod! {
let modPath = if (findUp) {
let needle = normalizePath(path)
let asSdkBase = managedBase(ws, needle)
let foundToml = ws.findUp("dagger-module.toml", path)
let foundJson = ws.findUp("dagger.json", path)
let tomlBase = if (foundToml == null) { null } else {
configDir(
foundToml,
"dagger-module.toml",
)
}
let jsonBase = if (foundJson == null) { null } else {
configDir(
foundJson,
"dagger.json",
)
}
# Every candidate is an ancestor of `path`, so they lie on one chain and
# the deepest is the owning module. Resolving each source separately and
# falling back in order would let a shallow as-sdk entry or an ancestor's
# dagger-module.toml shadow a deeper module in a partially-migrated repo.
let asSdkDepth = baseDepth(asSdkBase)
let tomlDepth = baseDepth(tomlBase)
let jsonDepth = baseDepth(jsonBase)
let best = maxDepth(maxDepth(asSdkDepth, tomlDepth), jsonDepth)
if (asSdkBase != null and asSdkDepth == best) {
asSdkBase
} else if (tomlBase != null and tomlDepth == best) {
resolveTomlBase(ws, tomlBase, path)
} else if (jsonBase != null and jsonDepth == best) {
resolveJsonBase(ws, jsonBase, path)
} else {
raise "no Dagger module found containing path: " + path
}
} else {
path.trimPrefix("/")
}
Mod(
rootPath: modPath,
ws: ws,
skipGenerateFilename: skipGenerateFilename,
)
}
let baseDepth(base: String): Int! {
if (base == null) { -1 } else { pathDepth(base) }
}
let maxDepth(a: Int!, b: Int!): Int! {
if (b > a) { b } else { a }
}
let resolveTomlBase(ws: Workspace!, base: String!, path: String!): String! {
let runtimeSource = tomlRuntimeSource(ws, base)
if (runtimeSource == "go") {
base
} else if (runtimeSource == "") {
raise "Dagger module does not use the Go SDK: " + path
} else {
raise "Dagger module does not use the Go SDK: " + path + " (runtime source: " + runtimeSource + ")"
}
}
let resolveJsonBase(ws: Workspace!, base: String!, path: String!): String! {
let configPath = if (base == ".") { "dagger.json" } else { base + "/dagger.json" }
if (ws
.directory("/", include: [configPath])
.file(configPath)
.search(
pattern: "\"sdk\"\\s*:\\s*\\{[^}]*\"source\"\\s*:\\s*\"go\"",
multiline: true,
dotall: true,
limit: 1,
).{{id}}
.length == 0) {
raise "Dagger module does not use the Go SDK: " + path
} else {
base
}
}
"""
Return the runtime source declared by a module's dagger-module.toml, or ""
when it declares none.
Only a quoted `source` on its own line of a literal [runtime] section is
recognized; inline tables and other TOML spellings read as no declaration,
which callers reject rather than mistake for Go.
"""
let tomlRuntimeSource(ws: Workspace!, base: String!): String! {
let configPath = if (base == ".") { "dagger-module.toml" } else { base + "/dagger-module.toml" }
let matches = ws
.directory("/", include: [configPath])
.file(configPath)
.search(
pattern: "^[ \\t]*\\[runtime\\][^\\[]*?^[ \\t]*source[ \\t]*=[ \\t]*(?:\"[^\"]*\"|'[^']*')",
multiline: true,
limit: 1,
).{{matchedLines}}
matches
.map { m => runtimeSourceValue(m.matchedLines) }
.reduce("") { acc, source => if (acc == "") { source } else { acc } }
}
"""
Extract the runtime source value out of a matched [runtime] block.
The match stops at the first uncommented assignment, so the value lives on
the block's last line, ahead of any trailing comment.
"""
let runtimeSourceValue(block: String!): String! {
let sourceLine = block.trimSpace.split("\n").reduce("") { acc, line => line }
let assignment = sourceLine.split("#").reduce("") { acc, part => if (acc == "") { part } else { acc } }.trimSpace
let quote = if (assignment.trimSuffix("'") == assignment) { "\"" } else { "'" }
assignment.trimSuffix(quote).split(quote).reduce("") { acc, part => part }
}
"""
Initialize Go-owned files for a new Dagger module.
The engine resolves the destination `path` and owns the module's config; this
function only returns the SDK-owned starter source to layer onto `path`.
Pass `template` to pick a starter under templates/<template>; it defaults to
`default` (a small working module).
"""
initModule(
ws: Workspace!,
name: String!,
path: String!,
"""
Starter to materialize from templates/<template>: `default` for a small working module, `empty` for a bare struct, `legacy` for the pre-1.0 scaffold.
"""
template: String! = defaultTemplate,
): Changeset! {
let rawPath = path.trimPrefix("./").trimPrefix("/")
let modPath = if (rawPath == "" or rawPath == ".") {
"."
} else if (rawPath == ".." or rawPath.trimPrefix("../") != rawPath) {
raise "path escapes workspace: " + rawPath
} else {
rawPath.trimSuffix("/")
}
let fork = polyfill.workspace(ws).fork
# An empty name means "the default", not the templates/ directory itself —
# which exists, so it would pass the check below and render every starter as
# a subdirectory of the new module.
let starter = if (template == "") { defaultTemplate } else { template }
if (currentModule.source.exists("templates/" + starter) == false) {
raise "unknown init template: " + starter
} else {
fork.withDirectory(modPath, renderedTemplate(name, starter)).changes
}
}
"""
Generate a typed Go client for `module` at `path`.
The engine records the managed client in workspace config before calling
this function. The engine owns materializing the generated client files.
"""
initClient(
ws: Workspace!,
path: String!,
module: String!,
dev: Boolean! = false,
): Changeset! {
polyfill.workspace(ws).fork.changes
}
"""
Build the engine-free client codegen helper.
"""
let codegenBuilder: Container! {
container
.from("golang:1.25-alpine")
.withoutEntrypoint
.withMountedCache("/go/pkg/mod", cacheVolume("go-mod"))
.withMountedCache("/root/.cache/go-build", cacheVolume("go-build"))
.withDirectory("/helper", currentModule.source.directory("helpers/codegen"))
.withWorkdir("/helper")
.withExec(["go", "build", "-o", "/usr/local/bin/codegen", "."])
}
"""
Serialize the bound-module provenance the codegen helper embeds in the
generated serve bootstrap.
"""
let boundModuleJSON(kindJSON: String!, path: String!, ref: String!, pin: String!): String! {
"{\"kind\":" + kindJSON + ",\"path\":" + JSON.encode(path) + ",\"ref\":" + JSON.encode(ref) + ",\"pin\":" + JSON.encode(pin) + "}"
}
"""
Run client codegen: schema + meta in, generated client out. The existing
client directory seeds the output so user files survive and an existing
go.mod keeps its module name and replace directives (only the
dagger.io/dagger pin is refreshed).
"""
let clientDirectory(
schemaJSON: String!,
moduleName: String!,
engineVersion: String!,
kindJSON: String!,
path: String!,
ref: String!,
pin: String!,
existing: Directory!,
): Directory! {
let metaJson = "{\"moduleName\":" + JSON.encode(moduleName) + ",\"engineVersion\":" + JSON.encode(engineVersion) + ",\"module\":" + boundModuleJSON(kindJSON, path, ref, pin) + "}"
codegenBuilder
.withNewFile("/schema.json", schemaJSON)
.withNewFile("/meta.json", metaJson)
.withDirectory("/out", existing)
.withExec(["codegen", "--introspection-json-path", "/schema.json", "--client-meta-path", "/meta.json", "--output", "/out"])
.directory("/out")
}
"""
Existing contents of the client directory, empty when it doesn't exist yet.
"""
let existingClientDir(ws: Workspace!, path: String!): Directory! {
let filtered = ws.directory("/", include: [path + "/**"])
if (filtered.exists(path)) {
filtered.directory(path)
} else {
directory
}
}
"""
Whether a client's bound-module ref points into the workspace rather than
at a remote module.
"""
let isLocalModuleRef(ref: String!): Boolean! {
ref.hasPrefix("/") or ref.hasPrefix(".") or (ref.contains(".") == false)
}
"""
Generate a typed Go client for the module at `module`, written to `path`.
"""
pub generateClient(ws: Workspace!, module: String!, path: String!): Changeset! {
let pws = polyfill.workspace(ws)
let modSrc = pws.moduleSource("/" + module).core
let generated = clientDirectory(
modSrc.clientSchemaIntrospectionJSON.contents,
modSrc.moduleOriginalName,
modSrc.engineVersion,
JSON.encode(modSrc.kind),
module,
modSrc.asString,
modSrc.pin,
existingClientDir(ws, path),
)
pws.fork.withDirectory(path, generated).changes
}
"""
Regenerate every Go client registered on this SDK that is visible from the
client's current location.
Scoped by cwd like `generate`: a returned changeset may only carry paths under
the caller's location, so regenerating from a subdirectory — or nested under
the engine's per-dependency generation, where the cwd is the dependency —
skips clients that live elsewhere in the workspace.
"""
pub generateAllClient(ws: Workspace!): Changeset! @generate {
let pws = polyfill.workspace(ws)
let cwd = normalizePath(ws.cwd)
ws.sdk(name: currentModule.name).clients.{{name, source}}
.filter { client => pathContains(cwd, normalizePath(client.name)) }
.reduce(pws.fork) { fork, client =>
let generated = if (isLocalModuleRef(client.source)) {
# A local module's cached source can miss live edits, so re-resolve
# it fresh from the workspace; git modules are pinned/immutable.
let src = pws.moduleSource("/" + client.source).core
clientDirectory(
src.clientSchemaIntrospectionJSON.contents,
src.moduleOriginalName,
src.engineVersion,
JSON.encode(src.kind),
client.source,
src.asString,
src.pin,
existingClientDir(ws, client.name),
)
} else {
let m = moduleSource(refString: client.source)
clientDirectory(
m.clientSchemaIntrospectionJSON.contents,
m.moduleOriginalName,
m.engineVersion,
JSON.encode(m.kind),
# Git: unused (ref/pin drive the serve).
client.source,
m.asString,
m.pin,
existingClientDir(ws, client.name),
)
}
fork.withDirectory(client.name, generated)
}
.changes
}
"""
Render the templates/<template> starter with the requested module name.
"""
let renderedTemplate(name: String!, template: String!): Directory! {
container
.from("golang:1.25-alpine")
.withoutEntrypoint
.withMountedCache("/go/pkg/mod", cacheVolume("go-mod"))
.withMountedCache("/root/.cache/go-build", cacheVolume("go-build"))
.withDirectory("/helper", currentModule.source.directory("helpers/render-template"))
.withDirectory("/template", currentModule.source.directory("templates/" + template))
.withWorkdir("/helper")
.withExec(["go", "build", "-o", "/usr/local/bin/render-template", "."])
.withExec(["render-template", name, "/template", "/rendered"])
.directory("/rendered")
}
"""
Generate every managed Go SDK module visible from the client's current
location: running from a subdirectory generates only the project you're in
and the projects beneath it.
Modules with the generate skip marker are skipped.
"""
generate(ws: Workspace!): Changeset! @generate {
let pws = polyfill.workspace(ws)
changeset.withChangesets(
modules(ws)
.filter { !_.skipGenerate(ws) }
.map { mod =>
# Stage this module's local dependency closure first (leaf-first, possibly
# across SDKs) so its codegen sees up-to-date dependency bindings. The dep
# codegen is ephemeral: taking the changeset against the staged workspace
# cancels it out, leaving only each module's own changes.
let stagedWs = ws.withChanges(
pws.moduleSource("/" + mod.rootPath).core.generateLocalDependencies(ws),
)
polyfill.workspace(stagedWs).moduleSource("/" + mod.rootPath).generate
},
)
}
}