forked from swiftlang/swift-package-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPluginTests.swift
1189 lines (1066 loc) · 63.8 KB
/
PluginTests.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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import _Concurrency
@_spi(SwiftPMInternal)
@testable import PackageGraph
import PackageLoading
import PackageModel
@testable import SPMBuildCore
import _InternalTestSupport
import Workspace
import XCTest
final class PluginTests: XCTestCase {
func testUseOfBuildToolPluginTargetByExecutableInSamePackage() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("MySourceGenPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"])
XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build of product 'MyLocalTool' complete!"), "stdout:\n\(stdout)")
}
}
func testUseOfBuildToolPluginTargetNoPreBuildCommands() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (_, stderr) = try await executeSwiftTest(fixturePath.appending("MySourceGenPluginNoPreBuildCommands"))
XCTAssertTrue(stderr.contains("file(s) which are unhandled; explicitly declare them as resources or exclude from the target"), "expected warning not emitted")
}
}
func testUseOfBuildToolPluginProductByExecutableAcrossPackages() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("MySourceGenClient"), configuration: .Debug, extraArgs: ["--product", "MyTool"])
XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking MyTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build of product 'MyTool' complete!"), "stdout:\n\(stdout)")
}
}
func testUseOfPrebuildPluginTargetByExecutableAcrossPackages() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("MySourceGenPlugin"), configuration: .Debug, extraArgs: ["--product", "MyOtherLocalTool"])
XCTAssert(stdout.contains("Compiling MyOtherLocalTool bar.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Compiling MyOtherLocalTool baz.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking MyOtherLocalTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build of product 'MyOtherLocalTool' complete!"), "stdout:\n\(stdout)")
}
}
func testUseOfPluginWithInternalExecutable() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("ClientOfPluginWithInternalExecutable"))
XCTAssert(stdout.contains("Compiling PluginExecutable main.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking PluginExecutable"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Compiling RootTarget foo.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking RootTarget"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)")
}
}
func testInternalExecutableAvailableOnlyToPlugin() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
await XCTAssertThrowsCommandExecutionError(try await executeSwiftBuild(fixturePath.appending("InvalidUseOfInternalPluginExecutable")), "Illegally used internal executable") { error in
XCTAssert(
error.stderr.contains("product 'PluginExecutable' required by package 'invaliduseofinternalpluginexecutable' target 'RootTarget' not found in package 'PluginWithInternalExecutable'."), "stderr:\n\(error.stderr)"
)
}
}
}
func testLocalBuildToolPluginUsingRemoteExecutable() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("LibraryWithLocalBuildToolPluginUsingRemoteTool"))
XCTAssert(stdout.contains("Compiling MySourceGenBuildTool main.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Generating generated.swift from generated.dat"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Compiling MyLibrary generated.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)")
}
}
func testBuildToolPluginDependencies() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("MyBuildToolPluginDependencies"))
XCTAssert(stdout.contains("Compiling MySourceGenBuildTool main.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Compiling MyLocalTool foo.swift"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build complete!"), "stdout:\n\(stdout)")
}
}
func testContrivedTestCases() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("ContrivedTestPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"])
XCTAssert(stdout.contains("Linking MySourceGenBuildTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Generating foo.swift from foo.dat"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build of product 'MyLocalTool' complete!"), "stdout:\n\(stdout)")
}
}
func testPluginScriptSandbox() async throws {
#if !os(macOS)
try XCTSkipIf(true, "test is only supported on macOS")
#endif
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("SandboxTesterPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"])
XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build of product 'MyLocalTool' complete!"), "stdout:\n\(stdout)")
}
}
func testUseOfVendedBinaryTool() async throws {
#if !os(macOS)
try XCTSkipIf(true, "test is only supported on macOS")
#endif
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("MyBinaryToolPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"])
XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build of product 'MyLocalTool' complete!"), "stdout:\n\(stdout)")
}
}
func testUseOfBinaryToolVendedAsProduct() async throws {
#if !os(macOS)
try XCTSkipIf(true, "test is only supported on macOS")
#endif
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins") { fixturePath in
let (stdout, _) = try await executeSwiftBuild(fixturePath.appending("BinaryToolProductPlugin"), configuration: .Debug, extraArgs: ["--product", "MyLocalTool"])
XCTAssert(stdout.contains("Linking MyLocalTool"), "stdout:\n\(stdout)")
XCTAssert(stdout.contains("Build of product 'MyLocalTool' complete!"), "stdout:\n\(stdout)")
}
}
func testBuildToolWithoutOutputs() async throws {
try UserToolchain.default.skipUnlessAtLeastSwift6()
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
func createPackageUnderTest(packageDir: AbsolutePath, toolsVersion: ToolsVersion) throws {
let manifestFile = packageDir.appending("Package.swift")
try localFileSystem.createDirectory(manifestFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
manifestFile,
string: """
// swift-tools-version: \(toolsVersion.description)
import PackageDescription
let package = Package(name: "MyPackage",
targets: [
.target(name: "SomeTarget", plugins: ["Plugin"]),
.plugin(name: "Plugin", capability: .buildTool),
])
""")
let targetSourceFile = packageDir.appending(components: "Sources", "SomeTarget", "dummy.swift")
try localFileSystem.createDirectory(targetSourceFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(targetSourceFile, string: "")
let pluginSourceFile = packageDir.appending(components: "Plugins", "Plugin", "plugin.swift")
try localFileSystem.createDirectory(pluginSourceFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(pluginSourceFile, string: """
import PackagePlugin
@main
struct Plugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
return [
.buildCommand(
displayName: "empty",
executable: .init("/usr/bin/touch"),
arguments: [context.pluginWorkDirectory.appending("best.txt")],
inputFiles: [],
outputFiles: []
)
]
}
}
""")
}
try await testWithTemporaryDirectory { tmpPath in
let packageDir = tmpPath.appending(components: "MyPackage")
let pathOfGeneratedFile = packageDir.appending(components: [".build", "plugins", "outputs", "mypackage", "SomeTarget", "destination", "Plugin", "best.txt"])
try createPackageUnderTest(packageDir: packageDir, toolsVersion: .v5_9)
let (_, stderr) = try await executeSwiftBuild(packageDir, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertTrue(stderr.contains("warning: Build tool command 'empty' (applied to target 'SomeTarget') does not declare any output files"), "expected warning not emitted")
XCTAssertFalse(localFileSystem.exists(pathOfGeneratedFile), "plugin generated file unexpectedly exists at \(pathOfGeneratedFile.pathString)")
try createPackageUnderTest(packageDir: packageDir, toolsVersion: .v6_0)
let (_, stderr2) = try await executeSwiftBuild(packageDir, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertEqual("", stderr2)
XCTAssertTrue(localFileSystem.exists(pathOfGeneratedFile), "plugin did not run, generated file does not exist at \(pathOfGeneratedFile.pathString)")
}
}
func testCommandPluginInvocation() async throws {
try XCTSkipIf(true, "test is disabled because it isn't stable, see rdar://117870608")
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
// FIXME: This test is getting quite long — we should add some support functionality for creating synthetic plugin tests and factor this out into separate tests.
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin. It depends on a sample package.
let packageDir = tmpPath.appending(components: "MyPackage")
let manifestFile = packageDir.appending("Package.swift")
try localFileSystem.createDirectory(manifestFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
manifestFile,
string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(name: "HelperPackage", path: "VendoredDependencies/HelperPackage")
],
targets: [
.target(
name: "MyLibrary",
dependencies: [
.product(name: "HelperLibrary", package: "HelperPackage")
]
),
.plugin(
name: "PluginPrintingInfo",
capability: .command(
intent: .custom(verb: "print-info", description: "Description of the command"),
permissions: [.writeToPackageDirectory(reason: "Reason for wanting to write to package directory")]
)
),
.plugin(
name: "PluginFailingWithError",
capability: .command(
intent: .custom(verb: "fail-with-error", description: "Sample plugin that throws an error")
)
),
.plugin(
name: "PluginFailingWithoutError",
capability: .command(
intent: .custom(verb: "fail-without-error", description: "Sample plugin that exits without error")
)
),
.plugin(
name: "NeverendingPlugin",
capability: .command(
intent: .custom(verb: "neverending-plugin", description: "A plugin that doesn't end running")
)
),
]
)
"""
)
let librarySourceFile = packageDir.appending(components: "Sources", "MyLibrary", "library.swift")
try localFileSystem.createDirectory(librarySourceFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
librarySourceFile,
string: """
public func Foo() { }
"""
)
let printingPluginSourceFile = packageDir.appending(components: "Plugins", "PluginPrintingInfo", "plugin.swift")
try localFileSystem.createDirectory(printingPluginSourceFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
printingPluginSourceFile,
string: """
import PackagePlugin
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Check the identity of the root packages.
print("Root package is \\(context.package.displayName).")
// Check that we can find a tool in the toolchain.
let swiftc = try context.tool(named: "swiftc")
print("Found the swiftc tool at \\(swiftc.path).")
}
}
"""
)
let pluginFailingWithErrorSourceFile = packageDir.appending(components: "Plugins", "PluginFailingWithError", "plugin.swift")
try localFileSystem.createDirectory(pluginFailingWithErrorSourceFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
pluginFailingWithErrorSourceFile,
string: """
import PackagePlugin
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Print some output that should appear before the error diagnostic.
print("This text should appear before the uncaught thrown error.")
// Throw an uncaught error that should be reported as a diagnostics.
throw "This is the uncaught thrown error."
}
}
extension String: Error { }
"""
)
let pluginFailingWithoutErrorSourceFile = packageDir.appending(components: "Plugins", "PluginFailingWithoutError", "plugin.swift")
try localFileSystem.createDirectory(pluginFailingWithoutErrorSourceFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
pluginFailingWithoutErrorSourceFile,
string: """
import PackagePlugin
import Foundation
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Print some output that should appear before we exit.
print("This text should appear before we exit.")
// Just exit with an error code without an emitting error.
exit(1)
}
}
extension String: Error { }
"""
)
let neverendingPluginSourceFile = packageDir.appending(components: "Plugins", "NeverendingPlugin", "plugin.swift")
try localFileSystem.createDirectory(neverendingPluginSourceFile.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
neverendingPluginSourceFile,
string: """
import PackagePlugin
import Foundation
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Print some output that should appear before we exit.
print("This text should appear before we exit.")
// Just exit with an error code without an emitting error.
exit(1)
}
}
extension String: Error { }
"""
)
// Create the sample vendored dependency package.
let library1Path = packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Package.swift")
try localFileSystem.createDirectory(library1Path.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
library1Path,
string: """
// swift-tools-version: 5.5
import PackageDescription
let package = Package(
name: "HelperPackage",
products: [
.library(
name: "HelperLibrary",
targets: ["HelperLibrary"]
),
],
targets: [
.target(
name: "HelperLibrary"
),
]
)
"""
)
let library2Path = packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Sources", "HelperLibrary", "library.swift")
try localFileSystem.createDirectory(library2Path.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
library2Path,
string: """
public func Bar() { }
"""
)
// Load a workspace from the package.
let observability = ObservabilitySystem.makeForTesting()
let workspace = try Workspace(
fileSystem: localFileSystem,
forRootPackage: packageDir,
customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),
delegate: MockWorkspaceDelegate()
)
// Load the root manifest.
let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])
let rootManifests = try await workspace.loadRootManifests(
packages: rootInput.packages,
observabilityScope: observability.topScope
)
XCTAssert(rootManifests.count == 1, "\(rootManifests)")
// Load the package graph.
let packageGraph = try await workspace.loadPackageGraph(
rootInput: rootInput,
observabilityScope: observability.topScope
)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssert(packageGraph.packages.count == 2, "\(packageGraph.packages)")
XCTAssert(packageGraph.rootPackages.count == 1, "\(packageGraph.rootPackages)")
let package = try XCTUnwrap(packageGraph.rootPackages.first)
// Find the regular target in our test package.
let libraryTarget = try XCTUnwrap(package.modules.map(\.underlying).first{ $0.name == "MyLibrary" } as? SwiftModule)
XCTAssertEqual(libraryTarget.type, .library)
// Set up a delegate to handle callbacks from the command plugin.
let delegateQueue = DispatchQueue(label: "plugin-invocation")
class PluginDelegate: PluginInvocationDelegate {
let delegateQueue: DispatchQueue
var diagnostics: [Basics.Diagnostic] = []
init(delegateQueue: DispatchQueue) {
self.delegateQueue = delegateQueue
}
func pluginCompilationStarted(commandLine: [String], environment: [String: String]) {
}
func pluginCompilationEnded(result: PluginCompilationResult) {
}
func pluginCompilationWasSkipped(cachedResult: PluginCompilationResult) {
}
func pluginEmittedOutput(_ data: Data) {
// Add each line of emitted output as a `.info` diagnostic.
dispatchPrecondition(condition: .onQueue(delegateQueue))
let textlines = String(decoding: data, as: UTF8.self).split(whereSeparator: { $0.isNewline })
print(textlines.map{ "[TEXT] \($0)" }.joined(separator: "\n"))
diagnostics.append(contentsOf: textlines.map{
Basics.Diagnostic(severity: .info, message: String($0), metadata: .none)
})
}
func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) {
// Add the diagnostic as-is.
dispatchPrecondition(condition: .onQueue(delegateQueue))
print("[DIAG] \(diagnostic)")
diagnostics.append(diagnostic)
}
func pluginEmittedProgress(_ message: String) {}
}
// Helper function to invoke a plugin with given input and to check its outputs.
func testCommand(
package: ResolvedPackage,
plugin pluginName: String,
modules moduleNames: [String],
arguments: [String],
toolNamesToPaths: [String: AbsolutePath] = [:],
file: StaticString = #file,
line: UInt = #line,
expectFailure: Bool = false,
diagnosticsChecker: (DiagnosticsTestResult) throws -> Void
) async {
// Find the named plugin.
let plugins = package.modules.compactMap{ $0.underlying as? PluginModule }
guard let plugin = plugins.first(where: { $0.name == pluginName }) else {
return XCTFail("There is no plugin target named ‘\(pluginName)’")
}
XCTAssertTrue(plugin.type == .plugin, "Target \(plugin) isn’t a plugin")
// Find the named input targets to the plugin.
var modules: [ResolvedModule] = []
for name in moduleNames {
guard let module = package.modules.first(where: { $0.underlying.name == name }) else {
return XCTFail("There is no target named ‘\(name)’")
}
XCTAssertTrue(module.type != .plugin, "Target \(module) is a plugin")
modules.append(module)
}
let pluginDir = tmpPath.appending(components: package.identity.description, plugin.name)
let delegate = PluginDelegate(delegateQueue: delegateQueue)
do {
let scriptRunner = DefaultPluginScriptRunner(
fileSystem: localFileSystem,
cacheDir: pluginDir.appending("cache"),
toolchain: try UserToolchain.default
)
let toolSearchDirectories = [try UserToolchain.default.swiftCompilerPath.parentDirectory]
let success = try await withCheckedThrowingContinuation { continuation in
plugin.invoke(
action: .performCommand(package: package, arguments: arguments),
buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug),
scriptRunner: scriptRunner,
workingDirectory: package.path,
outputDirectory: pluginDir.appending("output"),
toolSearchDirectories: toolSearchDirectories,
accessibleTools: [:],
writableDirectories: [pluginDir.appending("output")],
readOnlyDirectories: [package.path],
allowNetworkConnections: [],
pkgConfigDirectories: [],
sdkRootPath: nil,
fileSystem: localFileSystem,
modulesGraph: packageGraph,
observabilityScope: observability.topScope,
callbackQueue: delegateQueue,
delegate: delegate,
completion: {
continuation.resume(with: $0)
}
)
}
if expectFailure {
XCTAssertFalse(success, "expected command to fail, but it succeeded", file: file, line: line)
}
else {
XCTAssertTrue(success, "expected command to succeed, but it failed", file: file, line: line)
}
}
catch {
XCTFail("error \(String(describing: error))", file: file, line: line)
}
// Check that we didn't end up with any completely empty diagnostics.
XCTAssertNil(observability.diagnostics.first{ $0.message.isEmpty })
// Invoke the diagnostics checker for the plugin output.
testDiagnostics(delegate.diagnostics, problemsOnly: false, file: file, line: line, handler: diagnosticsChecker)
}
// Invoke the command plugin that prints out various things it was given, and check them.
await testCommand(package: package, plugin: "PluginPrintingInfo", modules: ["MyLibrary"], arguments: ["veni", "vidi", "vici"]) { output in
output.check(diagnostic: .equal("Root package is MyPackage."), severity: .info)
output.check(diagnostic: .and(.prefix("Found the swiftc tool"), .suffix(".")), severity: .info)
}
// Invoke the command plugin that throws an unhandled error at the top level.
await testCommand(package: package, plugin: "PluginFailingWithError", modules: [], arguments: [], expectFailure: true) { output in
output.check(diagnostic: .equal("This text should appear before the uncaught thrown error."), severity: .info)
output.check(diagnostic: .equal("This is the uncaught thrown error."), severity: .error)
}
// Invoke the command plugin that exits with code 1 without returning an error.
await testCommand(package: package, plugin: "PluginFailingWithoutError", modules: [], arguments: [], expectFailure: true) { output in
output.check(diagnostic: .equal("This text should appear before we exit."), severity: .info)
output.check(diagnostic: .equal("Plugin ended with exit code 1"), severity: .error)
}
}
}
func testLocalAndRemoteToolDependencies() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool") { path in
let (stdout, stderr) = try await executeSwiftPackage(path.appending("MyLibrary"), configuration: .Debug, extraArgs: ["plugin", "my-plugin"])
XCTAssert(stderr.contains("Linking RemoteTool"), "stdout:\n\(stderr)\n\(stdout)")
XCTAssert(stderr.contains("Linking LocalTool"), "stdout:\n\(stderr)\n\(stdout)")
XCTAssert(stderr.contains("Linking ImpliedLocalTool"), "stdout:\n\(stderr)\n\(stdout)")
XCTAssert(stderr.contains("Build of product 'ImpliedLocalTool' complete!"), "stdout:\n\(stderr)\n\(stdout)")
XCTAssert(stdout.contains("A message from the remote tool."), "stdout:\n\(stderr)\n\(stdout)")
XCTAssert(stdout.contains("A message from the local tool."), "stdout:\n\(stderr)\n\(stdout)")
XCTAssert(stdout.contains("A message from the implied local tool."), "stdout:\n\(stderr)\n\(stdout)")
}
}
func testPluginUsageDoesntAffectTestTargetMappings() async throws {
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins/MySourceGenPlugin") { packageDir in
// Load a workspace from the package.
let observability = ObservabilitySystem.makeForTesting()
let workspace = try Workspace(
fileSystem: localFileSystem,
forRootPackage: packageDir,
customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),
delegate: MockWorkspaceDelegate()
)
// Load the root manifest.
let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])
let rootManifests = try await workspace.loadRootManifests(
packages: rootInput.packages,
observabilityScope: observability.topScope
)
XCTAssert(rootManifests.count == 1, "\(rootManifests)")
// Load the package graph.
let packageGraph = try await workspace.loadPackageGraph(
rootInput: rootInput,
observabilityScope: observability.topScope
)
XCTAssertNoDiagnostics(observability.diagnostics)
// Make sure that the use of plugins doesn't bleed into the use of plugins by tools.
let testTargetMappings = try packageGraph.computeTestModulesForExecutableModules()
for (target, testTargets) in testTargetMappings {
XCTAssertFalse(testTargets.contains{ $0.name == "MySourceGenPluginTests" }, "target: \(target), testTargets: \(testTargets)")
}
}
}
func testCommandPluginCancellation() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { (tmpPath: AbsolutePath) -> Void in
// Create a sample package with a couple of plugins a other targets and products.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(
packageDir.appending(components: "Package.swift"),
string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.library(
name: "MyLibrary",
targets: ["MyLibrary"]
),
],
targets: [
.target(
name: "MyLibrary"
),
.plugin(
name: "NeverendingPlugin",
capability: .command(
intent: .custom(verb: "neverending-plugin", description: "Help description")
)
),
]
)
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(
myLibraryTargetDir.appending("library.swift"),
string: """
public func GetGreeting() -> String { return "Hello" }
"""
)
let neverendingPluginTargetDir = packageDir.appending(components: "Plugins", "NeverendingPlugin")
try localFileSystem.createDirectory(neverendingPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(
neverendingPluginTargetDir.appending("plugin.swift"),
string: """
import PackagePlugin
import Foundation
@main struct NeverendingPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
print("pid: \\(ProcessInfo.processInfo.processIdentifier)")
while true {
Thread.sleep(forTimeInterval: 1.0)
print("still here")
}
}
}
"""
)
// Load a workspace from the package.
let observability = ObservabilitySystem.makeForTesting()
let workspace = try Workspace(
fileSystem: localFileSystem,
forRootPackage: packageDir,
customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),
delegate: MockWorkspaceDelegate()
)
// Load the root manifest.
let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])
let rootManifests = try await workspace.loadRootManifests(
packages: rootInput.packages,
observabilityScope: observability.topScope
)
XCTAssert(rootManifests.count == 1, "\(rootManifests)")
// Load the package graph.
let packageGraph = try await workspace.loadPackageGraph(
rootInput: rootInput,
observabilityScope: observability.topScope
)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssert(packageGraph.packages.count == 1, "\(packageGraph.packages)")
XCTAssert(packageGraph.rootPackages.count == 1, "\(packageGraph.rootPackages)")
let package: ResolvedPackage = try XCTUnwrap(packageGraph.rootPackages.first)
// Find the regular target in our test package.
let libraryTarget = try XCTUnwrap(
package.modules
.map(\.underlying)
.first{ $0.name == "MyLibrary" } as? SwiftModule
)
XCTAssertEqual(libraryTarget.type, .library)
// Set up a delegate to handle callbacks from the command plugin. In particular we want to know the process identifier.
let delegateQueue = DispatchQueue(label: "plugin-invocation")
class PluginDelegate: PluginInvocationDelegate {
let delegateQueue: DispatchQueue
var diagnostics: [Basics.Diagnostic] = []
var parsedProcessIdentifier: Int? = .none
init(delegateQueue: DispatchQueue) {
self.delegateQueue = delegateQueue
}
func pluginCompilationStarted(commandLine: [String], environment: [String: String]) {
}
func pluginCompilationEnded(result: PluginCompilationResult) {
}
func pluginCompilationWasSkipped(cachedResult: PluginCompilationResult) {
}
func pluginEmittedOutput(_ data: Data) {
// Add each line of emitted output as a `.info` diagnostic.
dispatchPrecondition(condition: .onQueue(delegateQueue))
let textlines = String(decoding: data, as: UTF8.self).split(whereSeparator: { $0.isNewline })
diagnostics.append(contentsOf: textlines.map{
Basics.Diagnostic(severity: .info, message: String($0), metadata: .none)
})
// If we don't already have the process identifier, we try to find it.
if parsedProcessIdentifier == .none {
func parseProcessIdentifier(_ string: String) -> Int? {
guard let match = try? NSRegularExpression(pattern: "pid: (\\d+)", options: []).firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)) else { return .none }
// We have a match, so extract the process identifier.
assert(match.numberOfRanges == 2)
return Int((string as NSString).substring(with: match.range(at: 1)))
}
parsedProcessIdentifier = textlines.compactMap{ parseProcessIdentifier(String($0)) }.first
}
}
func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) {
// Add the diagnostic as-is.
dispatchPrecondition(condition: .onQueue(delegateQueue))
diagnostics.append(diagnostic)
}
func pluginEmittedProgress(_ message: String) {}
}
// Find the relevant plugin.
let plugins = package.modules.compactMap { $0.underlying as? PluginModule }
guard let plugin = plugins.first(where: { $0.name == "NeverendingPlugin" }) else {
return XCTFail("There is no plugin target named ‘NeverendingPlugin’")
}
XCTAssertTrue(plugin.type == .plugin, "Target \(plugin) isn’t a plugin")
// Run the plugin.
let pluginDir = tmpPath.appending(components: package.identity.description, plugin.name)
let scriptRunner = DefaultPluginScriptRunner(
fileSystem: localFileSystem,
cacheDir: pluginDir.appending("cache"),
toolchain: try UserToolchain.default
)
let delegate = PluginDelegate(delegateQueue: delegateQueue)
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask {
// TODO: have invoke natively support task cancellation instead
try await withTaskCancellationHandler {
_ = try await plugin.invoke(
action: .performCommand(package: package, arguments: []),
buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug),
scriptRunner: scriptRunner,
workingDirectory: package.path,
outputDirectory: pluginDir.appending("output"),
toolSearchDirectories: [try UserToolchain.default.swiftCompilerPath.parentDirectory],
accessibleTools: [:],
writableDirectories: [pluginDir.appending("output")],
readOnlyDirectories: [package.path],
allowNetworkConnections: [],
pkgConfigDirectories: [],
sdkRootPath: try UserToolchain.default.sdkRootPath,
fileSystem: localFileSystem,
modulesGraph: packageGraph,
observabilityScope: observability.topScope,
callbackQueue: delegateQueue,
delegate: delegate
)
} onCancel: {
do {
try scriptRunner.cancel(deadline: .now() + .seconds(5))
} catch {
XCTFail("Cancelling script runner should not fail: \(error)")
}
}
}
group.addTask {
do {
try await Task.sleep(nanoseconds: UInt64(DispatchTimeInterval.seconds(3).nanoseconds()!))
} catch {
XCTFail("The plugin should not finish within 3 seconds")
}
}
try await group.next()
// At this point we should have parsed out the process identifier. But it's possible we don't always — this is being investigated in rdar://88792829.
var pid: Int? = .none
delegateQueue.sync {
pid = delegate.parsedProcessIdentifier
}
guard let pid else {
throw XCTSkip("skipping test because no pid was received from the plugin; being investigated as rdar://88792829\n\(delegate.diagnostics.description)")
}
// Check that it's running (we do this by asking for its priority — this only works on some platforms).
#if os(macOS)
errno = 0
getpriority(Int32(PRIO_PROCESS), UInt32(pid))
XCTAssertEqual(errno, 0, "unexpectedly got errno \(errno) when trying to check process \(pid)")
#endif
// Ask the plugin running to cancel all plugins.
group.cancelAll()
// Check that it's no longer running (we do this by asking for its priority — this only works on some platforms).
#if os(macOS)
errno = 0
getpriority(Int32(PRIO_PROCESS), UInt32(pid))
XCTAssertEqual(errno, ESRCH, "unexpectedly got errno \(errno) when trying to check process \(pid)")
#endif
}
}
}
func testUnusedPluginProductWarnings() async throws {
// Test the warnings we get around unused plugin products in package dependencies.
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package that uses three packages that vend plugins.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(
packageDir.appending("Package.swift"),
string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(name: "BuildToolPluginPackage", path: "VendoredDependencies/BuildToolPluginPackage"),
.package(name: "UnusedBuildToolPluginPackage", path: "VendoredDependencies/UnusedBuildToolPluginPackage"),
.package(name: "CommandPluginPackage", path: "VendoredDependencies/CommandPluginPackage")
],
targets: [
.target(
name: "MyLibrary",
path: ".",
plugins: [
.plugin(name: "BuildToolPlugin", package: "BuildToolPluginPackage")
]
),
]
)
"""
)
try localFileSystem.writeFileContents(
packageDir.appending("Library.swift"),
string: """
public var Foo: String
"""
)
// Create the depended-upon package that vends a build tool plugin that is used by the main package.
let buildToolPluginPackageDir = packageDir.appending(components: "VendoredDependencies", "BuildToolPluginPackage")
try localFileSystem.createDirectory(buildToolPluginPackageDir, recursive: true)
try localFileSystem.writeFileContents(
buildToolPluginPackageDir.appending("Package.swift"),
string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "BuildToolPluginPackage",
products: [
.plugin(
name: "BuildToolPlugin",
targets: ["BuildToolPlugin"])
],
targets: [
.plugin(
name: "BuildToolPlugin",
capability: .buildTool(),
path: ".")
]
)
"""
)
try localFileSystem.writeFileContents(
buildToolPluginPackageDir.appending("Plugin.swift"),
string: """
import PackagePlugin
@main struct MyPlugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
return []
}
}
"""
)
// Create the depended-upon package that vends a build tool plugin that is not used by the main package.
let unusedBuildToolPluginPackageDir = packageDir.appending(components: "VendoredDependencies", "UnusedBuildToolPluginPackage")
try localFileSystem.createDirectory(unusedBuildToolPluginPackageDir, recursive: true)
try localFileSystem.writeFileContents(
unusedBuildToolPluginPackageDir.appending("Package.swift"),
string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "UnusedBuildToolPluginPackage",
products: [
.plugin(
name: "UnusedBuildToolPlugin",
targets: ["UnusedBuildToolPlugin"])
],
targets: [
.plugin(
name: "UnusedBuildToolPlugin",
capability: .buildTool(),
path: ".")
]
)
"""
)
try localFileSystem.writeFileContents(
unusedBuildToolPluginPackageDir.appending("Plugin.swift"),
string: """
import PackagePlugin
@main struct MyPlugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
return []
}
}
"""
)
// Create the depended-upon package that vends a command plugin.