forked from swiftlang/swift-package-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPIFBuilderTests.swift
More file actions
1115 lines (1018 loc) · 48.7 KB
/
PIFBuilderTests.swift
File metadata and controls
1115 lines (1018 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
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) 2025 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 Testing
import PackageGraph
import PackageLoading
import PackageModel
import SPMBuildCore
import SwiftBuild
import SwiftBuildSupport
import _InternalTestSupport
import Workspace
@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly) import PackageGraph
// MARK: - Helpers
extension PIFBuilderParameters {
static func constructDefaultParametersForTesting(
temporaryDirectory: Basics.AbsolutePath,
addLocalRpaths: Bool,
shouldCreateDylibForDynamicProducts: Bool = false,
pluginScriptRunner: PluginScriptRunner? = nil
) throws -> Self {
try self.init(
isPackageAccessModifierSupported: true,
enableTestability: false,
shouldCreateDylibForDynamicProducts: shouldCreateDylibForDynamicProducts,
materializeStaticArchiveProductsForRootPackages: true,
createDynamicVariantsForLibraryProducts: false,
toolchainLibDir: temporaryDirectory.appending(component: "toolchain-lib-dir"),
pkgConfigDirectories: [],
supportedSwiftVersions: [.v4, .v4_2, .v5, .v6],
pluginScriptRunner: pluginScriptRunner ?? DefaultPluginScriptRunner(
fileSystem: localFileSystem,
cacheDir: temporaryDirectory.appending(component: "plugin-cache-dir"),
toolchain: try UserToolchain.default
),
disableSandbox: false,
pluginWorkingDirectory: temporaryDirectory.appending(component: "plugin-working-dir"),
additionalFileRules: [],
addLocalRPaths: addLocalRpaths
)
}
}
fileprivate func withGeneratedPIF(
fromFixture fixtureName: String,
addLocalRpaths: Bool = true,
shouldCreateDylibForDynamicProducts: Bool = true,
buildParameters: BuildParameters? = nil,
hostBuildParameters: BuildParameters? = nil,
do doIt: (SwiftBuildSupport.PIF.TopLevelObject, TestingObservability) async throws -> ()
) async throws {
let buildParameters = if let buildParameters {
buildParameters
} else {
mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)
}
let hostBuildParameters = if let hostBuildParameters {
hostBuildParameters
} else {
mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)
}
try await fixture(name: fixtureName) { fixturePath in
let observabilitySystem: TestingObservability = ObservabilitySystem.makeForTesting(verbose: false)
let toolchain = try UserToolchain.default
var config = WorkspaceConfiguration.default
config.shouldCreateMultipleTestProducts = true
let workspace = try Workspace(
fileSystem: localFileSystem,
forRootPackage: fixturePath,
configuration: config,
customManifestLoader: ManifestLoader(toolchain: toolchain),
delegate: MockWorkspaceDelegate()
)
let rootInput = PackageGraphRootInput(packages: [fixturePath], dependencies: [])
let graph = try await workspace.loadPackageGraph(
rootInput: rootInput,
observabilityScope: observabilitySystem.topScope
)
let builder = PIFBuilder(
graph: graph,
parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(
temporaryDirectory: fixturePath,
addLocalRpaths: addLocalRpaths,
shouldCreateDylibForDynamicProducts: shouldCreateDylibForDynamicProducts
),
fileSystem: localFileSystem,
observabilityScope: observabilitySystem.topScope
)
let pif = try await builder.constructPIF(
buildParameters: buildParameters,
hostBuildParameters: hostBuildParameters
)
try await doIt(pif, observabilitySystem)
}
}
extension SwiftBuildSupport.PIF.Workspace {
fileprivate func project(named name: String) throws -> SwiftBuildSupport.PIF.Project {
let matchingProjects = projects.filter {
$0.underlying.name == name
}
if matchingProjects.isEmpty {
throw StringError("No project named \(name) in PIF workspace")
} else if matchingProjects.count > 1 {
throw StringError("Multiple projects named \(name) in PIF workspace")
} else {
return matchingProjects[0]
}
}
}
extension SwiftBuildSupport.PIF.Project {
fileprivate func target(id: String) throws -> ProjectModel.BaseTarget {
let matchingTargets: [ProjectModel.BaseTarget] = underlying.targets.filter {
return $0.common.id.value == String(id)
}
if matchingTargets.isEmpty {
throw StringError("No target named \(id) in PIF project")
} else if matchingTargets.count > 1 {
throw StringError("Multiple target named \(id) in PIF project")
} else {
return matchingTargets[0]
}
}
fileprivate func target(named name: String) throws -> ProjectModel.BaseTarget {
let matchingTargets = underlying.targets.filter {
$0.common.name == name
}
switch matchingTargets.count {
case 0:
throw StringError("No target named \(name) in PIF project")
case 1:
return matchingTargets[0]
case 2:
if let nonDynamicVariant = matchingTargets.filter({ !$0.id.value.hasSuffix("-dynamic") }).only {
return nonDynamicVariant
} else {
fallthrough
}
default:
throw StringError("Multiple targets named \(name) in PIF project")
}
}
fileprivate func buildConfig(named name: BuildConfiguration) throws -> SwiftBuild.ProjectModel.BuildConfig {
let matchingConfigs = underlying.buildConfigs.filter {
$0.name == name.pifConfiguration
}
if matchingConfigs.isEmpty {
throw StringError("No config named \(name) in PIF project")
} else if matchingConfigs.count > 1 {
throw StringError("Multiple configs named \(name) in PIF project")
} else {
return matchingConfigs[0]
}
}
}
extension SwiftBuild.ProjectModel.BaseTarget {
fileprivate func buildConfig(named name: BuildConfiguration) throws -> SwiftBuild.ProjectModel.BuildConfig {
let matchingConfigs = common.buildConfigs.filter {
$0.name == name.pifConfiguration
}
if matchingConfigs.isEmpty {
throw StringError("No config named \(name) in PIF target")
} else if matchingConfigs.count > 1 {
throw StringError("Multiple configs named \(name) in PIF target")
} else {
return matchingConfigs[0]
}
}
}
extension BuildConfiguration {
var pifConfiguration: String {
switch self {
case .debug, .release: self.rawValue.capitalized
}
}
}
// MARK: - Tests
@Suite(
.tags(
.TestSize.medium,
.FunctionalArea.PIF
)
)
struct PIFBuilderTests {
struct RootPackagesTestData {
let id: String
let rootPackages: [(name: String, path: Basics.AbsolutePath)]
let expectedData: (pifPath: Basics.AbsolutePath, pifName: String, pifId: String)
}
@Test(
arguments:[
RootPackagesTestData(
id: "Single root package, package path at root",
rootPackages: [
(name: "fooPackage", path: AbsolutePath("/fooPackage")),
],
expectedData: (
pifPath: "/fooPackage",
pifName: "fooPackage",
pifId: "/fooPackage",
),
),
RootPackagesTestData(
id: "Single root package, package path nested ",
rootPackages: [
(name: "fooPackage", path: AbsolutePath("/a/b/c/d/fooPackage")),
],
expectedData: (
pifPath: "/a/b/c/d/fooPackage",
pifName: "fooPackage",
pifId: "/a/b/c/d/fooPackage",
),
),
RootPackagesTestData(
id: "Two root packages, unordered, no common parent directory",
rootPackages: [
(name: "fooPackage", path: AbsolutePath("/fooPackage")),
(name: "barPackage", path: AbsolutePath("/barPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath.root,
pifName: "barPackage,fooPackage",
pifId: "/barPackage,/fooPackage",
),
),
RootPackagesTestData(
id: "Two root packages, ordered, no common parent directory",
rootPackages: [
(name: "barPackage", path: AbsolutePath("/barPackage")),
(name: "fooPackage", path: AbsolutePath("/fooPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath.root,
pifName: "barPackage,fooPackage",
pifId: "/barPackage,/fooPackage",
),
),
RootPackagesTestData(
id: "Two root packages, unordered, no common parent directory",
rootPackages: [
(name: "fooPackage", path: AbsolutePath("/fooPackage")),
(name: "barPackage", path: AbsolutePath("/barPackage")),
(name: "bazPackage", path: AbsolutePath("/bazPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath.root,
pifName: "barPackage,bazPackage,fooPackage",
pifId: "/barPackage,/bazPackage,/fooPackage",
),
),
RootPackagesTestData(
id: "Multiple root packages, ordered, no common parent directory",
rootPackages: [
(name: "barPackage", path: AbsolutePath("/barPackage")),
(name: "bazPackage", path: AbsolutePath("/bazPackage")),
(name: "fooPackage", path: AbsolutePath("/fooPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath.root,
pifName: "barPackage,bazPackage,fooPackage",
pifId: "/barPackage,/bazPackage,/fooPackage",
),
),
RootPackagesTestData(
id: "Two root packages, unordered, contains common directory, packages are sibling",
rootPackages: [
(name: "fooPackage", path: AbsolutePath("/a/b/c/fooPackage")),
(name: "barPackage", path: AbsolutePath("/a/b/c/barPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath("/a/b/c"),
pifName: "barPackage,fooPackage",
pifId: "/a/b/c/barPackage,/a/b/c/fooPackage",
),
),
RootPackagesTestData(
id: "Two root packages, ordered, contains common directory, packages are sibling",
rootPackages: [
(name: "barPackage", path: AbsolutePath("/a/b/c/barPackage")),
(name: "fooPackage", path: AbsolutePath("/a/b/c/fooPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath("/a/b/c"),
pifName: "barPackage,fooPackage",
pifId: "/a/b/c/barPackage,/a/b/c/fooPackage",
),
),
RootPackagesTestData(
id: "Two root packages, ybordered, contains common directory, packages are not siblings",
rootPackages: [
(name: "fooPackage", path: AbsolutePath("/a/b/c/pink/fuzz/fooPackage")),
(name: "barPackage", path: AbsolutePath("/a/b/c/absolute/zero/barPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath("/a/b/c"),
pifName: "barPackage,fooPackage",
pifId: "/a/b/c/absolute/zero/barPackage,/a/b/c/pink/fuzz/fooPackage",
),
),
RootPackagesTestData(
id: "Two root packages, ordered, contains common directory, packages are not siblings",
rootPackages: [
(name: "barPackage", path: AbsolutePath("/a/b/c/absolute/zero/barPackage")),
(name: "fooPackage", path: AbsolutePath("/a/b/c/pink/fuzz/fooPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath("/a/b/c"),
pifName: "barPackage,fooPackage",
pifId: "/a/b/c/absolute/zero/barPackage,/a/b/c/pink/fuzz/fooPackage",
),
),
RootPackagesTestData(
id: "Many root packages, unordered, contains common directory, packages are not siblings",
rootPackages: [
(name: "fooPackage", path: AbsolutePath("/a/b/c/pink/fuzz/fooPackage")),
(name: "barPackage", path: AbsolutePath("/a/b/c/absolute/zero/barPackage")),
(name: "bazPackage", path: AbsolutePath("/a/b/c/absolute/legend/bazPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath("/a/b/c"),
pifName: "barPackage,bazPackage,fooPackage",
pifId: "/a/b/c/absolute/zero/barPackage,/a/b/c/absolute/legend/bazPackage,/a/b/c/pink/fuzz/fooPackage",
),
),
RootPackagesTestData(
id: "Many root packages, ordered, contains common directory, packages are not siblings",
rootPackages: [
(name: "barPackage", path: AbsolutePath("/a/b/c/absolute/zero/barPackage")),
(name: "bazPackage", path: AbsolutePath("/a/b/c/absolute/legend/bazPackage")),
(name: "fooPackage", path: AbsolutePath("/a/b/c/pink/fuzz/fooPackage")),
],
expectedData: (
pifPath: Basics.AbsolutePath("/a/b/c"),
pifName: "barPackage,bazPackage,fooPackage",
pifId: "/a/b/c/absolute/zero/barPackage,/a/b/c/absolute/legend/bazPackage,/a/b/c/pink/fuzz/fooPackage",
),
),
],
)
func multipleRootPackages(
testData: RootPackagesTestData,
) async throws {
// Arrange
try #require(testData.rootPackages.count >= 1, "Test configuration data error. No root packages are specified.")
let fs = InMemoryFileSystem()
let observabilityScope = ObservabilitySystem.makeForTesting()
let graph = try loadModulesGraph(
fileSystem: fs,
manifests: testData.rootPackages.map { rootPackage in
Manifest.createRootManifest(
displayName: rootPackage.name,
path: rootPackage.path,
products: [],
targets: [],
)
},
observabilityScope: observabilityScope.topScope
)
let pifBuilder = PIFBuilder(
graph: graph,
parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(
temporaryDirectory: AbsolutePath.root.appending("tmp"),
addLocalRpaths: true,
),
fileSystem: fs,
observabilityScope: observabilityScope.topScope,
)
// Act
let pif = try await pifBuilder.constructPIF(
buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild),
hostBuildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)
)
// Assert
#expect(
pif.workspace.path == testData.expectedData.pifPath,
"Actual path is not as expected",
)
#expect(
pif.workspace.name == testData.expectedData.pifName,
"Actual pif name is not as expected",
)
}
@Test func platformExecutableModuleLibrarySearchPath() async throws {
try await withGeneratedPIF(fromFixture: "PIFBuilder/BasicExecutable") { pif, observabilitySystem in
let releaseConfig = try pif.workspace
.project(named: "BasicExecutable")
.target(named: "Executable")
.buildConfig(named: .release)
for platform in ProjectModel.BuildSettings.Platform.allCases {
let search_paths = releaseConfig.impartedBuildProperties.settings[.LIBRARY_SEARCH_PATHS, platform]
switch platform {
case .macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .xrOS, .driverKit, .freebsd, .android, .linux, .wasi, .openbsd, ._iOSDevice:
#expect(search_paths == nil, "for platform \(platform)")
case .windows:
#expect(search_paths == ["$(inherited)", "$(TARGET_BUILD_DIR)/ExecutableModules"], "for platform \(platform)")
}
}
}
}
@Test func platformConditionBasics() async throws {
try await withGeneratedPIF(fromFixture: "PIFBuilder/UnknownPlatforms") { pif, observabilitySystem in
// We should emit a warning to the PIF log about the unknown platform
#expect(observabilitySystem.diagnostics.filter {
$0.severity == .warning && $0.message.contains("Ignoring settings assignments for unknown platform 'DoesNotExist'")
}.count > 0)
let releaseConfig = try pif.workspace
.project(named: "UnknownPlatforms")
.target(named: "UnknownPlatforms")
.buildConfig(named: .release)
// The platforms with conditional settings should have those propagated to the PIF.
#expect(releaseConfig.settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, .linux] == ["$(inherited)", "BAR"])
#expect(releaseConfig.settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, .macOS] == ["$(inherited)", "BAZ"])
#expect(releaseConfig.settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, .windows] == nil)
}
}
@Test func platformCCLibrary() async throws {
try await withGeneratedPIF(fromFixture: "PIFBuilder/CCPackage") { pif, observabilitySystem in
let releaseConfig = try pif.workspace
.project(named: "CCPackage")
.target(id: "PACKAGE-TARGET:CCTarget")
.buildConfig(named: .release)
for platform in ProjectModel.BuildSettings.Platform.allCases {
let ld_flags = releaseConfig.impartedBuildProperties.settings[.OTHER_LDFLAGS, platform]
switch platform {
case .macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .xrOS, .driverKit, .freebsd:
#expect(ld_flags == ["-lc++", "$(inherited)"], "for platform \(platform)")
case .android, .linux, .wasi, .openbsd:
#expect(ld_flags == ["-lstdc++", "$(inherited)"], "for platform \(platform)")
case .windows, ._iOSDevice:
#expect(ld_flags == nil, "for platform \(platform)")
}
}
}
}
@Test func packageWithInternal() async throws {
try await withGeneratedPIF(fromFixture: "PIFBuilder/PackageWithSDKSpecialization") { pif, observabilitySystem in
let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }
#expect(errors.isEmpty, "Expected no errors during PIF generation, but got: \(errors)")
let releaseConfig = try pif.workspace
.project(named: "PackageWithSDKSpecialization")
.buildConfig(named: .release)
#expect(releaseConfig.settings[.SPECIALIZATION_SDK_OPTIONS, .macOS] == ["foo"])
}
}
@Test func pluginWithBinaryTargetDependency() async throws {
try await withGeneratedPIF(fromFixture: "Miscellaneous/Plugins/BinaryTargetExePlugin") { pif, observabilitySystem in
// Verify that PIF generation succeeds for a package with a plugin that depends on a binary target
#expect(pif.workspace.projects.count > 0)
let project = try pif.workspace.project(named: "MyBinaryTargetExePlugin")
// Verify the plugin target exists
let pluginTarget = try project.target(named: "MyPlugin")
#expect(pluginTarget.common.name == "MyPlugin")
// Verify the executable target that uses the plugin exists
let executableTarget = try project.target(named: "MyPluginExe")
#expect(executableTarget.common.name == "MyPluginExe")
// Verify no errors were emitted during PIF generation
let errors = observabilitySystem.diagnostics.filter { $0.severity == .error }
#expect(errors.isEmpty, "Expected no errors during PIF generation, but got: \(errors)")
// Verify that the plugin target has a dependency (binary targets are handled differently in PIF)
// The key test is that PIF generation succeeds without errors when a plugin depends on a binary target
let binaryArtifactMessages = observabilitySystem.diagnostics.filter {
$0.message.contains("found binary artifact")
}
#expect(binaryArtifactMessages.count > 0, "Expected to find binary artifact processing messages")
}
}
@Test func buildToolPluginCommandLineUsesHostBuildPath() async throws {
let hostBuildPath = AbsolutePath("/path/to/host/build")
let destBuildPath = AbsolutePath("/path/to/dest/build")
let hostBuildParams = mockBuildParameters(
destination: .host,
buildPath: hostBuildPath,
buildSystemKind: .swiftbuild
)
let destBuildParams = mockBuildParameters(
destination: .host,
buildPath: destBuildPath,
buildSystemKind: .swiftbuild
)
try await withGeneratedPIF(
fromFixture: "Miscellaneous/Plugins/MySourceGenPlugin",
buildParameters: destBuildParams,
hostBuildParameters: hostBuildParams
) { pif, observabilitySystem in
let project = try pif.workspace.project(named: "MySourceGenPlugin")
let target = try project.target(named: "MyLocalTool-product")
for task in target.common.customTasks {
let commandLine = task.commandLine
#expect(commandLine.contains { $0.contains(hostBuildPath.pathString) })
#expect(!commandLine.contains { $0.contains(destBuildPath.pathString) })
}
}
}
@Test(
arguments: BuildConfiguration.allCases,
)
func dynamicLibraryProductExecutablePrefix(
configuration: BuildConfiguration,
) async throws {
try await withGeneratedPIF(
fromFixture: "PIFBuilder/Library",
shouldCreateDylibForDynamicProducts: true
) { pif, observabilitySystem in
let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }
#expect(errors.isEmpty, "Expected no errors during PIF generation, but got: \(errors)")
let target = try pif.workspace
.project(named: "Library")
.target(named: "LibraryDynamic-product")
guard case .target(let concreteTarget) = target else {
Issue.record("Expected a regular target, got \(target)")
return
}
#expect(concreteTarget.productType == .dynamicLibrary)
let config = try target.buildConfig(named: configuration)
#expect(config.settings[.EXECUTABLE_PREFIX] == "lib")
#expect(config.settings[.EXECUTABLE_PREFIX, .windows] == "")
}
try await withGeneratedPIF(
fromFixture: "PIFBuilder/Library",
shouldCreateDylibForDynamicProducts: false
) { pif, observabilitySystem in
let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }
#expect(errors.isEmpty, "Expected no errors during PIF generation, but got: \(errors)")
let target = try pif.workspace
.project(named: "Library")
.target(named: "LibraryDynamic-product")
let config = try target.buildConfig(named: configuration)
#expect(config.settings[.EXECUTABLE_PREFIX] == nil)
}
}
@Test(
arguments: BuildConfiguration.allCases,
)
func executablePrefixIsSetCorrectly(
configuration: BuildConfiguration,
) async throws {
try await withGeneratedPIF(fromFixture: "PIFBuilder/Library") { pif, observabilitySystem in
let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }
#expect(errors.isEmpty, "Expected no errors during PIF generation, but got: \(errors)")
struct ExpectedValue {
let targetName: String
let expectedValue: String?
let expectedValueForWindows: String?
}
let targetsUnderTest = [
ExpectedValue(
targetName: "LibraryDynamic-product",
expectedValue: "lib",
expectedValueForWindows: "",
),
ExpectedValue(
targetName: "LibraryStatic-product",
expectedValue: "lib",
expectedValueForWindows: "",
),
ExpectedValue(
targetName: "LibraryAuto-product",
expectedValue: "lib",
expectedValueForWindows: "",
),
]
for targetUnderTest in targetsUnderTest {
let projectConfig = try pif.workspace
.project(named: "Library")
.target(named: targetUnderTest.targetName)
.buildConfig(named: configuration)
let actualValue = projectConfig.settings[.EXECUTABLE_PREFIX]
let actualValueForWindows = projectConfig.settings[.EXECUTABLE_PREFIX, .windows]
#expect(actualValue == targetUnderTest.expectedValue)
#expect(actualValueForWindows == targetUnderTest.expectedValueForWindows)
}
}
}
@Test(arguments: BuildConfiguration.allCases)
func conditionalLinkerSettings(configuration: BuildConfiguration) async throws {
try await withGeneratedPIF(fromFixture: "PIFBuilder/ConditionalBuildSettings") { pif, observabilitySystem in
let errors = observabilitySystem.diagnostics.filter { $0.severity == .error }
#expect(errors.isEmpty, "Expected no errors during PIF generation, but got: \(errors)")
let targetConfig = try pif.workspace
.project(named: "ConditionalBuildSettings")
.target(id: "PACKAGE-TARGET:ConditionalBuildSettings")
.buildConfig(named: configuration)
let ldflags = targetConfig.settings[.OTHER_LDFLAGS]
switch configuration {
case .debug:
let debugFlags = try #require(ldflags, "Debug config requires OTHER_LDFLAGS")
#expect(
debugFlags.contains("-Xlinker") && debugFlags.contains("-interposable"),
"Debug config missing required flags: \(debugFlags)"
)
case .release:
#expect(ldflags == nil, "Release config should not have debug flags, but got \(ldflags)")
}
}
}
@Test func impartedModuleMaps() async throws {
try await withGeneratedPIF(fromFixture: "CFamilyTargets/ModuleMapGenerationCases") { pif, observabilitySystem in
#expect(observabilitySystem.diagnostics.filter {
$0.severity == .error
}.isEmpty)
do {
let releaseConfig = try pif.workspace
.project(named: "ModuleMapGenerationCases")
.target(named: "UmbrellaHeader")
.buildConfig(named: .release)
#expect(releaseConfig.impartedBuildProperties.settings[.OTHER_CFLAGS] == ["-fmodule-map-file=\(RelativePath("$(GENERATED_MODULEMAP_DIR)").appending(component: "UmbrellaHeader.modulemap").pathString)", "$(inherited)"])
}
do {
let releaseConfig = try pif.workspace
.project(named: "ModuleMapGenerationCases")
.target(named: "UmbrellaDirectoryInclude")
.buildConfig(named: .release)
#expect(releaseConfig.impartedBuildProperties.settings[.OTHER_CFLAGS] == ["-fmodule-map-file=\(RelativePath("$(GENERATED_MODULEMAP_DIR)").appending(component: "UmbrellaDirectoryInclude.modulemap").pathString)", "$(inherited)"])
}
do {
let releaseConfig = try pif.workspace
.project(named: "ModuleMapGenerationCases")
.target(named: "CustomModuleMap")
.buildConfig(named: .release)
let arg = try #require(releaseConfig.impartedBuildProperties.settings[.OTHER_CFLAGS]?.first)
#expect(arg.hasPrefix("-fmodule-map-file") && arg.hasSuffix(RelativePath("CustomModuleMap").appending(components: ["include", "module.modulemap"]).pathString))
}
}
}
@Test func disablingLocalRpaths() async throws {
try await withGeneratedPIF(fromFixture: "Miscellaneous/Simple") { pif, observabilitySystem in
#expect(observabilitySystem.diagnostics.filter {
$0.severity == .error
}.isEmpty)
do {
let releaseConfig = try pif.workspace
.project(named: "Foo")
.target(named: "Foo")
.buildConfig(named: .release)
#expect(releaseConfig.impartedBuildProperties.settings[.LD_RUNPATH_SEARCH_PATHS] == ["$(RPATH_ORIGIN)", "$(inherited)"])
}
}
try await withGeneratedPIF(fromFixture: "Miscellaneous/Simple", addLocalRpaths: false) { pif, observabilitySystem in
#expect(observabilitySystem.diagnostics.filter {
$0.severity == .error
}.isEmpty)
do {
let releaseConfig = try pif.workspace
.project(named: "Foo")
.target(named: "Foo")
.buildConfig(named: .release)
#expect(releaseConfig.impartedBuildProperties.settings[.LD_RUNPATH_SEARCH_PATHS] == nil)
}
}
}
@Test func warningSettingsInRemotePackage() async throws {
let observability = ObservabilitySystem.makeForTesting()
let fs = InMemoryFileSystem(emptyFiles: [
"/Root/Sources/RootLib/RootLib.swift",
"/RemotePkg/Sources/swiftLib/swiftLib.swift",
"/RemotePkg/Sources/cLib/cLib.c",
"/RemotePkg/Sources/cLib/include/cLib.h",
"/RemotePkg/Sources/cxxLib/cxxLib.cpp",
"/RemotePkg/Sources/cxxLib/include/cxxLib.h",
"/LocalPkg/Sources/localLib/localLib.swift",
])
let graph = try loadModulesGraph(
fileSystem: fs,
manifests: [
Manifest.createRootManifest(
displayName: "Root",
path: "/Root",
toolsVersion: .v6_2,
dependencies: [
.remoteSourceControl(
url: "https://example.com/remote-pkg",
requirement: .upToNextMajor(from: "1.0.0")
),
.fileSystem(path: "/LocalPkg"),
],
products: [],
targets: [
TargetDescription(
name: "RootLib",
dependencies: [
.product(name: "RemoteLib", package: "remote-pkg"),
.product(name: "RemoteCLib", package: "remote-pkg"),
.product(name: "RemoteCXXLib", package: "remote-pkg"),
.product(name: "LocalLib", package: "LocalPkg"),
]
),
]
),
Manifest.createRemoteSourceControlManifest(
displayName: "remote-pkg",
url: "https://example.com/remote-pkg",
path: "/RemotePkg",
toolsVersion: .v6_2,
products: [
ProductDescription(name: "RemoteLib", type: .library(.automatic), targets: ["swiftLib"]),
ProductDescription(name: "RemoteCLib", type: .library(.automatic), targets: ["cLib"]),
ProductDescription(name: "RemoteCXXLib", type: .library(.automatic), targets: ["cxxLib"]),
],
targets: [
TargetDescription(
name: "swiftLib",
settings: [
.init(tool: .swift, kind: .treatAllWarnings(.warning), condition: .init(config: "debug")),
.init(tool: .swift, kind: .treatAllWarnings(.error), condition: .init(config: "release")),
.init(tool: .swift, kind: .treatWarning("DeprecatedDeclaration", .error), condition: .init(config: "release")),
]
),
TargetDescription(
name: "cLib",
settings: [
.init(tool: .c, kind: .enableWarning("implicit-fallthrough"), condition: .init(config: "debug")),
.init(tool: .c, kind: .treatAllWarnings(.error), condition: .init(config: "release")),
.init(tool: .c, kind: .treatWarning("deprecated-declarations", .error), condition: .init(config: "release")),
]
),
TargetDescription(
name: "cxxLib",
settings: [
.init(tool: .cxx, kind: .enableWarning("implicit-fallthrough"), condition: .init(config: "debug")),
.init(tool: .cxx, kind: .treatAllWarnings(.error), condition: .init(config: "release")),
.init(tool: .cxx, kind: .treatWarning("deprecated-declarations", .error), condition: .init(config: "release")),
]
),
]
),
Manifest.createFileSystemManifest(
displayName: "LocalPkg",
path: "/LocalPkg",
toolsVersion: .v6_2,
products: [
ProductDescription(name: "LocalLib", type: .library(.automatic), targets: ["localLib"]),
],
targets: [
TargetDescription(
name: "localLib",
settings: [
.init(tool: .swift, kind: .treatAllWarnings(.error)),
]
),
]
),
],
observabilityScope: observability.topScope
)
let pifBuilder = PIFBuilder(
graph: graph,
parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(
temporaryDirectory: AbsolutePath.root,
addLocalRpaths: true
),
fileSystem: fs,
observabilityScope: observability.topScope
)
let pif = try await pifBuilder.constructPIF(
buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild),
hostBuildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)
)
let remoteProject = try pif.workspace.project(named: "remote-pkg")
for config in [BuildConfiguration.debug, .release] {
#expect(try remoteProject.buildConfig(named: config).settings[.SUPPRESS_WARNINGS] == "YES")
}
let swiftLibTarget = try remoteProject.target(named: "swiftLib")
let strippedSwiftFlags = ["-warnings-as-errors", "-no-warnings-as-errors", "-Wwarning", "-Werror", "DeprecatedDeclaration"]
for config in [BuildConfiguration.debug, .release] {
let swiftLibConfig = try swiftLibTarget.buildConfig(named: config)
if let swiftFlags = swiftLibConfig.settings[.OTHER_SWIFT_FLAGS] {
for flag in strippedSwiftFlags {
#expect(!swiftFlags.contains(flag))
}
}
}
for clangLibTargetName in ["cLib", "cxxLib"] {
let cLibTarget = try remoteProject.target(named: clangLibTargetName)
for config in [BuildConfiguration.debug, .release] {
let cLibConfig = try cLibTarget.buildConfig(named: config)
if let cFlags = cLibConfig.settings[.OTHER_CFLAGS] {
#expect(cFlags.filter { $0.count > 2 && $0.hasPrefix("-W") }.isEmpty)
}
if let cPlusPlusFlags = cLibConfig.settings[.OTHER_CPLUSPLUSFLAGS] {
#expect(cPlusPlusFlags.filter { $0.count > 2 && $0.hasPrefix("-W") }.isEmpty)
}
}
}
let localProject = try pif.workspace.project(named: "LocalPkg")
for config in [BuildConfiguration.debug, .release] {
#expect(try localProject.buildConfig(named: config).settings[.SUPPRESS_WARNINGS] == nil)
}
let localLibTarget = try localProject.target(named: "localLib")
for config in [BuildConfiguration.debug, .release] {
#expect(try localLibTarget.buildConfig(named: config).settings[.OTHER_SWIFT_FLAGS]?.contains("-warnings-as-errors") == true)
}
}
@Suite(
.tags(
.FunctionalArea.IndexMode
)
)
struct IndexModeSettingTests {
@Test(
arguments: [BuildParameters.IndexStoreMode.auto], [BuildConfiguration.debug],
// arguments: BuildParameters.IndexStoreMode.allCases, BuildConfiguration.allCases,
)
func indexModeSettingSetTo(
indexStoreSettingUT: BuildParameters.IndexStoreMode,
configuration: BuildConfiguration,
) async throws {
try await withGeneratedPIF(
fromFixture: "PIFBuilder/Simple",
buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild, indexStoreMode: indexStoreSettingUT),
) { pif, observabilitySystem in
// #expect(false, "fail purposefully...")
#expect(observabilitySystem.diagnostics.filter {
$0.severity == .error
}.isEmpty)
let targetConfig = try pif.workspace
.project(named: "Simple")
// .target(named: "Simple")
.buildConfig(named: configuration)
switch indexStoreSettingUT {
case .on, .off:
#expect(targetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == nil)
case .auto:
let expectedSwiftIndexStoreEnableValue: String? = switch configuration {
case .debug: "YES"
case .release: nil
}
#expect(targetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == expectedSwiftIndexStoreEnableValue)
}
let testTargetConfig = try pif.workspace
.project(named: "Simple")
.target(named: "SimpleTests-product")
.buildConfig(named: configuration)
switch indexStoreSettingUT {
case .on, .off:
#expect(testTargetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == nil)
case .auto:
#expect(testTargetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == "YES")
}
}
}
}
@Test func swiftCompileForStaticLinkingInDynamicLibraries() async throws {
let observability = ObservabilitySystem.makeForTesting()
let fs = InMemoryFileSystem(emptyFiles: [
"/Root/Sources/ModuleA/ModuleA.swift",
"/Root/Sources/ModuleB/ModuleB.swift",
"/Root/Sources/ModuleC/ModuleC.swift",
])
let graph = try loadModulesGraph(
fileSystem: fs,
manifests: [
Manifest.createRootManifest(
displayName: "Root",
path: "/Root",
toolsVersion: .v6_0,
products: [
ProductDescription(name: "DynamicLib", type: .library(.dynamic), targets: ["ModuleA", "ModuleB"]),
ProductDescription(name: "StaticLib", type: .library(.static), targets: ["ModuleC"]),
],
targets: [
TargetDescription(name: "ModuleA"),
TargetDescription(name: "ModuleB"),
TargetDescription(name: "ModuleC"),
]
),
],
observabilityScope: observability.topScope
)
let pifBuilder = PIFBuilder(
graph: graph,
parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(
temporaryDirectory: AbsolutePath.root.appending("tmp"),
addLocalRpaths: true
),
fileSystem: fs,
observabilityScope: observability.topScope
)
let pif = try await pifBuilder.constructPIF(
buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild),
hostBuildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)
)
let project = try pif.workspace.project(named: "Root")
// Modules that are direct dependencies of dynamic library products should have
// SWIFT_COMPILE_FOR_STATIC_LINKING = "NO" on Windows
for moduleName in ["ModuleA", "ModuleB"] {
let moduleTarget = try project.target(named: moduleName)
let config = try moduleTarget.buildConfig(named: .release)
// Check that the setting is "NO" on Windows
#expect(
config.settings[.SWIFT_COMPILE_FOR_STATIC_LINKING, .windows] == "NO",
"Module \(moduleName) in dynamic library should have SWIFT_COMPILE_FOR_STATIC_LINKING=NO on Windows"
)
// Check that the setting is not set on other platforms
for platform in SwiftBuild.ProjectModel.BuildSettings.Platform.allCases where platform != .windows {
#expect(
config.settings[.SWIFT_COMPILE_FOR_STATIC_LINKING, platform] == nil,
"Module \(moduleName) should not have SWIFT_COMPILE_FOR_STATIC_LINKING on platform \(platform)"
)
}
}
// Modules that are NOT in dynamic library products should not have this setting
let moduleC = try project.target(named: "ModuleC")
let moduleCConfig = try moduleC.buildConfig(named: .release)
for platform in ProjectModel.BuildSettings.Platform.allCases {