-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
PackageBuilder.swift
1721 lines (1508 loc) · 71.7 KB
/
PackageBuilder.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) 2014-2023 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 Dispatch
import OrderedCollections
import PackageModel
import func TSCBasic.findCycle
import func TSCBasic.topologicalSort
import struct TSCBasic.KeyedPair
/// An error in the structure or layout of a package.
public enum ModuleError: Swift.Error {
/// Describes a way in which a package layout is invalid.
public enum InvalidLayoutType {
case multipleSourceRoots([AbsolutePath])
case modulemapInSources(AbsolutePath)
case modulemapMissing(AbsolutePath)
}
/// Indicates two targets with the same name and their corresponding packages.
case duplicateModule(targetName: String, packages: [PackageIdentity])
/// The referenced target could not be found.
case moduleNotFound(String, TargetDescription.TargetType, shouldSuggestRelaxedSourceDir: Bool)
/// The artifact for the binary target could not be found.
case artifactNotFound(targetName: String, expectedArtifactName: String)
/// Invalid module alias.
case invalidModuleAlias(originalName: String, newName: String)
/// Invalid custom path.
case invalidCustomPath(target: String, path: String)
/// Package layout is invalid.
case invalidLayout(InvalidLayoutType)
/// The manifest has invalid configuration wrt type of the target.
case invalidManifestConfig(String, String)
/// The target dependency declaration has cycle in it.
case cycleDetected((path: [String], cycle: [String]))
/// The public headers directory is at an invalid path.
case invalidPublicHeadersDirectory(String)
/// The sources of a target are overlapping with another target.
case overlappingSources(target: String, sources: [AbsolutePath])
/// We found multiple test entry point files.
case multipleTestEntryPointFilesFound(package: String, files: [AbsolutePath])
/// The tools version in use is not compatible with target's sources.
case incompatibleToolsVersions(package: String, required: [SwiftLanguageVersion], current: ToolsVersion)
/// The target path is outside the package.
case targetOutsidePackage(package: String, target: String)
/// Unsupported target path
case unsupportedTargetPath(String)
/// Invalid header search path.
case invalidHeaderSearchPath(String)
/// Default localization not set in the presence of localized resources.
case defaultLocalizationNotSet
/// A plugin target didn't declare a capability.
case pluginCapabilityNotDeclared(target: String)
/// A C target has declared an embedded resource
case embedInCodeNotSupported(target: String)
/// Indicates several targets with the same name exist in packages
case duplicateModules(package: PackageIdentity, otherPackage: PackageIdentity, targets: [String])
/// Indicates several targets with the same name exist in a registry and scm package
case duplicateModulesScmAndRegistry(
regsitryPackage: PackageIdentity.RegistryIdentity,
scmPackage: PackageIdentity,
targets: [String]
)
}
extension ModuleError: CustomStringConvertible {
public var description: String {
switch self {
case .duplicateModule(let target, let packages):
let packages = packages.map(\.description).sorted().joined(separator: "', '")
return "multiple targets named '\(target)' in: '\(packages)'"
case .moduleNotFound(let target, let type, let shouldSuggestRelaxedSourceDir):
let folderName = (type == .test) ? "Tests" : (type == .plugin) ? "Plugins" : "Sources"
var clauses = ["Source files for target \(target) should be located under '\(folderName)/\(target)'"]
if shouldSuggestRelaxedSourceDir {
clauses.append("'\(folderName)'")
}
clauses.append("or a custom sources path can be set with the 'path' property in Package.swift")
return clauses.joined(separator: ", ")
case .artifactNotFound(let targetName, let expectedArtifactName):
return "binary target '\(targetName)' could not be mapped to an artifact with expected name '\(expectedArtifactName)'"
case .invalidModuleAlias(let originalName, let newName):
return "empty or invalid module alias; ['\(originalName)': '\(newName)']"
case .invalidLayout(let type):
return "package has unsupported layout; \(type)"
case .invalidManifestConfig(let package, let message):
return "configuration of package '\(package)' is invalid; \(message)"
case .cycleDetected(let cycle):
return "cyclic dependency declaration found: " +
(cycle.path + cycle.cycle).joined(separator: " -> ") +
" -> " + cycle.cycle[0]
case .invalidPublicHeadersDirectory(let name):
return "public headers (\"include\") directory path for '\(name)' is invalid or not contained in the target"
case .overlappingSources(let target, let sources):
return "target '\(target)' has overlapping sources: " +
sources.map(\.description).joined(separator: ", ")
case .multipleTestEntryPointFilesFound(let package, let files):
return "package '\(package)' has multiple test entry point files: " +
files.map(\.description).sorted().joined(separator: ", ")
case .incompatibleToolsVersions(let package, let required, let current):
if required.isEmpty {
return "package '\(package)' supported Swift language versions is empty"
}
return "package '\(package)' requires minimum Swift language version \(required[0]) which is not supported by the current tools version (\(current))"
case .targetOutsidePackage(let package, let target):
return "target '\(target)' in package '\(package)' is outside the package root"
case .unsupportedTargetPath(let targetPath):
return "target path '\(targetPath)' is not supported; it should be relative to package root"
case .invalidCustomPath(let target, let path):
return "invalid custom path '\(path)' for target '\(target)'"
case .invalidHeaderSearchPath(let path):
return "invalid header search path '\(path)'; header search path should not be outside the package root"
case .defaultLocalizationNotSet:
return "manifest property 'defaultLocalization' not set; it is required in the presence of localized resources"
case .pluginCapabilityNotDeclared(let target):
return "plugin target '\(target)' doesn't have a 'capability' property"
case .embedInCodeNotSupported(let target):
return "embedding resources in code not supported for C-family language target \(target)"
case .duplicateModules(let package, let otherPackage, let targets):
var targetsDescription = "'\(targets.sorted().prefix(3).joined(separator: "', '"))'"
if targets.count > 3 {
targetsDescription += " and \(targets.count - 3) others"
}
return """
multiple similar targets \(targetsDescription) appear in package '\(package)' and '\(otherPackage)', \
this may indicate that the two packages are the same and can be de-duplicated by using mirrors. \
if they are not duplicate consider using the `moduleAliases` parameter in manifest to provide unique names
"""
case .duplicateModulesScmAndRegistry(let registryPackage, let scmPackage, let targets):
var targetsDescription = "'\(targets.sorted().prefix(3).joined(separator: "', '"))'"
if targets.count > 3 {
targetsDescription += " and \(targets.count - 3) others"
}
return """
multiple similar targets \(targetsDescription) appear in registry package '\(registryPackage)' and source control package '\(scmPackage)', \
this may indicate that the two packages are the same and can be de-duplicated \
by activating the automatic source-control to registry replacement, or by using mirrors. \
if they are not duplicate consider using the `moduleAliases` parameter in manifest to provide unique names
"""
}
}
}
extension ModuleError.InvalidLayoutType: CustomStringConvertible {
public var description: String {
switch self {
case .multipleSourceRoots(let paths):
return "multiple source roots found: " + paths.map(\.description).sorted().joined(separator: ", ")
case .modulemapInSources(let path):
return "modulemap '\(path)' should be inside the 'include' directory"
case .modulemapMissing(let path):
return "missing system target module map at '\(path)'"
}
}
}
extension Target {
/// An error in the organization or configuration of an individual target.
enum Error: Swift.Error {
/// The target's name is invalid.
case invalidName(path: RelativePath, problem: ModuleNameProblem)
enum ModuleNameProblem {
/// Empty target name.
case emptyName
}
/// The target contains an invalid mix of languages (e.g. both Swift and C).
case mixedSources(AbsolutePath)
}
}
extension Target.Error: CustomStringConvertible {
var description: String {
switch self {
case .invalidName(let path, let problem):
return "invalid target name at '\(path)'; \(problem)"
case .mixedSources(let path):
return "target at '\(path)' contains mixed language source files; feature not supported"
}
}
}
extension Target.Error.ModuleNameProblem: CustomStringConvertible {
var description: String {
switch self {
case .emptyName:
return "target names can not be empty"
}
}
}
extension Product {
/// An error in a product definition.
enum Error: Swift.Error {
case emptyName
case moduleEmpty(product: String, target: String)
}
}
extension Product.Error: CustomStringConvertible {
var description: String {
switch self {
case .emptyName:
return "product names can not be empty"
case .moduleEmpty(let product, let target):
return "target '\(target)' referenced in product '\(product)' is empty"
}
}
}
/// A structure representing the remote artifact information necessary to construct the package.
public struct BinaryArtifact {
/// The kind of the artifact.
public let kind: BinaryTarget.Kind
/// The URL the artifact was downloaded from.
public let originURL: String?
/// The path to the artifact.
public let path: AbsolutePath
public init(kind: BinaryTarget.Kind, originURL: String?, path: AbsolutePath) {
self.kind = kind
self.originURL = originURL
self.path = path
}
}
/// Helper for constructing a package following the convention system.
///
/// The 'builder' here refers to the builder pattern and not any build system
/// related function.
public final class PackageBuilder {
/// Predefined source directories, in order of preference.
public static let predefinedSourceDirectories = ["Sources", "Source", "src", "srcs"]
/// Predefined test directories, in order of preference.
public static let predefinedTestDirectories = ["Tests", "Sources", "Source", "src", "srcs"]
/// Predefined plugin directories, in order of preference.
public static let predefinedPluginDirectories = ["Plugins"]
/// The identity for the package being constructed.
private let identity: PackageIdentity
/// The manifest for the package being constructed.
private let manifest: Manifest
/// The product filter to apply to the package.
private let productFilter: ProductFilter
/// The path of the package.
private let packagePath: AbsolutePath
/// Information concerning the different downloaded or local (archived) binary target artifacts.
private let binaryArtifacts: [String: BinaryArtifact]
/// Create multiple test products.
///
/// If set to true, one test product will be created for each test target.
private let shouldCreateMultipleTestProducts: Bool
/// Path to test entry point file, if specified explicitly.
private let testEntryPointPath: AbsolutePath?
/// Temporary parameter controlling whether to warn about implicit executable targets when tools version is 5.4.
private let warnAboutImplicitExecutableTargets: Bool
/// Create the special REPL product for this package.
private let createREPLProduct: Bool
/// The additional file detection rules.
private let additionalFileRules: [FileRuleDescription]
/// ObservabilityScope with which to emit diagnostics
private let observabilityScope: ObservabilityScope
/// The filesystem package builder will run on.
private let fileSystem: FileSystem
private var platformRegistry: PlatformRegistry {
PlatformRegistry.default
}
// The set of the sources computed so far, used to validate source overlap
private var allSources = Set<AbsolutePath>()
private var swiftVersionCache: SwiftLanguageVersion? = nil
/// Create a builder for the given manifest and package `path`.
///
/// - Parameters:
/// - identity: The identity of this package.
/// - manifest: The manifest of this package.
/// - path: The root path of the package.
/// - artifactPaths: Paths to the downloaded binary target artifacts.
/// - createMultipleTestProducts: If enabled, create one test product for
/// each test target.
/// - fileSystem: The file system on which the builder should be run.///
public init(
identity: PackageIdentity,
manifest: Manifest,
productFilter: ProductFilter,
path: AbsolutePath,
additionalFileRules: [FileRuleDescription],
binaryArtifacts: [String: BinaryArtifact],
shouldCreateMultipleTestProducts: Bool = false,
testEntryPointPath: AbsolutePath? = nil,
warnAboutImplicitExecutableTargets: Bool = true,
createREPLProduct: Bool = false,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) {
self.identity = identity
self.manifest = manifest
self.productFilter = productFilter
self.packagePath = path
self.additionalFileRules = additionalFileRules
self.binaryArtifacts = binaryArtifacts
self.shouldCreateMultipleTestProducts = shouldCreateMultipleTestProducts
self.testEntryPointPath = testEntryPointPath
self.createREPLProduct = createREPLProduct
self.warnAboutImplicitExecutableTargets = warnAboutImplicitExecutableTargets
self.observabilityScope = observabilityScope.makeChildScope(
description: "PackageBuilder",
metadata: .packageMetadata(identity: self.identity, kind: self.manifest.packageKind)
)
self.fileSystem = fileSystem
}
/// Build a new package following the conventions.
public func construct() throws -> Package {
let targets = try self.constructTargets()
let products = try self.constructProducts(targets)
// Find the special directory for targets.
let targetSpecialDirs = self.findTargetSpecialDirs(targets)
return Package(
identity: self.identity,
manifest: self.manifest,
path: self.packagePath,
targets: targets,
products: products,
targetSearchPath: self.packagePath.appending(component: targetSpecialDirs.targetDir),
testTargetSearchPath: self.packagePath.appending(component: targetSpecialDirs.testTargetDir)
)
}
/// Computes the special directory where targets are present or should be placed in future.
private func findTargetSpecialDirs(_ targets: [Target]) -> (targetDir: String, testTargetDir: String) {
let predefinedDirs = self.findPredefinedTargetDirectory()
// Select the preferred tests directory.
var testTargetDir = PackageBuilder.predefinedTestDirectories[0]
// If found predefined test directory is not same as preferred test directory,
// check if any of the test target is actually inside the predefined test directory.
if predefinedDirs.testTargetDir != testTargetDir {
let expectedTestsDir = self.packagePath.appending(component: predefinedDirs.testTargetDir)
for target in targets where target.type == .test {
// If yes, use the predefined test directory as preferred test directory.
if expectedTestsDir == target.sources.root.parentDirectory {
testTargetDir = predefinedDirs.testTargetDir
break
}
}
}
return (predefinedDirs.targetDir, testTargetDir)
}
// MARK: Utility Predicates
private func isValidSource(_ path: AbsolutePath) -> Bool {
// Ignore files which don't match the expected extensions.
guard let ext = path.extension,
SupportedLanguageExtension.validExtensions(toolsVersion: self.manifest.toolsVersion).contains(ext)
else {
return false
}
let basename = path.basename
// Ignore dotfiles.
if basename.hasPrefix(".") { return false }
// Ignore test entry point files.
if SwiftTarget.testEntryPointNames.contains(basename) { return false }
// Ignore paths which are not valid files.
if !self.fileSystem.isFile(path) {
// Diagnose broken symlinks.
if self.fileSystem.isSymlink(path) {
self.observabilityScope.emit(.brokenSymlink(path))
}
return false
}
// Ignore manifest files.
if path.parentDirectory == self.packagePath {
if basename == Manifest.filename { return false }
// Ignore version-specific manifest files.
if basename.hasPrefix(Manifest.basename + "@") && basename.hasSuffix(".swift") {
return false
}
}
// Otherwise, we have a valid source file.
return true
}
/// Returns path to all the items in a directory.
// FIXME: This is generic functionality, and should move to FileSystem.
func directoryContents(_ path: AbsolutePath) throws -> [AbsolutePath] {
try self.fileSystem.getDirectoryContents(path).map { path.appending(component: $0) }
}
/// Private function that creates and returns a list of targets defined by a package.
private func constructTargets() throws -> [Target] {
// Check for a modulemap file, which indicates a system target.
let moduleMapPath = self.packagePath.appending(component: moduleMapFilename)
if self.fileSystem.isFile(moduleMapPath) {
// Warn about any declared targets.
if !self.manifest.targets.isEmpty {
self.observabilityScope.emit(
.systemPackageDeclaresTargets(targets: Array(self.manifest.targets.map(\.name)))
)
}
// Emit deprecation notice.
if self.manifest.toolsVersion >= .v4_2 {
self.observabilityScope.emit(.systemPackageDeprecation)
}
// Package contains a modulemap at the top level, so we assuming
// it's a system library target.
return [
SystemLibraryTarget(
name: self.manifest.displayName, // FIXME: use identity instead?
path: self.packagePath,
isImplicit: true,
pkgConfig: self.manifest.pkgConfig,
providers: self.manifest.providers
),
]
}
// At this point the target can't be a system target, make sure manifest doesn't contain
// system target specific configuration.
guard self.manifest.pkgConfig == nil else {
throw ModuleError.invalidManifestConfig(
self.identity.description, "the 'pkgConfig' property can only be used with a System Module Package"
)
}
guard self.manifest.providers == nil else {
throw ModuleError.invalidManifestConfig(
self.identity.description, "the 'providers' property can only be used with a System Module Package"
)
}
return try self.constructV4Targets()
}
/// Finds the predefined directories for regular targets, test targets, and plugin targets.
private func findPredefinedTargetDirectory()
-> (targetDir: String, testTargetDir: String, pluginTargetDir: String)
{
let targetDir = PackageBuilder.predefinedSourceDirectories.first(where: {
fileSystem.isDirectory(packagePath.appending(component: $0))
}) ?? PackageBuilder.predefinedSourceDirectories[0]
let testTargetDir = PackageBuilder.predefinedTestDirectories.first(where: {
fileSystem.isDirectory(packagePath.appending(component: $0))
}) ?? PackageBuilder.predefinedTestDirectories[0]
let pluginTargetDir = PackageBuilder.predefinedPluginDirectories.first(where: {
fileSystem.isDirectory(packagePath.appending(component: $0))
}) ?? PackageBuilder.predefinedPluginDirectories[0]
return (targetDir, testTargetDir, pluginTargetDir)
}
/// Construct targets according to PackageDescription 4 conventions.
private func constructV4Targets() throws -> [Target] {
// Select the correct predefined directory list.
let predefinedDirs = self.findPredefinedTargetDirectory()
let predefinedTargetDirectory = PredefinedTargetDirectory(
fs: fileSystem,
path: packagePath.appending(component: predefinedDirs.targetDir)
)
let predefinedTestTargetDirectory = PredefinedTargetDirectory(
fs: fileSystem,
path: packagePath.appending(component: predefinedDirs.testTargetDir)
)
let predefinedPluginTargetDirectory = PredefinedTargetDirectory(
fs: fileSystem,
path: packagePath.appending(component: predefinedDirs.pluginTargetDir)
)
/// Returns the path of the given target.
func findPath(for target: TargetDescription) throws -> AbsolutePath {
if target.type == .binary {
guard let artifact = self.binaryArtifacts[target.name] else {
throw ModuleError.artifactNotFound(targetName: target.name, expectedArtifactName: target.name)
}
return artifact.path
} else if let subpath = target.path { // If there is a custom path defined, use that.
if subpath == "" || subpath == "." {
return self.packagePath
}
// Make sure target is not referenced by absolute path
guard let relativeSubPath = try? RelativePath(validating: subpath) else {
throw ModuleError.unsupportedTargetPath(subpath)
}
let path = self.packagePath.appending(relativeSubPath)
// Make sure the target is inside the package root.
guard path.isDescendantOfOrEqual(to: self.packagePath) else {
throw ModuleError.targetOutsidePackage(package: self.identity.description, target: target.name)
}
if self.fileSystem.isDirectory(path) {
return path
}
throw ModuleError.invalidCustomPath(target: target.name, path: subpath)
}
// Check if target is present in the predefined directory.
let predefinedDir: PredefinedTargetDirectory
switch target.type {
case .test:
predefinedDir = predefinedTestTargetDirectory
case .plugin:
predefinedDir = predefinedPluginTargetDirectory
default:
predefinedDir = predefinedTargetDirectory
}
let path = predefinedDir.path.appending(component: target.name)
// Return the path if the predefined directory contains it.
if predefinedDir.contents.contains(target.name) {
return path
}
let commonTargetsOfSimilarType = self.manifest.targetsWithCommonSourceRoot(type: target.type).count
// If there is only one target defined, it may be allowed to occupy the
// entire predefined target directory.
if self.manifest.toolsVersion >= .v5_9 {
if commonTargetsOfSimilarType == 1 {
return predefinedDir.path
}
}
// Otherwise, if the path "exists" then the case in manifest differs from the case on the file system.
if self.fileSystem.isDirectory(path) {
self.observabilityScope.emit(.targetNameHasIncorrectCase(target: target.name))
return path
}
throw ModuleError.moduleNotFound(
target.name,
target.type,
shouldSuggestRelaxedSourceDir: self.manifest
.shouldSuggestRelaxedSourceDir(type: target.type)
)
}
// Create potential targets.
let potentialTargets: [PotentialModule]
potentialTargets = try self.manifest.targetsRequired(for: self.productFilter).map { target in
let path = try findPath(for: target)
return PotentialModule(name: target.name, path: path, type: target.type, packageAccess: target.packageAccess)
}
let targets = try createModules(potentialTargets)
let snippetTargets: [Target]
if self.manifest.packageKind.isRoot {
// Snippets: depend on all available library targets in the package.
// TODO: Do we need to filter out targets that aren't available on the host platform?
let productTargets = Set(manifest.products.flatMap(\.targets))
let snippetDependencies = targets
.filter { $0.type == .library && productTargets.contains($0.name) }
.map { Target.Dependency.target($0, conditions: []) }
snippetTargets = try createSnippetTargets(dependencies: snippetDependencies)
} else {
snippetTargets = []
}
return targets + snippetTargets
}
// Create targets from the provided potential targets.
private func createModules(_ potentialModules: [PotentialModule]) throws -> [Target] {
// Find if manifest references a target which isn't present on disk.
let allVisibleModuleNames = self.manifest.visibleModuleNames(for: self.productFilter)
let potentialModulesName = Set(potentialModules.map(\.name))
let missingModuleNames = allVisibleModuleNames.subtracting(potentialModulesName)
if let missingModuleName = missingModuleNames.first {
let type = potentialModules.first(where: { $0.name == missingModuleName })?.type ?? .regular
throw ModuleError.moduleNotFound(
missingModuleName,
type,
shouldSuggestRelaxedSourceDir: self.manifest.shouldSuggestRelaxedSourceDir(type: type)
)
}
let products = Dictionary(manifest.products.map { ($0.name, $0) }, uniquingKeysWith: { $1 })
// If there happens to be a plugin product with the right name in the same package, we want to use that automatically.
func pluginTargetName(for productName: String) -> String? {
if let product = products[productName], product.type == .plugin {
return product.targets.first
} else {
return nil
}
}
let potentialModuleMap = Dictionary(potentialModules.map { ($0.name, $0) }, uniquingKeysWith: { $1 })
let successors: (PotentialModule) -> [PotentialModule] = {
// No reference of this target in manifest, i.e. it has no dependencies.
guard let target = self.manifest.targetMap[$0.name] else { return [] }
// Collect the successors from declared dependencies.
var successors: [PotentialModule] = target.dependencies.compactMap {
switch $0 {
case .target(let name, _):
// Since we already checked above that all referenced targets
// has to present, we always expect this target to be present in
// potentialModules dictionary.
return potentialModuleMap[name]!
case .product:
return nil
case .byName(let name, _):
// By name dependency may or may not be a target dependency.
return potentialModuleMap[name]
}
}
// If there are plugin usages, consider them to be dependencies too.
if let pluginUsages = target.pluginUsages {
successors += pluginUsages.compactMap {
switch $0 {
case .plugin(_, .some(_)):
return nil
case .plugin(let name, nil):
if let potentialModule = potentialModuleMap[name] {
return potentialModule
} else if let targetName = pluginTargetName(for: name),
let potentialModule = potentialModuleMap[targetName]
{
return potentialModule
} else {
return nil
}
}
}
}
return successors
}
// Look for any cycle in the dependencies.
if let cycle = findCycle(potentialModules.sorted(by: { $0.name < $1.name }), successors: successors) {
throw ModuleError.cycleDetected((cycle.path.map(\.name), cycle.cycle.map(\.name)))
}
// There was no cycle so we sort the targets topologically.
let potentialModules = try topologicalSort(potentialModules, successors: successors)
// The created targets mapped to their name.
var targets = [String: Target]()
// If a directory is empty, we don't create a target object for them.
var emptyModules = Set<String>()
// Start iterating the potential targets.
for potentialModule in potentialModules.lazy.reversed() {
// Validate the target name. This function will throw an error if it detects a problem.
try validateModuleName(potentialModule.path, potentialModule.name, isTest: potentialModule.isTest)
// Get the target from the manifest.
let manifestTarget = manifest.targetMap[potentialModule.name]
// Get the dependencies of this target.
let dependencies: [Target.Dependency] = try manifestTarget.map {
try $0.dependencies.compactMap { dependency -> Target.Dependency? in
switch dependency {
case .target(let name, let condition):
// We don't create an object for targets which have no sources.
if emptyModules.contains(name) { return nil }
guard let target = targets[name] else { return nil }
return .target(target, conditions: buildConditions(from: condition))
case .product(let name, let package, let moduleAliases, let condition):
try validateModuleAliases(moduleAliases)
return .product(
.init(name: name, package: package, moduleAliases: moduleAliases),
conditions: buildConditions(from: condition)
)
case .byName(let name, let condition):
// We don't create an object for targets which have no sources.
if emptyModules.contains(name) { return nil }
if let target = targets[name] {
return .target(target, conditions: buildConditions(from: condition))
} else if potentialModuleMap[name] == nil {
return .product(
.init(name: name, package: nil),
conditions: buildConditions(from: condition)
)
} else {
return nil
}
}
}
} ?? []
// Get dependencies from the plugin usages of this target.
let pluginUsages: [Target.PluginUsage] = manifestTarget?.pluginUsages.map {
$0.compactMap { usage in
switch usage {
case .plugin(let name, let package):
if let package {
return .product(Target.ProductReference(name: name, package: package), conditions: [])
} else {
if let target = targets[name] {
return .target(target, conditions: [])
} else if let targetName = pluginTargetName(for: name), let target = targets[targetName] {
return .target(target, conditions: [])
} else {
self.observabilityScope.emit(.pluginNotFound(name: name))
return nil
}
}
}
}
} ?? []
// Create the target, adding the inferred dependencies from plugin usages to the declared dependencies.
let target = try createTarget(
potentialModule: potentialModule,
manifestTarget: manifestTarget,
dependencies: dependencies + pluginUsages
)
// Add the created target to the map or print no sources warning.
if let createdTarget = target {
targets[createdTarget.name] = createdTarget
} else {
emptyModules.insert(potentialModule.name)
self.observabilityScope.emit(.targetHasNoSources(
name: potentialModule.name,
type: potentialModule.type,
shouldSuggestRelaxedSourceDir: manifest
.shouldSuggestRelaxedSourceDir(
type: potentialModule
.type
)
))
}
}
return targets.values.sorted { $0.name > $1.name }
}
/// Private function that checks whether a target name is valid. This method doesn't return anything, but rather,
/// if there's a problem, it throws an error describing what the problem is.
private func validateModuleName(_ path: AbsolutePath, _ name: String, isTest: Bool) throws {
if name.isEmpty {
throw Target.Error.invalidName(
path: path.relative(to: self.packagePath),
problem: .emptyName
)
}
}
/// Validates module alias key and value pairs and throws an error if empty or contains invalid characters.
private func validateModuleAliases(_ aliases: [String: String]?) throws {
guard let aliases else { return }
for (aliasKey, aliasValue) in aliases {
if !aliasKey.isValidIdentifier ||
!aliasValue.isValidIdentifier ||
aliasKey == aliasValue
{
throw ModuleError.invalidModuleAlias(originalName: aliasKey, newName: aliasValue)
}
}
}
/// Private function that constructs a single Target object for the potential target.
private func createTarget(
potentialModule: PotentialModule,
manifestTarget: TargetDescription?,
dependencies: [Target.Dependency]
) throws -> Target? {
guard let manifestTarget else { return nil }
// Create system library target.
if potentialModule.type == .system {
let moduleMapPath = potentialModule.path.appending(component: moduleMapFilename)
guard self.fileSystem.isFile(moduleMapPath) else {
throw ModuleError.invalidLayout(.modulemapMissing(moduleMapPath))
}
return SystemLibraryTarget(
name: potentialModule.name,
path: potentialModule.path, isImplicit: false,
pkgConfig: manifestTarget.pkgConfig,
providers: manifestTarget.providers
)
} else if potentialModule.type == .binary {
guard let artifact = self.binaryArtifacts[potentialModule.name] else {
throw InternalError("unknown binary artifact for '\(potentialModule.name)'")
}
let artifactOrigin: BinaryTarget.Origin = artifact.originURL.flatMap { .remote(url: $0) } ?? .local
return BinaryTarget(
name: potentialModule.name,
kind: artifact.kind,
path: potentialModule.path,
origin: artifactOrigin
)
}
// Check for duplicate target dependencies
if self.manifest.disambiguateByProductIDs {
let dupProductIDs = dependencies.compactMap { $0.product?.identity }.spm_findDuplicates()
for dupProductID in dupProductIDs {
let comps = dupProductID.components(separatedBy: "_")
let pkg = comps.first ?? ""
let name = comps.dropFirst().joined(separator: "_")
let dupProductName = name.isEmpty ? dupProductID : name
self.observabilityScope.emit(.duplicateProduct(name: dupProductName, package: pkg))
}
let dupTargetNames = dependencies.compactMap { $0.target?.name }.spm_findDuplicates()
for dupTargetName in dupTargetNames {
self.observabilityScope.emit(.duplicateTargetDependency(
dependency: dupTargetName,
target: potentialModule.name,
package: self.identity.description
))
}
} else {
dependencies.filter { $0.product?.moduleAliases == nil }.spm_findDuplicateElements(by: \.nameAndType)
.map(\.[0].name).forEach {
self.observabilityScope
.emit(.duplicateTargetDependency(
dependency: $0,
target: potentialModule.name,
package: self.identity.description
))
}
}
// Create the build setting assignment table for this target.
let buildSettings = try self.buildSettings(
for: manifestTarget,
targetRoot: potentialModule.path,
cxxLanguageStandard: self.manifest.cxxLanguageStandard
)
// Compute the path to public headers directory.
let publicHeaderComponent = manifestTarget.publicHeadersPath ?? ClangTarget.defaultPublicHeadersComponent
let publicHeadersPath = potentialModule.path.appending(try RelativePath(validating: publicHeaderComponent))
guard publicHeadersPath.isDescendantOfOrEqual(to: potentialModule.path) else {
throw ModuleError.invalidPublicHeadersDirectory(potentialModule.name)
}
let sourcesBuilder = TargetSourcesBuilder(
packageIdentity: self.identity,
packageKind: self.manifest.packageKind,
packagePath: self.packagePath,
target: manifestTarget,
path: potentialModule.path,
defaultLocalization: self.manifest.defaultLocalization,
additionalFileRules: self.additionalFileRules,
toolsVersion: self.manifest.toolsVersion,
fileSystem: self.fileSystem,
observabilityScope: self.observabilityScope
)
let (sources, resources, headers, ignored, others) = try sourcesBuilder.run()
// Make sure defaultLocalization is set if the target has localized resources.
let hasLocalizedResources = resources.contains(where: { $0.localization != nil })
if hasLocalizedResources && self.manifest.defaultLocalization == nil {
throw ModuleError.defaultLocalizationNotSet
}
// FIXME: use identity instead?
// The name of the bundle, if one is being generated.
let potentialBundleName = self.manifest.displayName + "_" + potentialModule.name
if sources.relativePaths.isEmpty && resources.isEmpty && headers.isEmpty {
return nil
}
try self.validateSourcesOverlapping(forTarget: potentialModule.name, sources: sources.paths)
// Deal with package plugin targets.
if potentialModule.type == .plugin {
// Check that the target has a declared capability; we should not have come this far if not.
guard let declaredCapability = manifestTarget.pluginCapability else {
throw ModuleError.pluginCapabilityNotDeclared(target: manifestTarget.name)
}
// Create and return an PluginTarget configured with the information from the manifest.
return PluginTarget(
name: potentialModule.name,
sources: sources,
apiVersion: self.manifest.toolsVersion,
pluginCapability: PluginCapability(from: declaredCapability),
dependencies: dependencies,
packageAccess: potentialModule.packageAccess
)
}
/// Determine the target's type, or leave nil to check the source directory.
let targetType: Target.Kind
switch potentialModule.type {
case .test:
targetType = .test
case .executable:
targetType = .executable
case .macro:
targetType = .macro
default:
targetType = sources.computeTargetType()
if targetType == .executable && self.manifest.toolsVersion >= .v5_4 && self
.warnAboutImplicitExecutableTargets
{
self.observabilityScope
.emit(
warning: "'\(potentialModule.name)' was identified as an executable target given the presence of a 'main.swift' file. Starting with tools version \(ToolsVersion.v5_4) executable targets should be declared as 'executableTarget()'"
)
}
}
// Create and return the right kind of target depending on what kind of sources we found.
if sources.hasSwiftSources {
return SwiftTarget(
name: potentialModule.name,
potentialBundleName: potentialBundleName,
type: targetType,
path: potentialModule.path,
sources: sources,
resources: resources,
ignored: ignored,
others: others,
dependencies: dependencies,
packageAccess: potentialModule.packageAccess,
swiftVersion: try self.swiftVersion(),
buildSettings: buildSettings,
buildSettingsDescription: manifestTarget.settings,
usesUnsafeFlags: manifestTarget.usesUnsafeFlags
)
} else {
// It's not a Swift target, so it's a Clang target (those are the only two types of source target currently supported).
// First determine the type of module map that will be appropriate for the target based on its header layout.
let moduleMapType: ModuleMapType
if self.fileSystem.exists(publicHeadersPath) {
let moduleMapGenerator = ModuleMapGenerator(
targetName: potentialModule.name,
moduleName: potentialModule.name.spm_mangledToC99ExtendedIdentifier(),
publicHeadersDir: publicHeadersPath,
fileSystem: self.fileSystem
)
moduleMapType = moduleMapGenerator.determineModuleMapType(observabilityScope: self.observabilityScope)
} else if targetType == .library, self.manifest.toolsVersion >= .v5_5 {
// If this clang target is a library, it must contain "include" directory.
throw ModuleError.invalidPublicHeadersDirectory(potentialModule.name)
} else {
moduleMapType = .none
}
if resources.contains(where: { $0.rule == .embedInCode }) {