-
-
Notifications
You must be signed in to change notification settings - Fork 511
/
ProjectFileElements.swift
546 lines (480 loc) · 23.2 KB
/
ProjectFileElements.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
import Basic
import Foundation
import TuistCore
import XcodeProj
// swiftlint:disable:next type_body_length
class ProjectFileElements {
struct GroupFileElement: Hashable {
var path: AbsolutePath
var group: ProjectGroup
var isReference: Bool
init(path: AbsolutePath, group: ProjectGroup, isReference: Bool = false) {
self.path = path
self.group = group
self.isReference = isReference
}
}
// MARK: - Static
// swiftlint:disable:next force_try
static let localizedRegex = try! NSRegularExpression(pattern: "(.+\\.lproj)/.+",
options: [])
// swiftlint:disable:next force_try
static let assetRegex = try! NSRegularExpression(pattern: ".+/.+\\.xcassets/.+",
options: [])
// MARK: - Attributes
var elements: [AbsolutePath: PBXFileElement] = [:]
var products: [String: PBXFileReference] = [:]
var sdks: [AbsolutePath: PBXFileReference] = [:]
let playgrounds: Playgrounding
let filesSortener: ProjectFilesSortening
// MARK: - Init
init(_ elements: [AbsolutePath: PBXFileElement] = [:],
playgrounds: Playgrounding = Playgrounds(),
filesSortener: ProjectFilesSortening = ProjectFilesSortener()) {
self.elements = elements
self.playgrounds = playgrounds
self.filesSortener = filesSortener
}
func generateProjectFiles(project: Project,
graph: Graphing,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath) throws {
var files = Set<GroupFileElement>()
var products = Set<String>()
project.targets.forEach { target in
files.formUnion(targetFiles(target: target))
products.formUnion(targetProducts(target: target))
}
let projectFileElements = projectFiles(project: project)
files.formUnion(projectFileElements)
let pathsSort = filesSortener.sort
let filesSort: (GroupFileElement, GroupFileElement) -> Bool = {
pathsSort($0.path, $1.path)
}
/// Files
try generate(files: files.sorted(by: filesSort),
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath)
/// Playgrounds
generatePlaygrounds(path: project.path,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath)
let dependencies = graph.findAll(path: project.path)
/// Products
try generateProducts(project: project,
dependencies: dependencies,
groups: groups,
pbxproj: pbxproj)
/// Dependencies
try generate(dependencies: dependencies,
path: project.path,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath,
filesGroup: project.filesGroup)
}
func projectFiles(project: Project) -> Set<GroupFileElement> {
var fileElements = Set<GroupFileElement>()
/// Config files
let configFiles = project.settings.configurations.values.compactMap { $0?.xcconfig }
fileElements.formUnion(configFiles.map {
GroupFileElement(path: $0, group: project.filesGroup)
})
// Additional files
fileElements.formUnion(project.additionalFiles.map {
GroupFileElement(path: $0.path,
group: project.filesGroup,
isReference: $0.isReference)
})
return fileElements
}
func targetProducts(target: Target) -> Set<String> {
var products: Set<String> = Set()
products.insert(target.productNameWithExtension)
return products
}
func targetFiles(target: Target) -> Set<GroupFileElement> {
var files = Set<AbsolutePath>()
files.formUnion(target.sources.map { $0.path })
files.formUnion(target.coreDataModels.map { $0.path })
files.formUnion(target.coreDataModels.flatMap { $0.versions })
if let headers = target.headers {
files.formUnion(headers.public)
files.formUnion(headers.private)
files.formUnion(headers.project)
}
// Support files
if let infoPlist = target.infoPlist {
files.insert(infoPlist.path)
}
if let entitlements = target.entitlements {
files.insert(entitlements)
}
// Config files
target.settings?.configurations.xcconfigs().forEach { configFilePath in
files.insert(configFilePath)
}
// Elements
var elements = Set<GroupFileElement>()
elements.formUnion(files.map { GroupFileElement(path: $0, group: target.filesGroup) })
elements.formUnion(target.resources.map {
GroupFileElement(path: $0.path,
group: target.filesGroup,
isReference: $0.isReference)
})
return elements
}
func generate(files: [GroupFileElement],
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath) throws {
try files.forEach {
try generate(fileElement: $0, groups: groups, pbxproj: pbxproj, sourceRootPath: sourceRootPath)
}
}
func generatePlaygrounds(path: AbsolutePath,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath _: AbsolutePath) {
let paths = playgrounds.paths(path: path)
if paths.isEmpty { return }
let group = groups.playgrounds
paths.forEach { playgroundPath in
let name = playgroundPath.components.last!
let reference = PBXFileReference(sourceTree: .group,
lastKnownFileType: "file.playground",
path: name,
xcLanguageSpecificationIdentifier: "xcode.lang.swift")
pbxproj.add(object: reference)
group!.children.append(reference)
}
}
func generateProducts(project: Project,
dependencies: Set<GraphNode>,
groups: ProjectGroups,
pbxproj: PBXProj) throws {
try prepareProductsFileReferences(project: project, dependencies: dependencies).forEach { pair in
guard self.products[pair.targetName] == nil else { return }
pbxproj.add(object: pair.fileReference)
groups.products.children.append(pair.fileReference)
self.products[pair.targetName] = pair.fileReference
}
}
func prepareProductsFileReferences(project: Project, dependencies: Set<GraphNode>)
throws -> [(targetName: String, fileReference: PBXFileReference)] {
let targetsProducts = project.targets
.map { ($0, $0.product) }
let dependenciesProducts = dependencies
.compactMap { $0 as? TargetNode }
.map { $0.target }
.map { ($0, $0.product) }
let mergeStrategy: (Product, Product) -> Product = { first, _ in first }
let sortByName: ((Target, Product), (Target, Product)) -> Bool = { first, second in first.0.productNameWithExtension < second.0.productNameWithExtension }
let targetsProductsDictionary = Dictionary(targetsProducts, uniquingKeysWith: mergeStrategy)
let dependenciesProductsDictionary = Dictionary(dependenciesProducts, uniquingKeysWith: mergeStrategy)
let productsDictionary = targetsProductsDictionary.merging(dependenciesProductsDictionary,
uniquingKeysWith: mergeStrategy)
return productsDictionary
.sorted(by: sortByName)
.map { target, product in
let fileType = Xcode.filetype(extension: product.xcodeValue.fileExtension!)
return (targetName: target.name,
fileReference: PBXFileReference(sourceTree: .buildProductsDir,
explicitFileType: fileType,
path: target.productNameWithExtension,
includeInIndex: false))
}
}
func generate(dependencies: Set<GraphNode>,
path _: AbsolutePath,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath,
filesGroup: ProjectGroup) throws {
let sortedDependencies = dependencies.sorted(by: { $0.path < $1.path })
try sortedDependencies.forEach { node in
switch node {
case let precompiledNode as PrecompiledNode:
let fileElement = GroupFileElement(path: precompiledNode.path,
group: filesGroup)
try generate(fileElement: fileElement,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath)
return
case let sdkNode as SDKNode:
generateSDKFileElement(node: sdkNode,
toGroup: groups.frameworks,
pbxproj: pbxproj)
default:
return
}
}
}
func generate(fileElement: GroupFileElement,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath) throws {
// The file already exists
if elements[fileElement.path] != nil { return }
let closestRelativeRelativePath = closestRelativeElementPath(path: fileElement.path,
sourceRootPath: sourceRootPath)
let closestRelativeAbsolutePath = sourceRootPath.appending(closestRelativeRelativePath)
let fileElementRelativeToSourceRoot = fileElement.path.relative(to: sourceRootPath)
// Add the first relative element.
let group: PBXGroup
switch fileElement.group {
case let .group(name: groupName):
group = try groups.projectGroup(named: groupName)
}
guard let firstElement = addElement(relativePath: closestRelativeRelativePath,
isLeaf: closestRelativeRelativePath == fileElementRelativeToSourceRoot,
from: sourceRootPath,
toGroup: group,
pbxproj: pbxproj) else {
return
}
// If it matches the file that we are adding or it's not a group we can exit.
if (closestRelativeAbsolutePath == fileElement.path) || !(firstElement.element is PBXGroup) {
return
}
var lastGroup: PBXGroup! = firstElement.element as? PBXGroup
var lastPath: AbsolutePath = firstElement.path
let components = fileElement.path.relative(to: lastPath).components
for component in components.enumerated() {
if lastGroup == nil { return }
guard let element = addElement(relativePath: RelativePath(component.element),
isLeaf: component.offset == components.count - 1,
from: lastPath,
toGroup: lastGroup!,
pbxproj: pbxproj) else {
return
}
lastGroup = element.element as? PBXGroup
lastPath = element.path
}
}
// MARK: - Internal
@discardableResult func addElement(relativePath: RelativePath,
isLeaf: Bool,
from: AbsolutePath,
toGroup: PBXGroup,
pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath)? {
let absolutePath = from.appending(relativePath)
if elements[absolutePath] != nil {
return (element: elements[absolutePath]!, path: from.appending(relativePath))
}
// If the path is ../../xx we specify the name
// to prevent Xcode from using that as a name.
var name: String?
let components = relativePath.components
if components.count != 1 {
name = components.last!
}
// Add the file element
if isLocalized(path: absolutePath) {
// Localized container (e.g. /path/to/en.lproj) we don't add it directly
// an element will get added once the next path component is evaluated
//
// note: assumption here is a path to a nested resource is always provided
return (element: toGroup, path: absolutePath)
} else if isLocalized(path: from) {
// Localized file (e.g. /path/to/en.lproj/foo.png)
addLocalizedFile(localizedFile: absolutePath,
toGroup: toGroup,
pbxproj: pbxproj)
return nil
} else if isVersionGroup(path: absolutePath) {
return addVersionGroupElement(from: from,
folderAbsolutePath: absolutePath,
folderRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj)
} else if !(isXcassets(path: absolutePath) || isLeaf) {
return addGroupElement(from: from,
folderAbsolutePath: absolutePath,
folderRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj)
} else {
addFileElement(from: from,
fileAbsolutePath: absolutePath,
fileRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj)
return nil
}
}
func addLocalizedFile(localizedFile: AbsolutePath,
toGroup: PBXGroup,
pbxproj: PBXProj) {
// e.g.
// from: resources/en.lproj/
// localizedFile: resources/en.lproj/App.strings
// Variant Group
let localizedName = localizedFile.basename // e.g. App.strings
let localizedContainer = localizedFile.parentDirectory // e.g. resources/en.lproj
let variantGroupPath = localizedContainer
.parentDirectory
.appending(component: localizedName) // e.g. resources/App.strings
let variantGroup = addVariantGroup(variantGroupPath: variantGroupPath,
localizedName: localizedName,
toGroup: toGroup,
pbxproj: pbxproj)
// Localized element
addLocalizedFileElement(localizedFile: localizedFile,
variantGroup: variantGroup,
localizedContainer: localizedContainer,
pbxproj: pbxproj)
}
private func addVariantGroup(variantGroupPath: AbsolutePath,
localizedName: String,
toGroup: PBXGroup,
pbxproj: PBXProj) -> PBXVariantGroup {
if let variantGroup = elements[variantGroupPath] as? PBXVariantGroup {
return variantGroup
}
let variantGroup = PBXVariantGroup(children: [], sourceTree: .group, name: localizedName)
pbxproj.add(object: variantGroup)
toGroup.children.append(variantGroup)
elements[variantGroupPath] = variantGroup
return variantGroup
}
private func addLocalizedFileElement(localizedFile: AbsolutePath,
variantGroup: PBXVariantGroup,
localizedContainer: AbsolutePath,
pbxproj: PBXProj) {
let localizedFilePath = localizedFile.relative(to: localizedContainer.parentDirectory)
let lastKnownFileType = Xcode.filetype(extension: localizedFile.basename)
let name = localizedContainer.basename.split(separator: ".").first
let localizedFileReference = PBXFileReference(sourceTree: .group,
name: name.map { String($0) },
lastKnownFileType: lastKnownFileType,
path: localizedFilePath.pathString)
pbxproj.add(object: localizedFileReference)
variantGroup.children.append(localizedFileReference)
}
func addVersionGroupElement(from: AbsolutePath,
folderAbsolutePath: AbsolutePath,
folderRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath) {
let versionGroupType = Xcode.filetype(extension: folderRelativePath.extension!)
let group = XCVersionGroup(currentVersion: nil,
path: folderRelativePath.pathString,
name: name,
sourceTree: .group,
versionGroupType: versionGroupType)
pbxproj.add(object: group)
toGroup.children.append(group)
elements[folderAbsolutePath] = group
return (element: group, path: from.appending(folderRelativePath))
}
func addGroupElement(from: AbsolutePath,
folderAbsolutePath: AbsolutePath,
folderRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath) {
let group = PBXGroup(children: [], sourceTree: .group, name: name, path: folderRelativePath.pathString)
pbxproj.add(object: group)
toGroup.children.append(group)
elements[folderAbsolutePath] = group
return (element: group, path: from.appending(folderRelativePath))
}
func addFileElement(from _: AbsolutePath,
fileAbsolutePath: AbsolutePath,
fileRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj) {
let lastKnownFileType = fileAbsolutePath.extension.flatMap { Xcode.filetype(extension: $0) }
let file = PBXFileReference(sourceTree: .group, name: name, lastKnownFileType: lastKnownFileType, path: fileRelativePath.pathString)
pbxproj.add(object: file)
toGroup.children.append(file)
elements[fileAbsolutePath] = file
}
private func generateSDKFileElement(node: SDKNode,
toGroup: PBXGroup,
pbxproj: PBXProj) {
guard sdks[node.path] == nil else {
return
}
addSDKElement(node: node, toGroup: toGroup, pbxproj: pbxproj)
}
private func addSDKElement(node: SDKNode,
toGroup: PBXGroup,
pbxproj: PBXProj) {
let sdkPath = node.path.relative(to: AbsolutePath("/")) // SDK paths are relative
let lastKnownFileType = sdkPath.extension.flatMap { Xcode.filetype(extension: $0) }
let file = PBXFileReference(sourceTree: .developerDir,
name: sdkPath.basename,
lastKnownFileType: lastKnownFileType,
path: sdkPath.pathString)
pbxproj.add(object: file)
toGroup.children.append(file)
sdks[node.path] = file
}
func group(path: AbsolutePath) -> PBXGroup? {
return elements[path] as? PBXGroup
}
func product(target name: String) -> PBXFileReference? {
return products[name]
}
func sdk(path: AbsolutePath) -> PBXFileReference? {
return sdks[path]
}
func file(path: AbsolutePath) -> PBXFileReference? {
return elements[path] as? PBXFileReference
}
func isLocalized(path: AbsolutePath) -> Bool {
return path.extension == "lproj"
}
func isVersionGroup(path: AbsolutePath) -> Bool {
return path.extension == "xcdatamodeld"
}
func isXcassets(path: AbsolutePath) -> Bool {
return path.extension == "xcassets"
}
/// Normalizes a path. Some paths have no direct representation in Xcode,
/// like localizable files. This method normalizes those and returns a project
/// representable path.
///
/// - Example:
/// /test/es.lproj/Main.storyboard ~> /test/es.lproj
func normalize(_ path: AbsolutePath) -> AbsolutePath {
let pathString = path.pathString
let range = NSRange(location: 0, length: pathString.count)
if let localizedMatch = ProjectFileElements.localizedRegex.firstMatch(in: pathString,
options: [],
range: range) {
let lprojPath = (pathString as NSString).substring(with: localizedMatch.range(at: 1))
return AbsolutePath(lprojPath)
} else {
return path
}
}
/// Returns the relative path of the closest relative element to the source root path.
/// If source root path is /a/b/c/project/ and file path is /a/d/myfile.swift
/// this method will return ../../../d/
func closestRelativeElementPath(path: AbsolutePath, sourceRootPath: AbsolutePath) -> RelativePath {
let relativePathComponents = path.relative(to: sourceRootPath).components
let firstElementComponents = relativePathComponents.reduce(into: [String]()) { components, component in
let isLastRelative = components.last == ".." || components.last == "."
if components.last != nil, !isLastRelative { return }
components.append(component)
}
if firstElementComponents.isEmpty, !relativePathComponents.isEmpty {
return RelativePath(relativePathComponents.first!)
} else {
return RelativePath(firstElementComponents.joined(separator: "/"))
}
}
}