-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathPackageToJSPlugin.swift
471 lines (425 loc) · 19.9 KB
/
PackageToJSPlugin.swift
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
#if canImport(PackagePlugin)
// Import minimal Foundation APIs to speed up overload resolution
@preconcurrency import struct Foundation.URL
@preconcurrency import struct Foundation.Data
@preconcurrency import class Foundation.Process
@preconcurrency import class Foundation.ProcessInfo
@preconcurrency import class Foundation.FileManager
@preconcurrency import func Foundation.fputs
@preconcurrency import func Foundation.exit
@preconcurrency import var Foundation.stderr
import PackagePlugin
/// The main entry point for the PackageToJS plugin.
@main
struct PackageToJSPlugin: CommandPlugin {
static let friendlyBuildDiagnostics:
[@Sendable (_ build: PackageManager.BuildResult, _ arguments: [String]) -> String?] = [
(
// In case user misses the `--swift-sdk` option
{ build, arguments in
guard
build.logText.contains(
"ld.gold: --export-if-defined=__main_argc_argv: unknown option")
else { return nil }
let didYouMean =
[
"swift", "package", "--swift-sdk", "wasm32-unknown-wasi", "js",
] + arguments
return """
Please pass the `--swift-sdk` option to the "swift package" command.
Did you mean:
\(didYouMean.joined(separator: " "))
"""
}),
(
// In case selected Swift SDK version is not compatible with the Swift compiler version
{ build, arguments in
let regex =
#/module compiled with Swift (?<swiftSDKVersion>\d+\.\d+(?:\.\d+)?) cannot be imported by the Swift (?<compilerVersion>\d+\.\d+(?:\.\d+)?) compiler/#
guard let match = build.logText.firstMatch(of: regex) else { return nil }
let swiftSDKVersion = match.swiftSDKVersion
let compilerVersion = match.compilerVersion
return """
Swift versions mismatch:
- Swift SDK version: \(swiftSDKVersion)
- Swift compiler version: \(compilerVersion)
Please ensure you are using matching versions of the Swift SDK and Swift compiler.
1. Use 'swift --version' to check your Swift compiler version
2. Use 'swift sdk list' to check available Swift SDKs
3. Select a matching SDK version with --swift-sdk option
"""
}),
]
private func reportBuildFailure(
_ build: PackageManager.BuildResult, _ arguments: [String]
) {
for diagnostic in Self.friendlyBuildDiagnostics {
if let message = diagnostic(build, arguments) {
printStderr("\n" + message)
}
}
}
func performCommand(context: PluginContext, arguments: [String]) throws {
if arguments.first == "test" {
return try performTestCommand(context: context, arguments: Array(arguments.dropFirst()))
}
return try performBuildCommand(context: context, arguments: arguments)
}
static let JAVASCRIPTKIT_PACKAGE_ID: Package.ID = "javascriptkit"
func performBuildCommand(context: PluginContext, arguments: [String]) throws {
if arguments.contains(where: { ["-h", "--help"].contains($0) }) {
printStderr(PackageToJS.BuildOptions.help())
return
}
var extractor = ArgumentExtractor(arguments)
let buildOptions = PackageToJS.BuildOptions.parse(from: &extractor)
if extractor.remainingArguments.count > 0 {
printStderr(
"Unexpected arguments: \(extractor.remainingArguments.joined(separator: " "))")
printStderr(PackageToJS.BuildOptions.help())
exit(1)
}
// Build products
let productName = try buildOptions.product ?? deriveDefaultProduct(package: context.package)
let build = try buildWasm(
productName: productName, context: context)
guard build.succeeded else {
reportBuildFailure(build, arguments)
exit(1)
}
let productArtifact = try build.findWasmArtifact(for: productName)
let outputDir =
if let outputPath = buildOptions.packageOptions.outputPath {
URL(fileURLWithPath: outputPath)
} else {
context.pluginWorkDirectoryURL.appending(path: "Package")
}
guard
let selfPackage = findPackageInDependencies(
package: context.package, id: Self.JAVASCRIPTKIT_PACKAGE_ID)
else {
throw PackageToJSError("Failed to find JavaScriptKit in dependencies!?")
}
var make = MiniMake(
explain: buildOptions.packageOptions.explain,
printProgress: self.printProgress
)
let planner = PackagingPlanner(
options: buildOptions.packageOptions, context: context, selfPackage: selfPackage,
outputDir: outputDir, wasmProductArtifact: productArtifact)
let rootTask = try planner.planBuild(
make: &make, buildOptions: buildOptions)
cleanIfBuildGraphChanged(root: rootTask, make: make, context: context)
print("Packaging...")
try make.build(output: rootTask)
print("Packaging finished")
}
func performTestCommand(context: PluginContext, arguments: [String]) throws {
if arguments.contains(where: { ["-h", "--help"].contains($0) }) {
printStderr(PackageToJS.TestOptions.help())
return
}
var extractor = ArgumentExtractor(arguments)
let testOptions = PackageToJS.TestOptions.parse(from: &extractor)
if extractor.remainingArguments.count > 0 {
printStderr(
"Unexpected arguments: \(extractor.remainingArguments.joined(separator: " "))")
printStderr(PackageToJS.TestOptions.help())
exit(1)
}
let productName = "\(context.package.displayName)PackageTests"
let build = try buildWasm(
productName: productName, context: context)
guard build.succeeded else {
reportBuildFailure(build, arguments)
exit(1)
}
// NOTE: Find the product artifact from the default build directory
// because PackageManager.BuildResult doesn't include the
// product artifact for tests.
// This doesn't work when `--scratch-path` is used but
// we don't have a way to guess the correct path. (we can find
// the path by building a dummy executable product but it's
// not worth the overhead)
var productArtifact: URL?
for fileExtension in ["wasm", "xctest"] {
let path = ".build/debug/\(productName).\(fileExtension)"
if FileManager.default.fileExists(atPath: path) {
productArtifact = URL(fileURLWithPath: path)
break
}
}
guard let productArtifact = productArtifact else {
throw PackageToJSError(
"Failed to find '\(productName).wasm' or '\(productName).xctest'")
}
let outputDir =
if let outputPath = testOptions.packageOptions.outputPath {
URL(fileURLWithPath: outputPath)
} else {
context.pluginWorkDirectoryURL.appending(path: "PackageTests")
}
guard
let selfPackage = findPackageInDependencies(
package: context.package, id: Self.JAVASCRIPTKIT_PACKAGE_ID)
else {
throw PackageToJSError("Failed to find JavaScriptKit in dependencies!?")
}
var make = MiniMake(
explain: testOptions.packageOptions.explain,
printProgress: self.printProgress
)
let planner = PackagingPlanner(
options: testOptions.packageOptions, context: context, selfPackage: selfPackage,
outputDir: outputDir, wasmProductArtifact: productArtifact)
let (rootTask, binDir) = try planner.planTestBuild(
make: &make)
cleanIfBuildGraphChanged(root: rootTask, make: make, context: context)
print("Packaging tests...")
try make.build(output: rootTask)
print("Packaging tests finished")
let testRunner = binDir.appending(path: "test.js")
if !testOptions.buildOnly {
var testJsArguments: [String] = []
var testFrameworkArguments: [String] = []
if testOptions.listTests {
testFrameworkArguments += ["--list-tests"]
}
if let prelude = testOptions.prelude {
let preludeURL = URL(fileURLWithPath: prelude, relativeTo: URL(fileURLWithPath: FileManager.default.currentDirectoryPath))
testJsArguments += ["--prelude", preludeURL.path]
}
if let environment = testOptions.environment {
testJsArguments += ["--environment", environment]
}
if testOptions.inspect {
testJsArguments += ["--inspect"]
}
try runTest(
testRunner: testRunner, context: context,
extraArguments: testJsArguments + ["--"] + testFrameworkArguments + testOptions.filter
)
try runTest(
testRunner: testRunner, context: context,
extraArguments: testJsArguments + ["--", "--testing-library", "swift-testing"] + testFrameworkArguments
+ testOptions.filter.flatMap { ["--filter", $0] }
)
}
}
private func runTest(testRunner: URL, context: PluginContext, extraArguments: [String]) throws {
let node = try which("node")
let arguments = ["--experimental-wasi-unstable-preview1", testRunner.path] + extraArguments
print("Running test...")
logCommandExecution(node.path, arguments)
let task = Process()
task.executableURL = node
task.arguments = arguments
task.currentDirectoryURL = context.pluginWorkDirectoryURL
try task.forwardTerminationSignals {
try task.run()
task.waitUntilExit()
}
// swift-testing returns EX_UNAVAILABLE (which is 69 in wasi-libc) for "no tests found"
guard task.terminationStatus == 0 || task.terminationStatus == 69 else {
throw PackageToJSError("Test failed with status \(task.terminationStatus)")
}
}
private func buildWasm(productName: String, context: PluginContext) throws
-> PackageManager.BuildResult
{
var parameters = PackageManager.BuildParameters(
configuration: .inherit,
logging: .concise
)
parameters.echoLogs = true
let buildingForEmbedded =
ProcessInfo.processInfo.environment["JAVASCRIPTKIT_EXPERIMENTAL_EMBEDDED_WASM"].flatMap(
Bool.init) ?? false
if !buildingForEmbedded {
// NOTE: We only support static linking for now, and the new SwiftDriver
// does not infer `-static-stdlib` for WebAssembly targets intentionally
// for future dynamic linking support.
parameters.otherSwiftcFlags = [
"-static-stdlib", "-Xclang-linker", "-mexec-model=reactor",
]
parameters.otherLinkerFlags = [
"--export-if-defined=__main_argc_argv"
]
}
return try self.packageManager.build(.product(productName), parameters: parameters)
}
/// Clean if the build graph of the packaging process has changed
///
/// This is especially important to detect user changes debug/release
/// configurations, which leads to placing the .wasm file in a different
/// path.
private func cleanIfBuildGraphChanged(
root: MiniMake.TaskKey,
make: MiniMake, context: PluginContext
) {
let buildFingerprint = context.pluginWorkDirectoryURL.appending(path: "minimake.json")
let lastBuildFingerprint = try? Data(contentsOf: buildFingerprint)
let currentBuildFingerprint = try? make.computeFingerprint(root: root)
if lastBuildFingerprint != currentBuildFingerprint {
print("Build graph changed, cleaning...")
make.cleanEverything()
}
try? currentBuildFingerprint?.write(to: buildFingerprint)
}
private func printProgress(task: MiniMake.Task, total: Int, built: Int, message: String) {
printStderr("[\(built + 1)/\(total)] \(task.displayName): \(message)")
}
}
private func printStderr(_ message: String) {
fputs(message + "\n", stderr)
}
// MARK: - Options parsing
extension PackageToJS.PackageOptions {
static func parse(from extractor: inout ArgumentExtractor) -> PackageToJS.PackageOptions {
let outputPath = extractor.extractOption(named: "output").last
let packageName = extractor.extractOption(named: "package-name").last
let explain = extractor.extractFlag(named: "explain")
let useCDN = extractor.extractFlag(named: "use-cdn")
return PackageToJS.PackageOptions(
outputPath: outputPath, packageName: packageName, explain: explain != 0, useCDN: useCDN != 0
)
}
}
extension PackageToJS.BuildOptions {
static func parse(from extractor: inout ArgumentExtractor) -> PackageToJS.BuildOptions {
let product = extractor.extractOption(named: "product").last
let splitDebug = extractor.extractFlag(named: "split-debug")
let noOptimize = extractor.extractFlag(named: "no-optimize")
let packageOptions = PackageToJS.PackageOptions.parse(from: &extractor)
return PackageToJS.BuildOptions(product: product, splitDebug: splitDebug != 0, noOptimize: noOptimize != 0, packageOptions: packageOptions)
}
static func help() -> String {
return """
OVERVIEW: Builds a JavaScript module from a Swift package.
USAGE: swift package --swift-sdk <swift-sdk> [SwiftPM options] PackageToJS [options] [subcommand]
OPTIONS:
--product <product> Product to build (default: executable target if there's only one)
--output <path> Path to the output directory (default: .build/plugins/PackageToJS/outputs/Package)
--package-name <name> Name of the package (default: lowercased Package.swift name)
--explain Whether to explain the build plan
--split-debug Whether to split debug information into a separate .wasm.debug file (default: false)
--no-optimize Whether to disable wasm-opt optimization (default: false)
SUBCOMMANDS:
test Builds and runs tests
EXAMPLES:
$ swift package --swift-sdk wasm32-unknown-wasi plugin js
# Build a specific product
$ swift package --swift-sdk wasm32-unknown-wasi plugin js --product Example
# Build in release configuration
$ swift package --swift-sdk wasm32-unknown-wasi -c release plugin js
# Run tests
$ swift package --swift-sdk wasm32-unknown-wasi plugin js test
"""
}
}
extension PackageToJS.TestOptions {
static func parse(from extractor: inout ArgumentExtractor) -> PackageToJS.TestOptions {
let buildOnly = extractor.extractFlag(named: "build-only")
let listTests = extractor.extractFlag(named: "list-tests")
let filter = extractor.extractOption(named: "filter")
let prelude = extractor.extractOption(named: "prelude").last
let environment = extractor.extractOption(named: "environment").last
let inspect = extractor.extractFlag(named: "inspect")
let packageOptions = PackageToJS.PackageOptions.parse(from: &extractor)
var options = PackageToJS.TestOptions(
buildOnly: buildOnly != 0, listTests: listTests != 0,
filter: filter, prelude: prelude, environment: environment, inspect: inspect != 0, packageOptions: packageOptions
)
if !options.buildOnly, !options.packageOptions.useCDN {
options.packageOptions.useCDN = true
}
return options
}
static func help() -> String {
return """
OVERVIEW: Builds and runs tests
USAGE: swift package --swift-sdk <swift-sdk> [SwiftPM options] PackageToJS test [options]
OPTIONS:
--build-only Whether to build only (default: false)
--prelude <path> Path to the prelude script
--environment <name> The environment to use for the tests
--inspect Whether to run tests in the browser with inspector enabled
EXAMPLES:
$ swift package --swift-sdk wasm32-unknown-wasi plugin js test
$ swift package --swift-sdk wasm32-unknown-wasi plugin js test --environment browser
# Just build tests, don't run them
$ swift package --swift-sdk wasm32-unknown-wasi plugin js test --build-only
$ node .build/plugins/PackageToJS/outputs/PackageTests/bin/test.js
"""
}
}
// MARK: - PackagePlugin helpers
/// Derive default product from the package
/// - Returns: The name of the product to build
/// - Throws: `PackageToJSError` if there's no executable product or if there's more than one
internal func deriveDefaultProduct(package: Package) throws -> String {
let executableProducts = package.products(ofType: ExecutableProduct.self)
guard !executableProducts.isEmpty else {
throw PackageToJSError(
"Make sure there's at least one executable product in your Package.swift")
}
guard executableProducts.count == 1 else {
throw PackageToJSError(
"Failed to disambiguate the product. Pass one of \(executableProducts.map(\.name).joined(separator: ", ")) to the --product option"
)
}
return executableProducts[0].name
}
extension PackageManager.BuildResult {
/// Find `.wasm` executable artifact
internal func findWasmArtifact(for product: String) throws -> URL {
let executables = self.builtArtifacts.filter {
($0.kind == .executable) && ($0.url.lastPathComponent == "\(product).wasm")
}
guard !executables.isEmpty else {
throw PackageToJSError(
"Failed to find '\(product).wasm' from executable artifacts of product '\(product)'"
)
}
guard executables.count == 1, let executable = executables.first else {
throw PackageToJSError(
"Failed to disambiguate executable product artifacts from \(executables.map(\.url.path).joined(separator: ", "))"
)
}
return executable.url
}
}
private func findPackageInDependencies(package: Package, id: Package.ID) -> Package? {
var visited: Set<Package.ID> = []
func visit(package: Package) -> Package? {
if visited.contains(package.id) { return nil }
visited.insert(package.id)
if package.id == id { return package }
for dependency in package.dependencies {
if let found = visit(package: dependency.package) {
return found
}
}
return nil
}
return visit(package: package)
}
extension PackagingPlanner {
init(
options: PackageToJS.PackageOptions,
context: PluginContext,
selfPackage: Package,
outputDir: URL,
wasmProductArtifact: URL
) {
self.init(
options: options,
packageId: context.package.id,
pluginWorkDirectoryURL: context.pluginWorkDirectoryURL,
selfPackageDir: selfPackage.directoryURL,
outputDir: outputDir,
wasmProductArtifact: wasmProductArtifact
)
}
}
#endif