-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathPackageToJSPlugin.swift
583 lines (528 loc) · 25.2 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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#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 struct Foundation.CocoaError
@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") ||
build.logText.contains("-static-stdlib is no longer supported for Apple platforms")
else { return nil }
let didYouMean =
[
"swift", "package", "--swift-sdk", "wasm32-unknown-wasi", "js",
] + arguments
return """
Please pass `--swift-sdk` to "swift package".
Did you mean this?
\(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
"""
}),
(
// In case selected toolchain is a Xcode toolchain, not OSS toolchain
{ build, arguments in
guard build.logText.contains("No available targets are compatible with triple \"wasm32-unknown-wasi\"") else {
return nil
}
return """
The selected toolchain might be an Xcode toolchain, which doesn't support WebAssembly target.
Please use a swift.org Open Source toolchain with WebAssembly support.
See https://book.swiftwasm.org/getting-started/setup.html for more information.
"""
}),
]
private func emitHintMessage(_ message: String) {
printStderr("\n" + "\u{001B}[1m\u{001B}[97mHint:\u{001B}[0m " + message)
}
private func reportBuildFailure(
_ build: PackageManager.BuildResult, _ arguments: [String]
) {
for diagnostic in Self.friendlyBuildDiagnostics {
if let message = diagnostic(build, arguments) {
emitHintMessage(message)
return
}
}
}
func performCommand(context: PluginContext, arguments: [String]) throws {
do {
if arguments.first == "test" {
return try performTestCommand(context: context, arguments: Array(arguments.dropFirst()))
}
return try performBuildCommand(context: context, arguments: arguments)
} catch let error as CocoaError where error.code == .fileWriteNoPermission {
guard let filePath = error.filePath else { throw error }
let packageDir = context.package.directoryURL
printStderr("\n\u{001B}[1m\u{001B}[91merror:\u{001B}[0m \(error.localizedDescription)")
if filePath.hasPrefix(packageDir.path) {
// Emit hint for --allow-writing-to-package-directory if the destination path
// is under the package directory
let didYouMean = [
"swift", "package", "--swift-sdk", "wasm32-unknown-wasi",
"plugin", "--allow-writing-to-package-directory",
"js",
] + arguments
emitHintMessage(
"""
Please pass `--allow-writing-to-package-directory` to "swift package".
Did you mean this?
\(didYouMean.joined(separator: " "))
"""
)
} else {
// Emit hint for --allow-writing-to-directory <directory>
// if the destination path is outside the package directory
let didYouMean = [
"swift", "package", "--swift-sdk", "wasm32-unknown-wasi",
"plugin", "--allow-writing-to-directory", "\(filePath)",
"js",
] + arguments
emitHintMessage(
"""
Please pass `--allow-writing-to-directory <directory>` to "swift package".
Did you mean this?
\(didYouMean.joined(separator: " "))
"""
)
}
exit(1)
}
}
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,
options: buildOptions.packageOptions
)
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,
wasmFilename: productArtifact.lastPathComponent
)
let rootTask = try planner.planBuild(
make: &make, buildOptions: buildOptions)
cleanIfBuildGraphChanged(root: rootTask, make: make, context: context)
print("Packaging...")
let scope = MiniMake.VariableScope(variables: [:])
try make.build(output: rootTask, scope: scope)
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,
options: testOptions.packageOptions
)
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 packageDir = context.package.directoryURL
let path = packageDir.appending(path: ".build/debug/\(productName).\(fileExtension)").path
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,
// If the product artifact doesn't have a .wasm extension, add it
// to deliver it with the correct MIME type when serving the test
// files for browser tests.
wasmFilename: productArtifact.lastPathComponent.hasSuffix(".wasm")
? productArtifact.lastPathComponent
: productArtifact.lastPathComponent + ".wasm"
)
let (rootTask, binDir) = try planner.planTestBuild(
make: &make)
cleanIfBuildGraphChanged(root: rootTask, make: make, context: context)
print("Packaging tests...")
let scope = MiniMake.VariableScope(variables: [:])
try make.build(output: rootTask, scope: scope)
print("Packaging tests finished")
if !testOptions.buildOnly {
let testRunner = scope.resolve(path: binDir.appending(path: "test.js"))
try PackageToJS.runTest(
testRunner: testRunner,
currentDirectoryURL: context.pluginWorkDirectoryURL,
outputDir: outputDir,
testOptions: testOptions
)
}
}
private func buildWasm(productName: String, context: PluginContext, options: PackageToJS.PackageOptions) throws
-> PackageManager.BuildResult
{
var parameters = PackageManager.BuildParameters(
configuration: .inherit,
logging: options.verbose ? .verbose : .concise
)
parameters.echoLogs = true
parameters.otherSwiftcFlags = ["-color-diagnostics"]
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"
]
// Enable code coverage options if requested
if options.enableCodeCoverage {
parameters.otherSwiftcFlags += ["-profile-coverage-mapping", "-profile-generate"]
parameters.otherCFlags += ["-fprofile-instr-generate", "-fcoverage-mapping"]
}
}
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 {
printStderr("Build graph changed, cleaning...")
make.cleanEverything(scope: MiniMake.VariableScope(variables: [:]))
}
try? currentBuildFingerprint?.write(to: buildFingerprint)
}
private func printProgress(context: MiniMake.ProgressPrinter.Context, message: String) {
let buildCwd = FileManager.default.currentDirectoryPath
let outputPath = context.scope.resolve(path: context.subject.output).path
let displayName = outputPath.hasPrefix(buildCwd + "/")
? String(outputPath.dropFirst(buildCwd.count + 1)) : outputPath
printStderr("[\(context.built + 1)/\(context.total)] \(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")
let verbose = extractor.extractFlag(named: "verbose")
let enableCodeCoverage = extractor.extractFlag(named: "enable-code-coverage")
return PackageToJS.PackageOptions(
outputPath: outputPath, packageName: packageName, explain: explain != 0, verbose: verbose != 0, useCDN: useCDN != 0, enableCodeCoverage: enableCodeCoverage != 0
)
}
}
extension PackageToJS.BuildOptions {
static func parse(from extractor: inout ArgumentExtractor) -> PackageToJS.BuildOptions {
let product = extractor.extractOption(named: "product").last
let noOptimize = extractor.extractFlag(named: "no-optimize")
let rawDebugInfoFormat = extractor.extractOption(named: "debug-info-format").last
var debugInfoFormat: PackageToJS.DebugInfoFormat = .none
if let rawDebugInfoFormat = rawDebugInfoFormat {
guard let format = PackageToJS.DebugInfoFormat(rawValue: rawDebugInfoFormat) else {
fatalError("Invalid debug info format: \(rawDebugInfoFormat), expected one of \(PackageToJS.DebugInfoFormat.allCases.map(\.rawValue).joined(separator: ", "))")
}
debugInfoFormat = format
}
let packageOptions = PackageToJS.PackageOptions.parse(from: &extractor)
return PackageToJS.BuildOptions(product: product, noOptimize: noOptimize != 0, debugInfoFormat: debugInfoFormat, 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] js [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
--verbose Whether to print verbose output
--no-optimize Whether to disable wasm-opt optimization
--use-cdn Whether to use CDN for dependency packages
--enable-code-coverage Whether to enable code coverage collection
--debug-info-format The format of debug info to keep in the final wasm file (values: none, dwarf, name; default: none)
SUBCOMMANDS:
test Builds and runs tests
EXAMPLES:
$ swift package --swift-sdk wasm32-unknown-wasi js
# Build a specific product
$ swift package --swift-sdk wasm32-unknown-wasi 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 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 extraNodeArguments = extractor.extractSingleDashOption(named: "Xnode")
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,
extraNodeArguments: extraNodeArguments,
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] js test [options]
OPTIONS:
--build-only Whether to build only
--prelude <path> Path to the prelude script
--environment <name> The environment to use for the tests (values: node, browser; default: node)
--inspect Whether to run tests in the browser with inspector enabled
--explain Whether to explain the build plan
--verbose Whether to print verbose output
--use-cdn Whether to use CDN for dependency packages
--enable-code-coverage Whether to enable code coverage collection
-Xnode <args> Extra arguments to pass to Node.js
EXAMPLES:
$ swift package --swift-sdk wasm32-unknown-wasi js test
$ swift package --swift-sdk wasm32-unknown-wasi js test --environment browser
# Just build tests, don't run them
$ swift package --swift-sdk wasm32-unknown-wasi js test --build-only
$ node .build/plugins/PackageToJS/outputs/PackageTests/bin/test.js
"""
}
}
// MARK: - PackagePlugin helpers
extension ArgumentExtractor {
fileprivate mutating func extractSingleDashOption(named name: String) -> [String] {
let parts = remainingArguments.split(separator: "--", maxSplits: 1, omittingEmptySubsequences: false)
var args = Array(parts[0])
let literals = Array(parts.count == 2 ? parts[1] : [])
var values: [String] = []
var idx = 0
while idx < args.count {
var arg = args[idx]
if arg == "-\(name)" {
args.remove(at: idx)
if idx < args.count {
let val = args[idx]
values.append(val)
args.remove(at: idx)
}
}
else if arg.starts(with: "-\(name)=") {
args.remove(at: idx)
arg.removeFirst(2 + name.count)
values.append(arg)
}
else {
idx += 1
}
}
self = ArgumentExtractor(args + literals)
return values
}
}
/// 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,
wasmFilename: String
) {
let outputBaseName = outputDir.lastPathComponent
let (configuration, triple) = PackageToJS.deriveBuildConfiguration(wasmProductArtifact: wasmProductArtifact)
let system = DefaultPackagingSystem(printWarning: printStderr)
self.init(
options: options,
packageId: context.package.id,
intermediatesDir: BuildPath(absolute: context.pluginWorkDirectoryURL.appending(path: outputBaseName + ".tmp").path),
selfPackageDir: BuildPath(absolute: selfPackage.directoryURL.path),
outputDir: BuildPath(absolute: outputDir.path),
wasmProductArtifact: BuildPath(absolute: wasmProductArtifact.path),
wasmFilename: wasmFilename,
configuration: configuration,
triple: triple,
system: system
)
}
}
#endif