Repository navigation
Expand file tree
/
Copy pathphp-sdk.dang
More file actions
349 lines (320 loc) · 13 KB
/
Copy pathphp-sdk.dang
File metadata and controls
349 lines (320 loc) · 13 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
"""
Manage Dagger modules that use the PHP SDK.
"""
type PhpSdk {
# Matches `"sdk": { "source": "php" }` in a legacy dagger.json.
let legacyConfigPattern = "\"sdk\"\\s*:\\s*\\{[^}]*\"source\"\\s*:\\s*\"php\""
# Matches a `[runtime]` table with `source = "php"` in a CLI 1.0
# dagger-module.toml.
let tomlConfigPattern = "\\[runtime\\][^\\[]*source\\s*=\\s*\"php\""
let moduleConfigFilenames: [String!]! = ["dagger-module.toml", "dagger.json"]
"""
Marker filename that skips generate when found at or above a PHP SDK module root.
"""
pub skipGenerateFilename: String! = ".dagger-php-sdk-skip-generate"
"""
Starter template under templates/<template> for a new module.
"""
pub template: String! = "minimal"
"""
The engine release a module's generated code targets: the floor or later, and
the release this SDK generates for or earlier. Empty takes the release this SDK
generates for.
"""
pub targetVersion: String! = ""
"""
Find the PHP client root containing the workspace cwd: the directory of the
nearest composer.json, relative to the workspace root. A module's vendored
SDK carries its own composer.json under sdk/, so the module owning it answers
instead. Null when there is none.
"""
pub findClientRoot(ws: Workspace!): String {
let found = ws.findUp("composer.json")
if (found == null) {
null
} else {
let root = normalizePath(found.trimSuffix("composer.json"))
let vendorParent = if (root == "sdk") { "." } else { root.trimSuffix("/sdk") }
if (vendorParent != root and hasModuleConfig(ws, vendorParent)) {
vendorParent
} else {
root
}
}
}
"""
Generate one SDK scope: the module at the workspace cwd, when the scope is a
module. A scope without a module config is first seeded from the `template`
setting, keeping the files already there, and given a dagger-module.toml. A
self-contained module then moves to the entrypoint this SDK generates; see
Mod.usesEntrypoint. Module clients are not generated yet.
"""
pub generateScope(ws: Workspace!, isModule: Boolean!, name: String!, clients: [ModuleSource!]!): Workspace! {
checkEngine
if (clients.length > 0) {
raise "php-sdk does not generate module clients yet"
}
if (isModule == false) {
ws
} else {
let scope = normalizePath(ws.cwd)
# Mod.rootPath is workspace-root-relative, so the scope is generated from
# the root and the cwd restored afterwards: the engine rejects a result
# whose cwd is not the scope.
let rooted = ws.withWorkdir(".")
let target = targetRelease("module \"" + name + "\"")
let selectedTemplate = if (template == "") { "minimal" } else { template }
let initialized = if (hasModuleConfig(ws, scope)) {
rooted
} else if (currentModule.source.exists("templates/" + selectedTemplate) == false) {
raise "unknown init template: " + template
} else {
sdkHelpers.moduleManifest
.withName(name: name)
.withLegacyRuntime(runtime: "php", engineVersion: target)
.generate(
rooted.withDirectory(scope, renderedTemplate(name, selectedTemplate)).withWorkdir(scope),
legacyJson: false,
)
.withWorkdir(".")
}
targetedMod(scope, initialized, name, "module \"" + name + "\"").generated.withWorkdir(scope)
}
}
"""
The engine API version a new module declares: the last release before the
identifier-casing cut, which dagger/dagger gates at v1.0.0-beta.26 and which
renames core API fields and changes module naming. It stays before that cut until
the PHP codegen is ported to those rules. Released engines compare base versions,
so older engines load it. The module's client schema, its DAGGER_CLIENT_VERSION
and its dang.toml use this one value. Moving it across that cut also means
checking the naming that sdk/src/Module/EngineNaming.php mirrors.
"""
let targetEngineVersion: String! = "v1.0.0-beta.25"
"""
The oldest release the generated entrypoint passed on, for modules targeting
v1.0.0-beta.21. It has not run again with the current target.
"""
let floorEngineVersion: String! = "v1.0.0-beta.17"
"""
Whether the running engine is below the floor. Released engines compare base
versions, so the manifest's engineVersion does not keep an older v1.0.0
prerelease out. A dev build or a later release is not below it.
"""
let belowEngineFloor: Boolean! {
let prefix = "v1.0.0-beta."
let release = version.split("+")[0] ?? version
let beta = release.trimPrefix(prefix)
let floor = floorEngineVersion.trimPrefix(prefix)
release.hasPrefix("v0.") or release.hasPrefix("v1.0.0-0") or
(beta != release and beta.containsMatch("^[0-9]+$") and beta.padLeft(6) < floor.padLeft(6))
}
let checkEngine: Void {
if (belowEngineFloor) {
raise "php-sdk needs an engine from " + floorEngineVersion + ", and this one is " + version + ": upgrade the engine"
}
null
}
let modAt(path: String!, ws: Workspace!, name: String!, target: String! = targetEngineVersion): Mod! {
Mod(
rootPath: path,
ws: ws,
skipGenerateFilename: skipGenerateFilename,
targetEngineVersion: target,
givenName: name,
)
}
"""
The module at path, generating for targetRelease. A pin on a module that keeps
the PHP runtime is refused: the engine regenerates that module for its
manifest's engineVersion.
"""
let targetedMod(path: String!, ws: Workspace!, name: String!, subject: String!): Mod! {
let target = targetRelease(subject)
let mod = modAt(path, ws, name, target)
if (targetVersion != "" and mod.skipGenerate == false and mod.usesEntrypoint == false) {
raise subject + " pins targetVersion " + target + ", which applies to the generated entrypoint only: this module keeps the PHP runtime, which generates for the engineVersion of its manifest. Remove targetVersion from the scope's settings in dagger.toml"
}
mod
}
"""
The release a module generates for. A targetVersion this SDK cannot generate for
is refused before anything is written.
"""
let targetRelease(subject: String!): String! {
if (targetVersion == "") { return targetEngineVersion }
let fix = "Set targetVersion between " + floorEngineVersion + " and " + targetEngineVersion + " in the scope's settings in dagger.toml, or remove it"
if (targetVersion.containsMatch(Regexp(releasePattern)) == false) {
raise subject + " pins targetVersion " + JSON.encode(targetVersion) + ", which is not a Dagger release such as " + targetEngineVersion + ". " + fix
}
let bare = targetVersion.split("+")[0] ?? targetVersion
let target = if (bare.hasPrefix("v")) { bare } else { "v" + bare }
if (releasePrecedes(target, floorEngineVersion)) {
raise subject + " pins targetVersion " + target + ", which this release of the PHP SDK cannot generate for: it is below " + floorEngineVersion + ", the oldest engine this SDK runs on. " + fix
}
if (releasePrecedes(targetEngineVersion, target)) {
raise subject + " pins targetVersion " + target + ", which this release of the PHP SDK cannot generate for: it targets " + targetEngineVersion + " at most. " + fix + ", or install the SDK release built for " + target
}
target
}
"""v?MAJOR.MINOR.PATCH, then an optional prerelease and build, as in the Go SDK."""
let releasePattern: String! = "^v?([0-9]+)\\.([0-9]+)\\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"
"""Semver precedence; false when either is not a release, so an unreadable version passes."""
let releasePrecedes(a: String!, b: String!): Boolean! {
let pattern = Regexp(releasePattern)
let ma = a.match(pattern)
if (ma == null) { return false }
let mb = b.match(pattern)
if (mb == null) { return false }
let ca = ma.captures
let cb = mb.captures
let coreA = [ca[0] ?? "", ca[1] ?? "", ca[2] ?? ""]
let coreB = [cb[0] ?? "", cb[1] ?? "", cb[2] ?? ""]
if (identifiersPrecede(coreA, coreB, 0)) { return true }
if (identifiersPrecede(coreB, coreA, 0)) { return false }
let preA = ca[3] ?? ""
let preB = cb[3] ?? ""
if (preA == "") {
false
} else if (preB == "") {
true
} else {
identifiersPrecede(preA.split("."), preB.split("."), 0)
}
}
"""Numbers by value before words, words by ASCII, a prefix first."""
let identifiersPrecede(a: [String!]!, b: [String!]!, i: Int!): Boolean! {
if (i >= a.length) { return i < b.length }
if (i >= b.length) { return false }
let x = a[i] ?? ""
let y = b[i] ?? ""
if (x == y) { return identifiersPrecede(a, b, i + 1) }
let xNumber = x.containsMatch(Regexp("^[0-9]+$"))
let yNumber = y.containsMatch(Regexp("^[0-9]+$"))
if (xNumber and yNumber) {
let xDigits = x.split("").length
let yDigits = y.split("").length
if (xDigits == yDigits) { x < y } else { xDigits < yDigits }
} else {
xNumber or (yNumber == false and x < y)
}
}
"""
Whether a module config exists in a workspace-root-relative directory.
"""
let hasModuleConfig(ws: Workspace!, dir: String!): Boolean! {
moduleConfigFilenames.filter { filename =>
let path = if (dir == ".") { filename } else { dir + "/" + filename }
ws.directory("/", include: [path]).exists(path)
}.length > 0
}
let normalizePath(path: String!): String! {
let normalized = path.trimPrefix("./").trimPrefix("/").trimSuffix("/")
if (normalized == "") { "." } else { normalized }
}
"""
Return init templates tracked by this module.
Templates live under templates/<name> and are materialized into a new module
before generation. The `template` setting selects one; empty selects the
default.
"""
pub 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,
)
}
}
}
"""
Return the PHP SDK module at or above a workspace path.
When `findUp` is true, `path` may point inside the module.
"""
pub mod(ws: Workspace!, path: String! = ".", findUp: Boolean! = true): Mod! {
checkEngine
let modPath = if (findUp) {
# Pick the nearest enclosing config regardless of filename ordering.
let foundConfigPath = moduleConfigFilenames.reduce(null) { nearest, filename =>
let found = ws.findUp(filename, path)
if (configHitDepth(found) > configHitDepth(nearest)) { found } else { nearest }
}
if (foundConfigPath == null) {
raise "no Dagger module found containing path: " + path
} else {
let configPath = foundConfigPath.trimPrefix("/")
if (isPhpConfig(ws, configPath) == false) {
raise "Dagger module does not use the PHP SDK: " + path
} else {
let dir = configPath.split("/").dropLast(1).join("/")
if (dir == "") { "." } else { dir }
}
}
} else {
normalizePath(path)
}
targetedMod(modPath, ws, "", "module at " + modPath)
}
"""
Return the depth of the directory containing a find-up result.
"""
let configHitDepth(hit: String): Int! {
if (hit == null) {
-1
} else {
let dir = hit.split("/").dropLast(1).join("/").trimPrefix("/")
if (dir == "") { 0 } else { dir.split("/").length }
}
}
"""
Whether a module config selects the PHP runtime or the entrypoint this SDK
generates.
"""
let isPhpConfig(ws: Workspace!, configPath: String!): Boolean! {
let dir = configPath.split("/").dropLast(1).join("/")
selectsPhpRuntime(ws, configPath) or modAt(if (dir == "") { "." } else { dir }, ws, "").ownsEntrypoint
}
let selectsPhpRuntime(ws: Workspace!, configPath: String!): Boolean! {
let pattern = if (configPath.trimSuffix("dagger-module.toml") != configPath) {
tomlConfigPattern
} else {
legacyConfigPattern
}
ws
.directory("/", include: [configPath])
.file(configPath)
.search(
pattern: pattern,
multiline: true,
dotall: true,
limit: 1,
)
.{{id}}
.length > 0
}
"""
Render a PHP template with the requested module name.
"""
let renderedTemplate(name: String!, templateName: 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/" + templateName))
.withWorkdir("/helper")
.withExec(["go", "build", "-o", "/usr/local/bin/render-template", "."])
.withExec(["render-template", name, "/template", "/rendered"])
.directory("/rendered")
}
}