-
-
Notifications
You must be signed in to change notification settings - Fork 508
/
Graph.swift
458 lines (356 loc) · 14.8 KB
/
Graph.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
import Basic
import Foundation
import TuistCore
enum GraphError: FatalError {
case unsupportedFileExtension(String)
var description: String {
switch self {
case let .unsupportedFileExtension(productType):
return "Could't obtain product file extension for product type: \(productType)"
}
}
var type: ErrorType {
switch self {
case .unsupportedFileExtension:
return .bug
}
}
}
enum DependencyReference: Equatable, Comparable, Hashable {
case absolute(AbsolutePath)
case product(target: String)
case sdk(AbsolutePath, SDKStatus)
func hash(into hasher: inout Hasher) {
switch self {
case let .absolute(path):
hasher.combine(path)
case let .product(target):
hasher.combine(target)
case let .sdk(path, status):
hasher.combine(path)
hasher.combine(status)
}
}
static func == (lhs: DependencyReference, rhs: DependencyReference) -> Bool {
switch (lhs, rhs) {
case let (.absolute(lhsPath), .absolute(rhsPath)):
return lhsPath == rhsPath
case let (.product(lhsName), .product(rhsName)):
return lhsName == rhsName
case let (.sdk(lhsPath, lhsStatus), .sdk(rhsPath, rhsStatus)):
return lhsPath == rhsPath && lhsStatus == rhsStatus
default:
return false
}
}
static func < (lhs: DependencyReference, rhs: DependencyReference) -> Bool {
switch (lhs, rhs) {
case let (.absolute(lhsPath), .absolute(rhsPath)):
return lhsPath < rhsPath
case let (.product(lhsName), .product(rhsName)):
return lhsName < rhsName
case let (.sdk(lhsPath, _), .sdk(rhsPath, _)):
return lhsPath < rhsPath
case (.sdk, .absolute):
return true
case (.sdk, .product):
return true
case (.product, .absolute):
return true
default:
return false
}
}
}
protocol Graphing: AnyObject, Encodable {
var name: String { get }
var entryPath: AbsolutePath { get }
var entryNodes: [GraphNode] { get }
var projects: [Project] { get }
/// Returns all the CocoaPods nodes that are part of the graph.
var cocoapods: [CocoaPodsNode] { get }
/// Returns all the frameorks that are part of the graph.
var frameworks: [FrameworkNode] { get }
/// Returns all the precompiled nodes that are part of the graph.
var precompiled: [PrecompiledNode] { get }
/// Returns all the targets that are part of the graph.
var targets: [TargetNode] { get }
func linkableDependencies(path: AbsolutePath, name: String, system: Systeming) throws -> [DependencyReference]
func librariesPublicHeadersFolders(path: AbsolutePath, name: String) -> [AbsolutePath]
func librariesSearchPaths(path: AbsolutePath, name: String) -> [AbsolutePath]
func librariesSwiftIncludePaths(path: AbsolutePath, name: String) -> [AbsolutePath]
func embeddableFrameworks(path: AbsolutePath, name: String, system: Systeming) throws -> [DependencyReference]
func targetDependencies(path: AbsolutePath, name: String) -> [TargetNode]
func staticDependencies(path: AbsolutePath, name: String) -> [DependencyReference]
func resourceBundleDependencies(path: AbsolutePath, name: String) -> [TargetNode]
// MARK: - Depth First Search
/// Depth-first search (DFS) is an algorithm for traversing graph data structures. It starts at a source node
/// and explores as far as possible along each branch before backtracking.
///
/// This implementation looks for TargetNode's and traverses their dependencies so that we are able to build
/// up a graph of dependencies to later be used to define the "Link Binary with Library" in an xcodeproj.
func findAll<T: GraphNode>(path: AbsolutePath) -> Set<T>
}
class Graph: Graphing {
// MARK: - Attributes
private let cache: GraphLoaderCaching
let name: String
let entryPath: AbsolutePath
let entryNodes: [GraphNode]
var projects: [Project] {
return Array(cache.projects.values)
}
var projectPaths: [AbsolutePath] {
return Array(cache.projects.keys)
}
// MARK: - Init
init(name: String,
entryPath: AbsolutePath,
cache: GraphLoaderCaching,
entryNodes: [GraphNode]) {
self.name = name
self.entryPath = entryPath
self.cache = cache
self.entryNodes = entryNodes
}
// MARK: - Internal
/// Returns all the CocoaPods nodes that are part of the graph.
var cocoapods: [CocoaPodsNode] {
return Array(cache.cocoapodsNodes.values)
}
/// Returns all the frameworks that are part of the graph
var frameworks: [FrameworkNode] {
return cache.precompiledNodes.values.compactMap { $0 as? FrameworkNode }
}
/// Returns all the precompiled nodes that are part of the graph.
var precompiled: [PrecompiledNode] {
return Array(cache.precompiledNodes.values)
}
/// Returns all the targets that are part of the graph.
var targets: [TargetNode] {
return cache.targetNodes.flatMap { $0.value.values }
}
func targetDependencies(path: AbsolutePath, name: String) -> [TargetNode] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
return targetNode.targetDependencies
.filter { $0.path == path }
}
func staticDependencies(path: AbsolutePath, name: String) -> [DependencyReference] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
return targetNode.targetDependencies
.filter(isStaticLibrary)
.map { DependencyReference.product(target: $0.target.name) }
}
func resourceBundleDependencies(path: AbsolutePath, name: String) -> [TargetNode] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
return targetNode.targetDependencies
.filter { $0.target.product == .bundle }
}
func linkableDependencies(path: AbsolutePath, name: String, system _: Systeming) throws -> [DependencyReference] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
var references = Set<DependencyReference>()
// System libraries and frameworks
if targetNode.target.canLinkStaticProducts() {
let transitiveSystemLibraries = findAll(targetNode: targetNode, test: isStaticLibrary, skip: isFramework).flatMap {
$0.sdkDependencies.map {
DependencyReference.sdk($0.path, $0.status)
}
}
references = references.union(transitiveSystemLibraries)
}
let directSystemLibrariesAndFrameworks = targetNode.sdkDependencies.map {
DependencyReference.sdk($0.path, $0.status)
}
references = references.union(directSystemLibrariesAndFrameworks)
// Precompiled libraries and frameworks
let precompiledLibrariesAndFrameworks = targetNode.precompiledDependencies
.lazy
.map(\.path)
.map(DependencyReference.absolute)
references = references.union(precompiledLibrariesAndFrameworks)
// Static libraries and frameworks / Static libraries' dynamic libraries
if targetNode.target.canLinkStaticProducts() {
let staticLibraryTargetNodes = findAll(targetNode: targetNode, test: isStaticLibrary, skip: isFramework)
let staticLibraries = staticLibraryTargetNodes.map {
DependencyReference.product(target: $0.target.name)
}
let staticDependenciesDynamicLibraries = staticLibraryTargetNodes.flatMap {
$0.targetDependencies
.filter(or(isFramework, isDynamicLibrary))
.map { DependencyReference.product(target: $0.target.name) }
}
references = references.union(staticLibraries + staticDependenciesDynamicLibraries)
}
// Link dynamic libraries and frameworks
let dynamicLibrariesAndFrameworks = targetNode.targetDependencies
.filter(or(isFramework, isDynamicLibrary))
.map { DependencyReference.product(target: $0.target.name) }
references = references.union(dynamicLibrariesAndFrameworks)
return Array(references).sorted()
}
func librariesPublicHeadersFolders(path: AbsolutePath, name: String) -> [AbsolutePath] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
return targetNode.libraryDependencies
.map(\.publicHeaders)
}
func librariesSearchPaths(path: AbsolutePath, name: String) -> [AbsolutePath] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
return targetNode.libraryDependencies
.map { $0.path.removingLastComponent() }
}
func librariesSwiftIncludePaths(path: AbsolutePath, name: String) -> [AbsolutePath] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
return targetNode.libraryDependencies
.compactMap { $0.swiftModuleMap?.removingLastComponent() }
}
func embeddableFrameworks(path: AbsolutePath,
name: String,
system: Systeming) throws -> [DependencyReference] {
guard let targetNode = findTargetNode(path: path, name: name) else {
return []
}
let validProducts: [Product] = [
.app,
.unitTests,
.uiTests,
]
if validProducts.contains(targetNode.target.product) == false {
return []
}
var references: [DependencyReference] = []
let isDynamicAndLinkable = frameworkUsesDynamicLinking(system: system)
/// Precompiled frameworks
let precompiledFrameworks = findAll(targetNode: targetNode, test: isDynamicAndLinkable)
.lazy
.map(\.path)
.map(DependencyReference.absolute)
references.append(contentsOf: precompiledFrameworks)
/// Other targets' frameworks.
let otherTargetFrameworks = findAll(targetNode: targetNode, test: isFramework)
.map { DependencyReference.product(target: $0.target.name) }
references.append(contentsOf: otherTargetFrameworks)
/// Pre-built frameworks
let transitiveFrameworks = findAll(targetNode: targetNode)
.lazy
.filter(FrameworkNode.self)
.map(\.path)
.map(DependencyReference.absolute)
references.append(contentsOf: transitiveFrameworks)
return Set(references).sorted()
}
// MARK: - Fileprivate
private func findTargetNode(path: AbsolutePath, name: String) -> TargetNode? {
func isPathAndNameEqual(node: TargetNode) -> Bool {
return node.path == path && node.target.name == name
}
let targetNodes = entryNodes.compactMap { $0 as? TargetNode }
if let targetNode = targetNodes.first(where: isPathAndNameEqual) {
return targetNode
}
guard let cachedTargetNodesForPath = cache.targetNodes[path] else {
return nil
}
return cachedTargetNodesForPath[name]
}
}
// MARK: - Predicates
extension Graph {
internal func isStaticLibrary(targetNode: TargetNode) -> Bool {
return targetNode.target.product.isStatic
}
internal func isDynamicLibrary(targetNode: TargetNode) -> Bool {
return targetNode.target.product == .dynamicLibrary
}
internal func isFramework(targetNode: TargetNode) -> Bool {
return targetNode.target.product == .framework
}
internal func frameworkUsesDynamicLinking(system: Systeming) -> (_ frameworkNode: PrecompiledNode) -> Bool {
return { frameworkNode in
let isDynamicLink = try? frameworkNode.linking(system: system) == .dynamic
return isDynamicLink ?? false
}
}
}
// MARK: - TargetNode helper computed properties, provide lazy arrays by default.
extension TargetNode {
fileprivate var targetDependencies: [TargetNode] {
return dependencies.lazy.compactMap { $0 as? TargetNode }
}
fileprivate var precompiledDependencies: [PrecompiledNode] {
return dependencies.lazy.compactMap { $0 as? PrecompiledNode }
}
fileprivate var libraryDependencies: [LibraryNode] {
return dependencies.lazy.compactMap { $0 as? LibraryNode }
}
fileprivate var frameworkDependencies: [FrameworkNode] {
return dependencies.lazy.compactMap { $0 as? FrameworkNode }
}
fileprivate var sdkDependencies: [SDKNode] {
return dependencies.lazy.compactMap { $0 as? SDKNode }
}
}
extension Graph {
func findAll<T: GraphNode>(path: AbsolutePath) -> Set<T> {
guard let targetNodes = cache.targetNodes[path] else {
return []
}
var references = Set<T>()
for (_, node) in targetNodes {
references.formUnion(findAll(targetNode: node))
}
return references
}
// Traverse the graph from the target node using DFS and return all results passing the test.
func findAll<T: GraphNode>(targetNode: TargetNode, test: (T) -> Bool = { _ in true }, skip: (T) -> Bool = { _ in false }) -> Set<T> {
var stack = Stack<GraphNode>()
stack.push(targetNode)
var visited: Set<GraphNode> = .init()
var references = Set<T>()
while !stack.isEmpty {
guard let node = stack.pop() else {
continue
}
if visited.contains(node) {
continue
}
visited.insert(node)
// swiftlint:disable:next force_cast
if node != targetNode, node is T, test(node as! T) {
// swiftlint:disable:next force_cast
references.insert(node as! T)
}
if node != targetNode, let node = node as? T, skip(node) {
continue
} else if let targetNode = node as? TargetNode {
for child in targetNode.dependencies where !visited.contains(child) {
stack.push(child)
}
}
}
return references
}
}
// MARK: - Encodable
extension Graph {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
var nodes: [GraphNode] = []
nodes.append(contentsOf: cache.targetNodes.values.flatMap { $0.values })
nodes.append(contentsOf: Array(cache.precompiledNodes.values))
try container.encode(nodes.sorted(by: { $0.path < $1.path }))
}
}