-
Notifications
You must be signed in to change notification settings - Fork 50
/
XcodeTarget.swift
1290 lines (1124 loc) · 50.5 KB
/
XcodeTarget.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
// Copyright 2018-present, Pinterest, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import PathKit
import TulsiGenerator
import ProjectSpec
import xcproj
import ShellOut
private func shouldPropagateDeps(forTarget xcodeTarget: XcodeTarget) -> Bool {
return xcodeTarget.needsRecursiveExtraction && xcodeTarget.label.packageName?.hasPrefix("@") == false
}
/// Return XCConfig files
private func getXCConfigFiles(for target: XcodeTarget) -> [String: String] {
let genOptions = target.genOptions
let targetConfig = genOptions.config.getTargetConfig(for: target.label.value)
if let overrides = targetConfig?.xcconfigOverrides ?? genOptions.projectConfig?.xcconfigOverrides {
return Dictionary.from(overrides.map {
k, v in
let path = genOptions.workspaceRootPath + Path(v)
return (k, (path.string))
})
}
return [String: String]()
}
let AppIconSet = "appiconset"
let DirectoriesAsFileSuffixes: [String] = [
"app",
"appex",
"bundle",
"framework",
"octest",
"xcassets",
"xcodeproj",
"xcdatamodel",
"xcdatamodeld",
"xcmappingmodel",
"xctest",
"xcstickers",
"xpc",
"scnassets",
"lproj",
]
func includeTarget(_ xcodeTarget: XcodeTarget, pathPredicate: (String) -> Bool) -> Bool {
guard let buildFilePath = xcodeTarget.buildFilePath else {
return false
}
guard pathPredicate(buildFilePath) else {
return false
}
if shouldPropagateDeps(forTarget: xcodeTarget) {
return true
}
if xcodeTarget.type == "objc_bundle_library" {
return true
}
// Skip targets without implementations
let impls = (xcodeTarget.sourceFiles + xcodeTarget.nonARCSourceFiles)
.map { $0.subPath }
.filter { !$0.hasSuffix(".modulemap") && !$0.hasSuffix(".hmap") && !$0.hasSuffix(".h") }
if impls.count == 0 {
return false
}
guard let _ = xcodeTarget.xcType else {
return false
}
return true
}
// Traversal predicates
private let stopAfterNeedsRecursive: TraversalTransitionPredicate<XcodeTarget> = TraversalTransitionPredicate { $0.needsRecursiveExtraction ? .justOnceMore : .keepGoing }
private let stopAtBundles: TraversalTransitionPredicate<XcodeTarget> = TraversalTransitionPredicate { $0.type == "objc_bundle_library" ? .stop : .keepGoing }
public class XcodeTarget: Hashable, Equatable {
private let ruleEntry: RuleEntry
fileprivate let genOptions: XCHammerGenerateOptions
// Memory semantic hack
private weak var weakTargetMap: XcodeTargetMap?
fileprivate var targetMap: XcodeTargetMap {
return weakTargetMap!
}
init (ruleEntry: RuleEntry, map targetMap: XcodeTargetMap, genOptions:
XCHammerGenerateOptions) {
self.ruleEntry = ruleEntry
self.weakTargetMap = targetMap
self.genOptions = genOptions
}
public var label: BuildLabel {
return ruleEntry.label
}
public var type: String {
return ruleEntry.type
}
public var hashValue: Int {
return ruleEntry.hashValue
}
public func equals(_ other: XcodeTarget) -> Bool {
return ruleEntry == other.ruleEntry
}
// MARK : RuleEntry helpers
public var deploymentTarget: TulsiGenerator.DeploymentTarget? {
return ruleEntry.deploymentTarget
}
fileprivate var linkedTargetLabels: Set<BuildLabel> {
return ruleEntry.linkedTargetLabels
}
fileprivate var attributes: [RuleEntry.Attribute: AnyObject] {
return ruleEntry.attributes
}
fileprivate var artifacts: [BazelFileInfo] {
return ruleEntry.artifacts
}
fileprivate var defines: [String]? {
return ruleEntry.objcDefines
}
fileprivate var sourceFiles: [BazelFileInfo] {
return ruleEntry.sourceFiles
}
fileprivate var nonARCSourceFiles: [BazelFileInfo] {
return ruleEntry.nonARCSourceFiles
}
fileprivate var includePaths: [RuleEntry.IncludePath]? {
return ruleEntry.includePaths
}
fileprivate var dependencies: Set<BuildLabel> {
return ruleEntry.dependencies
}
fileprivate var extensions: Set<BuildLabel> {
return ruleEntry.extensions
}
fileprivate var frameworkImports: [BazelFileInfo] {
return ruleEntry.frameworkImports
}
fileprivate var weakDependencies: Set<BuildLabel> {
return ruleEntry.weakDependencies
}
fileprivate var buildFilePath: String? {
return ruleEntry.buildFilePath
}
fileprivate var bundleID: String? {
return ruleEntry.bundleID
}
fileprivate var bundleName: String? {
return ruleEntry.bundleName
}
fileprivate var extensionBundleID: String? {
return ruleEntry.extensionBundleID
}
fileprivate var extensionType: String? {
return ruleEntry.extensionType
}
lazy var isExtension: Bool = {
return self.xcType?.contains("app-extension") ?? false
}()
lazy var needsRecursiveExtraction: Bool = {
let type = self.xcType
let needsRecursiveTypes: Set<String> = [
"application",
"app-extension",
"apple_ui_test"
]
let value = self.isTopLevelTestTarget || (
type.map { needsRecursiveTypes.contains($0) } ?? false
)
return value
}()
lazy var xcTargetName: String = {
let numberOfEntries = self.targetMap.targets(buildLabel: self.label).count
let deploymentSuffix = (numberOfEntries > 1) ? self.deploymentTarget.map { "\($0.platform)-\($0.osVersion)" } : nil
// FIXME: Add uncolliding naming convention
// For now, we'll assume that all projects in the target have
// an uncolliding name, unless targets are Vendored
guard self.label.packageName!.contains("Vendor") == true else {
return [self.label.targetName!, deploymentSuffix].compactMap{ $0 }.joined(separator: "-")
}
// We can't rely on target name in the global scope
// Note: this basic logic doesn't work in 100% of cases, like when
// a pod has a different package name than the target. ( Texture-AsycDisplayKit )
let lastPackageComponent = self.label.packageName!.split(separator: "/").last!
if lastPackageComponent == self.label.targetName! {
return [String(lastPackageComponent), deploymentSuffix].compactMap { $0 }.joined(separator: "-")
}
return [String(lastPackageComponent), self.label.targetName!, deploymentSuffix].compactMap { $0 }.joined(separator: "-")
}()
func getXCSourceRootAbsolutePath(for fileInfo: BazelFileInfo) -> String {
switch fileInfo.targetType {
case .sourceFile:
return "$(SRCROOT)/" + resolveExternalPath(for: fileInfo.subPath)
case .generatedFile:
return "$(SRCROOT)/bazel-genfiles/" + fileInfo.subPath
}
}
func getRelativePath(for fileInfo: BazelFileInfo) -> String {
switch fileInfo.targetType {
case .sourceFile:
return resolveExternalPath(for: fileInfo.subPath)
case .generatedFile:
return "bazel-genfiles/" + fileInfo.subPath
}
}
func resolveExternalPath(for path: String) -> String {
if path.hasPrefix("external/") || self.label.packageName?.hasPrefix("@") ?? false {
return path.replacingOccurrences(of: "../", with: "external/")
}
return path
}
lazy var unfilteredDependencies: [XcodeTarget] = {
let unwrapSuffixes: Set<String> = [
".apple_binary",
"_test_bundle",
"_test_binary",
]
return self.dependencies
.compactMap { self.targetMap.xcodeTarget(buildLabel: $0, depender: self) }
.flatMap { xcodeTarget in
(unwrapSuffixes.map { xcodeTarget.label.value.hasSuffix($0) }.any()) ?
xcodeTarget.unfilteredDependencies :
[xcodeTarget]
}
}()
private static func isHeaderLike(path: String) -> Bool {
// Reference: XcodeGenKit/SourceGenerator.swift
return path.hasSuffix(".h") ||
path.hasSuffix(".hpp") ||
path.hasSuffix(".hh") ||
path.hasSuffix(".ipp") ||
path.hasSuffix(".tpp") ||
path.hasSuffix(".hxx") ||
path.hasSuffix(".def")
}
lazy var xcSources: [ProjectSpec.TargetSource] = {
let sourceFiles = self.sourceFiles
.filter { !$0.subPath.hasSuffix(".modulemap") && !$0.subPath.hasSuffix(".hmap") }
.map { fileInfo -> ProjectSpec.TargetSource in
let path = self.getRelativePath(for: fileInfo)
let phase = XcodeTarget.isHeaderLike(path: path) ?
TargetSource.BuildPhase.headers : nil
return ProjectSpec.TargetSource(path: path, buildPhase: phase,
headerVisibility:
TargetSource.HeaderVisibility.`project`)
}
let nonArcFiles = self.nonARCSourceFiles
.map {
fileInfo -> ProjectSpec.TargetSource in
let path = self.getRelativePath(for: fileInfo)
let phase = XcodeTarget.isHeaderLike(path: path) ?
TargetSource.BuildPhase.headers : nil
return ProjectSpec.TargetSource(path: path,
compilerFlags: ["-fno-objc-arc"],
buildPhase: phase, headerVisibility:
TargetSource.HeaderVisibility.`project`)
}
let resources = self.xcResources
let bundles = self.xcBundles
let stubAsset = self.settings.swiftVersion == nil ? XCHammerAsset.stubImp : XCHammerAsset.stubImpSwift
let all: [ProjectSpec.TargetSource] = resources + nonArcFiles + (sourceFiles.filter { !$0.path.hasSuffix("h") }.count > 0 ?
sourceFiles :
[ProjectSpec.TargetSource(path: stubAsset.getPath(underProj:
self.genOptions.outputProjectPath), compilerFlags: ["-x objective-c", "-std=gnu99"])]
) + bundles
let s: Set<ProjectSpec.TargetSource> = Set(all)
return Array(s)
}()
func transitiveTargets(map targetMap: XcodeTargetMap, predicate:
TraversalTransitionPredicate<XcodeTarget> =
TraversalTransitionPredicate<XcodeTarget>.empty, force: Bool = true) -> [XcodeTarget] {
if !force && !needsRecursiveExtraction {
return []
}
var visited: Set<XcodeTarget> = [self]
var transitiveTargets: [XcodeTarget] = []
var queue = unfilteredDependencies
while let xcodeTarget = queue.first {
queue.removeFirst()
guard visited.insert(xcodeTarget).inserted else {
continue
}
switch predicate.run(xcodeTarget) {
case .stop:
continue
case .justOnceMore:
transitiveTargets.append(xcodeTarget)
case .keepGoing:
transitiveTargets.append(xcodeTarget)
if force || xcodeTarget.needsRecursiveExtraction {
queue.insert(contentsOf: xcodeTarget.unfilteredDependencies, at: 0)
}
}
}
return transitiveTargets
}
func makePathFiltersTransitionPredicate(paths: Set<String>) -> TraversalTransitionPredicate<XcodeTarget> {
let pathPredicate = makePathFiltersPredicate(paths)
return TraversalTransitionPredicate { xcodeTarget -> Transition in
guard let buildFilePath = xcodeTarget.buildFilePath else {
fatalError()
}
guard pathPredicate(buildFilePath) else {
return .stop
}
return .keepGoing
}
}
lazy var xcResources: [ProjectSpec.TargetSource] = {
if self.needsRecursiveExtraction {
let deps: [XcodeTarget] = ([self] +
self.transitiveTargets(map:
self.targetMap, predicate: stopAtBundles <>
stopAfterNeedsRecursive ))
.filter { !$0.isEntitlementsDep }
return Array(Set(deps.flatMap { $0.myResources }))
} else {
// FIXME: We naievely copy all resources
return self.myResources
}
}()
func pathsForAttrs(attrs: Set<RuleEntry.Attribute>) -> [Path] {
return attrs.flatMap { attr in
self.attributes[attr] as? [[String: Any]] ??
(self.attributes[attr] as? [String: Any]).map{ [$0] } ??
[]
}.compactMap { $0["path"] as? String }.map { Path($0) }
}
func isAllowableXcodeGenSource(path: Path) -> Bool {
// These files are handled in other ways.
return path.extension != "mobileprovision"
}
lazy var myResources: [ProjectSpec.TargetSource] = {
let resources: [ProjectSpec.TargetSource] = self.pathsForAttrs(attrs:
[.launch_storyboard, .supporting_files])
.filter(self.isAllowableXcodeGenSource(path:))
.compactMap { inputPath in
let path = Path(self.resolveExternalPath(for: inputPath.string))
let pathComponents = path.components
if let specialIndex = (pathComponents.index { component in
DirectoriesAsFileSuffixes.map { component.hasSuffix("." + $0) }.any()
}) {
let formattedPath =
Path(pathComponents[pathComponents.startIndex ...
specialIndex].joined(separator: Path.separator))
if formattedPath.extension == "lproj" {
// TODO: Don't hardcode the parents for lproj
return ProjectSpec.TargetSource(path: formattedPath.parent().string, type: .group)
} else {
return ProjectSpec.TargetSource(path: formattedPath.string)
}
} else {
return ProjectSpec.TargetSource(path: path.string)
}
}
let structuredResources: [ProjectSpec.TargetSource] =
self.pathsForAttrs(attrs: [.structured_resources]).compactMap {
resourcePath -> ProjectSpec.TargetSource? in
guard let buildFilePath = self.buildFilePath else { return nil }
let basePath = Path(buildFilePath).parent().normalize()
// now we can recover the relative path provided inside the build files
let buildFileRelativePath =
Path(resourcePath.string.replacingOccurrences(of: basePath.string +
"/", with: ""))
// the structured path is the first directory relative to the build file dir
let structuredPath = basePath + Path(buildFileRelativePath.components[0])
// structured resources are rendered as folder-references in Xcode
return ProjectSpec.TargetSource(path: self.resolveExternalPath(for:
structuredPath.string), compilerFlags: [], type: .folder)
}
// Normalize for Xcode
// - dedupe
// - frameworks shouldn't be injested as a resource or a source
return Array(Set(resources + structuredResources))
.filter { !$0.path.hasSuffix(".framework") }
// FIXME: There is path issue with a subset of BUILD files.
.filter { !$0.path.hasSuffix("BUILD") }
}()
func extractBuiltProductName() -> String {
guard let productType = extractProductType() else {
fatalError()
}
switch productType {
case .Application:
return xcTargetName + ".app"
case .UnitTest, .UIUnitTest:
return xcTargetName + ".xctest"
case .AppExtension, .XPCService, .Watch1App, .Watch2App, .Watch1Extension, .Watch2Extension, .TVAppExtension:
return xcTargetName + ".appex"
case .StaticLibrary:
return xcTargetName
default:
return "$(TARGET_NAME)"
}
}
func extractLinkableBuiltProductName(map targetMap: XcodeTargetMap) -> String? {
guard let productType = extractProductType() else {
return nil
}
switch productType {
case .StaticLibrary:
return "lib" + xcTargetName + ".a"
case .StaticFramework, .Framework:
return xcTargetName
default:
return nil
}
}
private static let librarySourceTypes = Set(["swift", "m", "mm", "cpp", "c", "cc", "S"])
// Returns transitive linkable
lazy var transitiveDeps: Set<ProjectSpec.Dependency> = {
let deps = self.transitiveTargets(map: self.targetMap, predicate:
stopAfterNeedsRecursive, force: true)
.flatMap { xcodeTarget -> [ProjectSpec.Dependency] in
guard let linkableProductName =
xcodeTarget.extractLinkableBuiltProductName(map:
self.targetMap), includeTarget(xcodeTarget, pathPredicate:
alwaysIncludePathPredicate) else {
// either way, get the dependencies
return xcodeTarget.xcDependencies
}
guard let productType = xcodeTarget.extractProductType() else { return xcodeTarget.xcDependencies }
switch productType {
// Do not link static libraries that aren't going to exist.
// These targets still need to be included in the project.
case .StaticLibrary, .DynamicLibrary:
let compiledSrcs = (xcodeTarget.sourceFiles + xcodeTarget.nonARCSourceFiles)
.filter {
fileInfo in
let path = fileInfo.subPath
guard let suffix = path.components(separatedBy: ".").last else { return false }
return XcodeTarget.librarySourceTypes.contains(suffix)
}
if compiledSrcs.count == 0 {
return xcodeTarget.xcDependencies
}
default:
break
}
// make an explicit dep if it's valid
return [ProjectSpec.Dependency(type: .framework, reference: linkableProductName,
embed: xcodeTarget.isExtension)]
+ xcodeTarget.xcDependencies
}
return Set(deps)
}()
lazy var settings: XCBuildSettings = {
let targetMap = self.targetMap
let genOptions = self.genOptions
func processDefines(defines: [String]) -> [String] {
return defines
.filter { !$0.hasPrefix("__TIME") }
.filter { !$0.hasPrefix("__DATE") }
.sorted()
.map { "-D\($0)" }
}
var settings = XCBuildSettings()
self.attributes.forEach { attr, value in
switch attr {
case .copts:
if let coptsArray = value as? [String] {
let processedOpts = coptsArray.map { opt -> String in
if opt.hasPrefix("-I") {
let substringRangeStart = opt.index(opt.startIndex, offsetBy: 2)
let path = opt[substringRangeStart...]
let processedOpt = "-I$(SRCROOT)/\(path)"
return processedOpt
} else {
return opt.replacingOccurrences(of: "__BAZEL_GEN_DIR__",
with: "$(SRCROOT)/bazel-genfiles")
}
}
settings.copts <>= processedOpts
}
case .compiler_defines:
if let definesArray = value as? [String] {
let processedDefines = processDefines(defines: definesArray)
settings.copts <>= processedDefines
}
case .pch:
if let pchDictionary = value as? [String: AnyObject] {
guard let pchPath = pchDictionary["path"] as? String else {
fatalError("Invalid PCH dictionary, missing `path`: \(pchDictionary)")
}
settings.pch <>= First("$(SRCROOT)/\(pchPath)")
}
case .enable_modules:
settings.enableModules <>= (value as? Bool).map { First($0 ? "YES" : "NO") }
case .supporting_files:
settings.infoPlistFile <>= (value as? [[String: AnyObject]]).flatMap { $0.map { dict in
if let filePath = dict["path"] as? String,
Path(filePath).extension == "plist" {
return First("$(SRCROOT)/\(filePath)")
} else {
return nil
}
}.reduce(nil, <>) }
case .test_host:
guard !value.hasPrefix("@"),
let entry = self.targetMap.anyXcodeTarget(withBuildLabel: BuildLabel(value as! String)) else {
break
}
let xcTargetName = entry.xcTargetName
if self.type == "apple_ui_test" {
// USES_XCTRUNNER is set by Xcode automatically so we just need to set the test target name
settings.testTargetName <>= First(xcTargetName)
} else {
settings.testHost <>= First("$(BUILT_PRODUCTS_DIR)/\(xcTargetName).app/\(xcTargetName)")
settings.bundleLoader <>= First("$(TEST_HOST)")
}
case .test_bundle:
// These are actual ProjectSpec.Targets'
break
case .sdk_dylibs, .sdk_frameworks, .weak_sdk_frameworks:
// These are implemented below
break
case .launch_storyboard, .structured_resources, .entitlements, .provisioning_profile:
break // These attrs are not related to XCConfigs
case .binary:
break // Explicitly not handled since it is a implicit target we don't intend to handle
case .swift_language_version:
guard let swiftVersion = value as? String else {
break
}
settings.swiftVersion <>= First(swiftVersion)
case .has_swift_dependency, .has_swift_info:
guard let swiftVersion = try? ShellOut.shellOut(to: "xcrun swift package tools-version") else {
break
}
settings.swiftVersion <>= First(swiftVersion)
case .swiftc_opts:
if let coptsArray = value as? [String] {
let processedOpts = coptsArray.map { opt -> String in
if opt.hasPrefix("-I") {
let substringRangeStart = opt.index(opt.startIndex, offsetBy: 2)
let path = opt[substringRangeStart...]
let processedOpt = "-I$(SRCROOT)/\(path)"
return processedOpt
} else {
return opt
}
}
settings.swiftCopts <>= processedOpts
}
default:
print("TODO: Unimplemented attribute \(attr) \(value)")
}
}
// Product Name
settings.productName <>= self.bundleName.map { First($0) }
if settings.productName == nil {
settings.productName = First(self.extractBuiltProductName())
}
// Product Bundle Identifier
settings.productBundleId <>= self.bundleID.map { First($0) }
// Set Header Search Paths
if let headerSearchPaths = self.includePaths {
settings.headerSearchPaths <>=
OrderedArray(["$(inherited)"]) <>
headerSearchPaths
.filter { !$0.0.contains("tulsi-includes") }
.foldMap { (path: String, isRecursive: Bool) in
if path.hasSuffix("module_map") {
return ["$(SRCROOT)/bazel-genfiles/\(path)"]
} else if isRecursive {
return ["$(SRCROOT)/\(path)/**"]
} else {
return ["$(SRCROOT)/\(path)"]
}
}
}
settings.headerSearchPaths <>=
OrderedArray(["external"])
// Add my own + transitive header maps to copts
settings.copts <>= ([self] + self.transitiveTargets(map: targetMap))
.compactMap { $0.self.extractHeaderMap() }
.map { "-iquote \($0)" }
// Delegate warnings and error compiler options for targets that have a
// xcconfig.
let configs = getXCConfigFiles(for: self)
settings.diagnosticFlags <>= settings.copts.filter { $0.hasPrefix("-W") }
if configs.keys.count > 0 {
settings.copts = ["$(inherited)"] + settings.copts.filter { !$0.hasPrefix("-W") }
}
// Framework Search Paths
settings.frameworkSearchPaths <>= ["$(inherited)",
"$(PLATFORM_DIR)/Developer/Library/Frameworks"] <>
OrderedArray(self.frameworkDependencies
.compactMap { dep in dep.reference }
.map(dirname)
.map { "$(SRCROOT)/\($0)" })
let libraryDeps = self.extractLibraryDeps(map: targetMap)
settings.librarySearchPaths <>= OrderedArray(libraryDeps.map(dirname))
// Add defines as copts
settings.copts <>= processDefines(defines: self.extractDefines(map: targetMap))
if let moduleMapPath = self.extractModuleMap() {
settings.moduleMapFile <>= First(moduleMapPath)
settings.enableModules <>= First("YES")
}
settings <>= getDeploymentTargetSettings()
// Code Signing
settings.codeSigningRequired <>= First("NO")
settings.codeSigningIdentity <>= First("")
// Misc
settings.onlyActiveArch <>= First("YES")
// Fixes an Xcode "Upgrade to recommended settings" warning. Technically the warning only
// requires this to be added to the Debug build configuration but as code is never compiled
// anyway it doesn't hurt anything to set it on all configs.
settings.enableTestability <>= First("YES")
// Bazel sources are more or less ARC by default (the user has to use the special non_arc_srcs
// attribute for non-ARC) so the project is set to reflect that and per-file flags are used to
// override the default.
settings.enableObjcArc <>= First("YES")
if let appIconComponent = (self.pathsForAttrs(attrs: [.supporting_files]).flatMap { $0.components }.first { $0.hasSuffix(".\(AppIconSet)") }) {
let appIcon: String = appIconComponent.replacingOccurrences(of: ".\(AppIconSet)", with: "")
settings.appIconName <>= First(appIcon)
} else {
settings.appIconName <>= First("")
}
// Linker Flags (Frameworks, Weak Frameworks, ...)
func getLibraryName(atPath path: String) -> String {
guard let libName = path.components(separatedBy: "/").last?.components(separatedBy: ".").first else {
fatalError()
}
let offsetIdx = libName.utf8.index(libName.utf8.startIndex, offsetBy: 3)
return String(libName[offsetIdx ..< libName.utf8.endIndex])
}
let linkerLibOpts: OrderedArray<String> = self.needsRecursiveExtraction ? OrderedArray(libraryDeps.compactMap { value in
"-l\(getLibraryName(atPath: value))"
} + ["-ObjC"]) : []
// We've got custom entitlements linking actions for simulator only
let baseLDFlags = linkerLibOpts <>
OrderedArray(self.SDKFrameworks.map { "-framework \($0)" }) <>
OrderedArray(self.weakSDKFrameworks.map { "-weak_framework \($0)" }) <>
OrderedArray(self.SDKDylibs.map { "-l\($0)" })
settings.ldFlags <>= Setting(base: baseLDFlags,
SDKiPhoneSimulator: baseLDFlags,
SDKiPhone: nil)
return settings
}()
func getDeploymentTargetSettings() -> XCBuildSettings {
var settings = XCBuildSettings()
// Set thes deployment target if available
if let deploymentTgt = self.deploymentTarget {
switch deploymentTgt.platform {
case .ios:
settings.iOSDeploymentTarget <>= First(deploymentTgt.osVersion)
settings.sdkRoot <>= First("iphoneos")
settings.targetedDeviceFamily <>= ["1", "2"]
case .tvos:
settings.tvOSDeploymentTarget <>= First(deploymentTgt.osVersion)
settings.sdkRoot <>= First("appletvos")
settings.targetedDeviceFamily <>= ["3"]
case .watchos:
settings.watchOSDeploymentTarget <>= First(deploymentTgt.osVersion)
settings.sdkRoot <>= First("watchos")
settings.targetedDeviceFamily <>= ["4"]
case .macos:
settings.macOSDeploymentTarget <>= First(deploymentTgt.osVersion)
settings.sdkRoot <>= First("macosx")
}
}
return settings
}
// ProductType and Map are different than Tulsi's
enum ProductType: String {
case StaticLibrary = "com.apple.product-type.library.static"
case DynamicLibrary = "com.apple.product-type.library.dynamic"
case Tool = "com.apple.product-type.tool"
case Bundle = "com.apple.product-type.bundle"
case Framework = "com.apple.product-type.framework"
case StaticFramework = "com.apple.product-type.framework.static"
case Application = "com.apple.product-type.application"
case UnitTest = "com.apple.product-type.bundle.unit-test"
case UIUnitTest = "com.apple.product-type.bundle.ui-testing"
case InAppPurchaseContent = "com.apple.product-type.in-app-purchase-content"
case AppExtension = "com.apple.product-type.app-extension"
case XPCService = "com.apple.product-type.xpc-service"
case Watch1App = "com.apple.product-type.application.watchapp"
case Watch2App = "com.apple.product-type.application.watchapp2"
case Watch1Extension = "com.apple.product-type.watchkit-extension"
case Watch2Extension = "com.apple.product-type.watchkit2-extension"
case TVAppExtension = "com.apple.product-type.tv-app-extension"
}
lazy var isTopLevelTestTarget: Bool = {
return self.xcType?.contains("-test") ?? false
}()
lazy var xcDependencies: [ProjectSpec.Dependency] = {
guard self.frameworkImports.count > 0 else {
return []
}
// TODO: Move this to transitiveDeps
let xcodeTargetDeps: [XcodeTarget] = self.dependencies.compactMap {
depLabel in
let depName = depLabel.value
guard let target = self.targetMap.xcodeTarget(buildLabel: depLabel, depender: self) else {
return nil
}
guard target.frameworkImports.count == 0 else {
return nil
}
if depName.hasSuffix(".apple_binary") {
let unwrappedDeps = target.dependencies
for depEntry in unwrappedDeps {
// If it's an iOS app, strip out entitlements
if depEntry.value.hasSuffix("entitlements") {
continue
}
if let foundTarget = self.targetMap.xcodeTarget(buildLabel:
depEntry, depender: self) {
return foundTarget
}
}
}
return target
}
return xcodeTargetDeps
.compactMap {
xcodeTarget in
guard targetMap.includedTargets.contains(xcodeTarget) else {
return nil
}
return ProjectSpec.Dependency(type: .target, reference:
xcodeTarget.xcTargetName, embed:
xcodeTarget.isExtension)
} + self.frameworkDependencies
}()
lazy var frameworkDependencies: [ProjectSpec.Dependency] = {
// Uwrap Framework deps to prevent having a Goofy framework target that doesn't do anything
let shouldEmbed = self.attributes[.is_dynamic] as? Bool ?? false
let frameworkImports = self.frameworkImports
.map { fileInfo in fileInfo.fullPath }
.map { ProjectSpec.Dependency(type: .framework, reference: $0, embed: shouldEmbed) }
let childFrameworkImports = self.unfilteredDependencies.flatMap { entry in
entry.frameworkDependencies
}
return Array(Set<ProjectSpec.Dependency>(frameworkImports + childFrameworkImports))
}()
lazy var xcType: String? = {
let productType = self.extractProductType()
return productType?.rawValue.replacingOccurrences(of: "com.apple.product-type.", with: "")
}()
/// MARK - Extraction helpers
/// These helpers aren't memoized if they are called 1 time and cached
/**
Bazel Convertible for the following rule
export_ios_entitlements:
name,
entitlements,
provisioning_profile,
bundle_id
*/
struct ExportEntitlements {
let name: String
let entitlements: String? // FileOrLabel
let provisioningProfile: String? // FileOrLabel
let bundleID: String
func toBazel() -> String {
let provisioningProfileEntry = provisioningProfile != nil ?
"\"\(provisioningProfile!)\"" : "None"
let entitlementsEntry = entitlements != nil ?
"\"\(entitlements!)\"" : "None"
return """
export_entitlements(
name = "\(name)",
entitlements = \(entitlementsEntry),
provisioning_profile = \(provisioningProfileEntry),
bundle_id = "\(bundleID)",
platform_type = \"ios\"
)
"""
}
}
func extractExportEntitlementRule(map targetMap: XcodeTargetMap) -> ExportEntitlements? {
guard needsRecursiveExtraction,
let bundleID = self.bundleID else {
return nil
}
let label = BuildLabel(self.label.value + "_entitlements")
guard let targetRule = targetMap.anyXcodeTarget(withBuildLabel: label) else {
return nil
}
// This becomes //__PROJECT_NAME__.xcodeproj/XCHammerAssets:$targetName
let targetName = label.asFullPBXTargetName!
let entitlements = targetRule.attributes[.entitlements] as? String
let provisioningProfile = self.attributes[.provisioning_profile] as? String
let exportEntitlements = ExportEntitlements(name: targetName,
entitlements: entitlements,
provisioningProfile: provisioningProfile,
bundleID: bundleID)
return exportEntitlements
}
func extractCodeSignEntitlementsFile(genOptions: XCHammerGenerateOptions) -> String? {
guard needsRecursiveExtraction,
bundleID != nil else {
return nil
}
let label = BuildLabel(self.label.value + "_entitlements")
guard targetMap.anyXcodeTarget(withBuildLabel: label) != nil else {
return nil
}
// The above rules ( written to the code gen'd build file )
// dumps entitlements to this file
let relativeProjDir = genOptions.outputProjectPath.string
.replacingOccurrences(of: genOptions.workspaceRootPath.string,
with: "")
let targetName = label.asFullPBXTargetName!
return "$(SRCROOT)/bazel-genfiles" + relativeProjDir + "/XCHammerAssets/" + targetName + ".entitlements"
}
var mobileProvisionProfileFile: String? {
return ruleEntry.normalNonSourceArtifacts
.first { $0.subPath.hasSuffix("mobileprovision") }
.map(getXCSourceRootAbsolutePath(for:))
}
var isEntitlementsDep: Bool {
return label.value.hasSuffix("entitlements")
}
func extractDefines(map targetMap: XcodeTargetMap) -> [String] {
// Get the defines on the current rule and any defines on it's child rules
let allDefines = ([self] + transitiveTargets(map: targetMap, predicate: stopAfterNeedsRecursive))
.flatMap { $0.defines ?? [] }
// dedupe
return Array(Set(allDefines))
}
lazy var xcBundles: [ProjectSpec.TargetSource] = {
let bundleResources = ([self] + self.transitiveTargets(map:
self.targetMap,
predicate: stopAfterNeedsRecursive))
.filter { $0.type == "objc_bundle" }
.flatMap { $0.xcResources }
return Set(bundleResources.map { self.resolveExternalPath(for: $0.path) }).map { ProjectSpec.TargetSource(path: $0) }
}()
func extractLibraryDeps(map targetMap: XcodeTargetMap) -> [String] {
return transitiveTargets(map: targetMap, predicate: stopAfterNeedsRecursive)
.filter { $0.type == "objc_import" }
.compactMap { target -> [String]? in
guard let archives = target.attributes[.archives] as? [[String: Any]] else {
return nil
}
return archives.map { $0["path"] as! String }
}.flatMap { $0 }
}
func extractAttributeArray(attr: RuleEntry.Attribute, map targetMap: XcodeTargetMap) -> [String] {
if needsRecursiveExtraction {
return ([self] + transitiveTargets(map: targetMap, predicate: stopAfterNeedsRecursive))
.flatMap { $0.attributes[attr] as? [String] ?? [] }
} else {
return attributes[attr] as? [String] ?? []
}
}
lazy var SDKFrameworks: [String] = {
return self.extractAttributeArray(attr: .sdk_frameworks, map: self.targetMap)
}()
lazy var SDKDylibs: [String] = {
return self.extractAttributeArray(attr: .sdk_dylibs, map: self.targetMap)
.map { $0.hasPrefix("lib") ? String($0.dropFirst(3)) : $0 }
}()
lazy var weakSDKFrameworks: [String] = {
return self.extractAttributeArray(attr: .weak_sdk_frameworks, map: self.targetMap)
}()
fileprivate var xcExtensionDeps: [ProjectSpec.Dependency] {
// Assume extensions are contained in the same workspace
return extensions
.compactMap {