-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathPackageInfo.swift
317 lines (257 loc) · 10.7 KB
/
PackageInfo.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
//
// PackageInfo.swift
// swift-create-xcframework
//
// Created by Rob Amos on 7/5/20.
//
import ArgumentParser
#if swift(>=5.6)
import Basics
#endif
import Build
import Foundation
#if swift(>=5.6)
import PackageGraph
#endif
import PackageLoading
import PackageModel
import SPMBuildCore
#if swift(>=5.6)
import TSCBasic
#endif
import Workspace
import Xcodeproj
struct PackageInfo {
// MARK: - Properties
let rootDirectory: Foundation.URL
let buildDirectory: Foundation.URL
var projectBuildDirectory: Foundation.URL {
return self.buildDirectory
.appendingPathComponent("swift-create-xcframework")
.absoluteURL
}
var hasDistributionBuildXcconfig: Bool {
self.overridesXcconfig != nil || self.options.stackEvolution == false
}
var distributionBuildXcconfig: Foundation.URL {
return self.projectBuildDirectory
.appendingPathComponent("Distribution.xcconfig")
.absoluteURL
}
var overridesXcconfig: Foundation.URL? {
guard let path = self.options.xcconfig else { return nil }
// absolute path
if path.hasPrefix("/") {
return Foundation.URL(fileURLWithPath: path)
// strip current directory if thats where we are
} else if path.hasPrefix("./") {
return self.rootDirectory.appendingPathComponent(String(path[path.index(path.startIndex, offsetBy: 2)...]))
}
return self.rootDirectory.appendingPathComponent(path)
}
// TODO: Map diagnostics to swift-log
#if swift(>=5.6)
let observabilitySystem = ObservabilitySystem { _, diagnostics in
print("\(diagnostics.severity): \(diagnostics.message)")
}
#else
let diagnostics = DiagnosticsEngine()
#endif
let options: Command.Options
let graph: PackageGraph
let manifest: Manifest
let toolchain: UserToolchain
let workspace: Workspace
// MARK: - Initialisation
init (options: Command.Options) throws { // swiftlint:disable:this function_body_length
self.options = options
self.rootDirectory = Foundation.URL(fileURLWithPath: options.packagePath, isDirectory: true).absoluteURL
self.buildDirectory = self.rootDirectory.appendingPathComponent(options.buildPath, isDirectory: true).absoluteURL
let root = try TSCBasic.AbsolutePath(validating: self.rootDirectory.path)
self.toolchain = try UserToolchain(destination: try .hostDestination())
#if swift(>=5.7)
let loader = ManifestLoader(toolchain: self.toolchain)
self.workspace = try Workspace(forRootPackage: root.absPath, customManifestLoader: loader)
#elseif swift(>=5.6)
let resources = ToolchainConfiguration(swiftCompilerPath: self.toolchain.swiftCompilerPath)
let loader = ManifestLoader(toolchain: resources)
self.workspace = try Workspace(forRootPackage: root, customManifestLoader: loader)
#else
#if swift(>=5.5)
let resources = try UserManifestResources(swiftCompiler: self.toolchain.swiftCompiler, swiftCompilerFlags: [])
#else
let resources = try UserManifestResources(swiftCompiler: self.toolchain.swiftCompiler)
#endif
let loader = ManifestLoader(manifestResources: resources)
self.workspace = Workspace.create(forRootPackage: root, manifestLoader: loader)
#endif
#if swift(>=5.6)
self.graph = try workspace.loadPackageGraph(rootPath: root.absPath, observabilityScope: self.observabilitySystem.topScope)
let workspace = self.workspace
let scope = observabilitySystem.topScope
self.manifest = try tsc_await {
workspace.loadRootManifest(
at: root.absPath,
observabilityScope: scope,
completion: $0
)
}
#elseif swift(>=5.5)
self.graph = try self.workspace.loadPackageGraph(rootPath: root, diagnostics: self.diagnostics)
let swiftCompiler = toolchain.swiftCompiler
self.manifest = try tsc_await {
ManifestLoader.loadRootManifest(
at: root,
swiftCompiler: swiftCompiler,
swiftCompilerFlags: [],
identityResolver: DefaultIdentityResolver(),
on: DispatchQueue.global(qos: .background),
completion: $0
)
}
#else
self.graph = self.workspace.loadPackageGraph(root: root, diagnostics: self.diagnostics)
self.manifest = try ManifestLoader.loadManifest (
packagePath: root,
swiftCompiler: self.toolchain.swiftCompiler,
packageKind: .root
)
#endif
}
// MARK: - Validation
func validationErrors () -> [PackageValidationError] {
var errors = [PackageValidationError]()
// check the graph for binary targets
let binary = self.graph.allTargets.filter { $0.type == .binary }
if binary.isEmpty == false {
errors.append(.containsBinaryTargets(binary.map(\.name)))
}
// check for system modules
let system = self.graph.allTargets.filter { $0.type == .systemModule }
if system.isEmpty == false {
errors.append(.containsSystemModules(system.map(\.name)))
}
// and for conditional dependencies
let conditionals = self.graph.allTargets.filter { $0.dependencies.contains { $0.conditions.isEmpty == false } }
if conditionals.isEmpty == false {
errors.append(.containsConditionalDependencies(conditionals.map(\.name)))
}
return errors
}
// MARK: - Product/Target Names
func validProductNames (project: Xcode.Project) throws -> [String] {
// find our build targets
let productNames: [String]
if self.options.products.isEmpty == false {
productNames = self.options.products
} else {
productNames = self.manifest.libraryProductNames
}
// validation
guard productNames.isEmpty == false else {
throw ValidationError (
"No products to create frameworks for were found. Add library products to Package.swift"
+ " or specify products/targets on the command line."
)
}
let xcodeTargetNames = project.frameworkTargets.map { $0.name }
let invalidProducts = productNames.filter { xcodeTargetNames.contains($0) == false }
guard invalidProducts.isEmpty == true else {
let allLibraryProductNames = self.manifest.libraryProductNames
let nonRootPackageTargets = xcodeTargetNames.filter { allLibraryProductNames.contains($0) == false }
throw ValidationError (
"""
Invalid product/target name(s):
\(invalidProducts.joined(separator: "\n "))
Available \(self.manifest.displayName) products:
\(allLibraryProductNames.sorted().joined(separator: "\n "))
Additional available targets:
\(nonRootPackageTargets.sorted().joined(separator: "\n "))
"""
)
}
return productNames
}
func printAllProducts (project: Xcode.Project) {
let allLibraryProductNames = self.manifest.libraryProductNames
let xcodeTargetNames = project.frameworkTargets.map { $0.name }
let nonRootPackageTargets = xcodeTargetNames.filter { allLibraryProductNames.contains($0) == false }
print (
"""
\nAvailable \(self.manifest.displayName) products:
\(allLibraryProductNames.sorted().joined(separator: "\n "))
Additional available targets:
\(nonRootPackageTargets.sorted().joined(separator: "\n "))
\n
"""
)
}
// MARK: - Platforms
/// check if our command line platforms are supported by the package definition
func supportedPlatforms () throws -> [TargetPlatform] {
// if they have specified platforms all good, if not go everything except catalyst
let supported = self.options.platform.nonEmpty ?? TargetPlatform.allCases.filter { $0 != .maccatalyst }
// do we have package platforms defined?
guard let packagePlatforms = self.manifest.platforms.nonEmpty else {
return supported
}
// filter our package platforms to make sure everything is supported
let target = packagePlatforms
.compactMap { platform -> [TargetPlatform]? in
return supported.filter({ $0.platformName == platform.platformName })
}
.flatMap { $0 }
return target
}
}
// MARK: - Supported Platform Types
enum SupportedPlatforms {
case noPackagePlatforms (plan: [SupportedPlatform])
case packagePlatformsUnsupported (plan: [SupportedPlatform])
case packageValid (plan: [SupportedPlatform])
}
extension SupportedPlatform: Comparable {
public static func == (lhs: SupportedPlatform, rhs: SupportedPlatform) -> Bool {
return lhs.platform == rhs.platform && lhs.version == rhs.version
}
public static func < (lhs: SupportedPlatform, rhs: SupportedPlatform) -> Bool {
if lhs.platform == rhs.platform {
return lhs.version < rhs.version
}
return lhs.platform.name < rhs.platform.name
}
}
// MARK: - Validation Errors
enum PackageValidationError: LocalizedError {
case containsBinaryTargets([String])
case containsSystemModules([String])
case containsConditionalDependencies([String])
var isFatal: Bool {
switch self {
case .containsBinaryTargets, .containsSystemModules:
return true
case .containsConditionalDependencies:
return false
}
}
var errorDescription: String? {
switch self {
case let .containsBinaryTargets(targets):
return "Xcode project generation is not supported by Swift Package Manager for packages that contain binary targets."
+ "These binary targets were detected: \(targets.joined(separator: ", "))"
case let .containsSystemModules(targets):
return "Xcode project generation is not supported by Swift Package Manager for packages that reference system modules."
+ "These system modules were referenced: \(targets.joined(separator: ", "))"
case let .containsConditionalDependencies(targets):
return "Xcode project generation does not support conditional target dependencies, so the generated project may not build successfully."
+ "These targets contain conditional dependencies: \(targets.joined(separator: ", "))"
}
}
}
#if swift(<5.6)
extension Manifest {
var displayName: String {
name
}
}
#endif