forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Xcode.swift
1663 lines (1461 loc) · 67.6 KB
/
Xcode.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
// swiftlint:disable file_length
import Foundation
import Result
import ReactiveSwift
import ReactiveTask
import XCDBLD
/// Emits the currect Swift version
internal func swiftVersion(usingToolchain toolchain: String? = nil) -> SignalProducer<String, SwiftVersionError> {
return determineSwiftVersion(usingToolchain: toolchain).replayLazily(upTo: 1)
}
/// Attempts to determine the local version of swift
private func determineSwiftVersion(usingToolchain toolchain: String?) -> SignalProducer<String, SwiftVersionError> {
let taskDescription = Task("/usr/bin/env", arguments: compilerVersionArguments(usingToolchain: toolchain))
return taskDescription.launch(standardInput: nil)
.ignoreTaskData()
.mapError { _ in SwiftVersionError.unknownLocalSwiftVersion }
.map { data -> String? in
return parseSwiftVersionCommand(output: String(data: data, encoding: .utf8))
}
.attemptMap { Result($0, failWith: SwiftVersionError.unknownLocalSwiftVersion) }
}
private func compilerVersionArguments(usingToolchain toolchain: String?) -> [String] {
if let toolchain = toolchain {
return ["xcrun", "--toolchain", toolchain, "swift", "--version"]
} else {
return ["xcrun", "swift", "--version"]
}
}
/// Parses output of `swift --version` for the version string.
private func parseSwiftVersionCommand(output: String?) -> String? {
guard
let output = output,
let regex = try? NSRegularExpression(pattern: "Apple Swift version ([^\\s]+) .*\\((.[^\\)]+)\\)", options: []),
let match = regex.firstMatch(in: output, options: [], range: NSRange(output.startIndex..., in: output))
else
{
return nil
}
guard match.numberOfRanges == 3 else { return nil }
let first = output[Range(match.range(at: 1), in: output)!]
let second = output[Range(match.range(at: 2), in: output)!]
return "\(first) (\(second))"
}
/// Determines the Swift version of a framework at a given `URL`.
internal func frameworkSwiftVersionIfIsSwiftFramework(_ frameworkURL: URL) -> SignalProducer<String?, SwiftVersionError> {
guard isSwiftFramework(frameworkURL) else {
return SignalProducer(value: nil)
}
return frameworkSwiftVersion(frameworkURL).map(Optional.some)
}
/// Determines the Swift version of a framework at a given `URL`.
internal func frameworkSwiftVersion(_ frameworkURL: URL) -> SignalProducer<String, SwiftVersionError> {
// Fall back to dSYM version parsing if header is not present
guard let swiftHeaderURL = frameworkURL.swiftHeaderURL() else {
let dSYMInXCFramework = frameworkURL.deletingLastPathComponent().appendingPathComponent("dSYMs")
.appendingPathComponent("\(frameworkURL.lastPathComponent).dSYM")
let dSYMInBuildFolder = frameworkURL.appendingPathExtension("dSYM")
return dSYMSwiftVersion(dSYMInXCFramework)
.flatMapError { _ in dSYMSwiftVersion(dSYMInBuildFolder) }
}
guard
let data = try? Data(contentsOf: swiftHeaderURL),
let contents = String(data: data, encoding: .utf8),
let swiftVersion = parseSwiftVersionCommand(output: contents)
else {
return SignalProducer(error: .unknownFrameworkSwiftVersion(message: "Could not derive version from header file."))
}
return SignalProducer(value: swiftVersion)
}
private func dSYMSwiftVersion(_ dSYMURL: URL) -> SignalProducer<String, SwiftVersionError> {
// Pick one architecture
guard let arch = architecturesInPackage(
dSYMURL,
xcrunQuery: ["lipo", "-info"]
).flatten().first()?.value else {
return SignalProducer(error: .unknownFrameworkSwiftVersion(message: "No architectures found in dSYM."))
}
// Check the .debug_info section left from the compiler in the dSYM.
let task = Task("/usr/bin/xcrun", arguments: ["dwarfdump", "--arch=\(arch)", "--debug-info", dSYMURL.path])
// $ dwarfdump --debug-info Carthage/Build/iOS/Swiftz.framework.dSYM
// ----------------------------------------------------------------------
// File: Carthage/Build/iOS/Swiftz.framework.dSYM/Contents/Resources/DWARF/Swiftz (i386)
// ----------------------------------------------------------------------
// .debug_info contents:
//
// 0x00000000: Compile Unit: length = 0x000000ac version = 0x0004 abbr_offset = 0x00000000 addr_size = 0x04 (next CU at 0x000000b0)
//
// 0x0000000b: TAG_compile_unit [1] *
// AT_producer( "Apple Swift version 4.1.2 effective-3.3.2 (swiftlang-902.0.54 clang-902.0.39.2) -emit-object /Users/Tommaso/<redacted>
let versions: [String]? = task.launch(standardInput: nil)
.ignoreTaskData()
.map { String(data: $0, encoding: .utf8) ?? "" }
.filter { !$0.isEmpty }
.flatMap(.merge) { (output: String) -> SignalProducer<String, NoError> in
output.linesProducer
}
.filter { $0.contains("AT_producer") }
.uniqueValues()
.map { parseSwiftVersionCommand(output: .some($0)) }
.skipNil()
.uniqueValues()
.collect()
.single()?
.value
let numberOfVersions = versions?.count ?? 0
guard numberOfVersions != 0 else {
return SignalProducer(error: .unknownFrameworkSwiftVersion(message: "No version found in dSYM."))
}
guard numberOfVersions == 1 else {
let versionsString = versions!.joined(separator: " ")
return SignalProducer(error: .unknownFrameworkSwiftVersion(message: "More than one found in dSYM - \(versionsString) ."))
}
return SignalProducer<String, SwiftVersionError>(value: versions!.first!)
}
/// Determines whether a framework was built with Swift
internal func isSwiftFramework(_ frameworkURL: URL) -> Bool {
return frameworkURL.swiftmoduleURL() != nil
}
/// Completes if the framework URL matches the local Swift version and errors if it does not.
internal func checkSwiftFrameworkCompatibility(_ frameworkURL: URL, usingToolchain toolchain: String?) -> SignalProducer<Void, SwiftVersionError> {
return SignalProducer.combineLatest(swiftVersion(usingToolchain: toolchain), frameworkSwiftVersion(frameworkURL))
.attemptMap { localSwiftVersion, frameworkSwiftVersion in
return localSwiftVersion == frameworkSwiftVersion || isModuleStableAPI(localSwiftVersion, frameworkSwiftVersion, frameworkURL)
? .success(())
: .failure(.incompatibleFrameworkSwiftVersions(local: localSwiftVersion, framework: frameworkSwiftVersion))
}
}
/// Determines whether a local swift version and a framework combination are considered module stable
internal func isModuleStableAPI(_ localSwiftVersion: String,
_ frameworkSwiftVersion: String,
_ frameworkURL: URL) -> Bool {
guard let localSwiftVersionNumber = determineMajorMinorVersion(localSwiftVersion),
let frameworkSwiftVersionNumber = determineMajorMinorVersion(frameworkSwiftVersion),
let swiftModuleURL = frameworkURL.swiftmoduleURL() else { return false }
let hasSwiftInterfaceFile = try? FileManager.default.contentsOfDirectory(at: swiftModuleURL,
includingPropertiesForKeys: nil,
options: []).first { (url) -> Bool in
return url.lastPathComponent.contains("swiftinterface")
} != nil
return localSwiftVersionNumber >= 5.1 && frameworkSwiftVersionNumber >= 5.1 && hasSwiftInterfaceFile == true
}
/// Attempts to return a `Double` representing the major/minor version components parsed from a given swift version, otherwise returns `nil`.
private func determineMajorMinorVersion(_ swiftVersion: String) -> Double? {
guard let range = swiftVersion.range(of: "^(\\d+)\\.(\\d+)", options: .regularExpression) else { return nil }
return Double(swiftVersion[range])
}
/// Completes if the framework URL if it is compatible with the build environment and errors if not.
internal func checkFrameworkCompatibility(_ frameworkURL: URL, usingToolchain toolchain: String?) -> SignalProducer<Void, CarthageError> {
return frameworkBundlesInURL(frameworkURL)
.mapError { CarthageError.readFailed(frameworkURL, $0 as NSError) }
.flatMap(.concat) { bundle -> SignalProducer<Void, CarthageError> in
if isSwiftFramework(bundle.bundleURL) {
return checkSwiftFrameworkCompatibility(bundle.bundleURL, usingToolchain: toolchain)
.mapError { .internalError(description: $0.description) }
} else {
return .empty
}
}
}
/// Creates a task description for executing `xcodebuild` with the given
/// arguments.
public func xcodebuildTask(_ tasks: [String], _ buildArguments: BuildArguments, environment: [String: String]? = nil) -> Task {
return Task("/usr/bin/xcrun", arguments: buildArguments.arguments + tasks, environment: environment)
}
/// Creates a task description for executing `xcodebuild` with the given
/// arguments.
public func xcodebuildTask(_ task: String, _ buildArguments: BuildArguments, environment: [String: String]? = nil) -> Task {
return xcodebuildTask([task], buildArguments)
}
/// Finds schemes of projects or workspaces, which Carthage should build, found
/// within the given directory.
public func buildableSchemesInDirectory( // swiftlint:disable:this function_body_length
_ directoryURL: URL,
withConfiguration configuration: String,
forPlatforms platformAllowList: Set<SDK>? = nil
) -> SignalProducer<(Scheme, ProjectLocator), CarthageError> {
precondition(directoryURL.isFileURL)
let locator = ProjectLocator
.locate(in: directoryURL)
.flatMap(.concurrent(limit: 4)) { project -> SignalProducer<(ProjectLocator, [Scheme]), CarthageError> in
return project
.schemes()
.collect()
.flatMapError { error in
if case .noSharedSchemes = error {
return .init(value: [])
} else {
return .init(error: error)
}
}
.map { (project, $0) }
}
.replayLazily(upTo: Int.max)
return locator
.collect()
// Allow dependencies which have no projects, not to error out with
// `.noSharedFrameworkSchemes`.
.filter { projects in !projects.isEmpty }
.flatMap(.merge) { (projects: [(ProjectLocator, [Scheme])]) -> SignalProducer<(Scheme, ProjectLocator), CarthageError> in
return schemesInProjects(projects).flatten()
}
.flatMap(.concurrent(limit: 4)) { scheme, project -> SignalProducer<(Scheme, ProjectLocator), CarthageError> in
/// Check whether we should the scheme by checking against the project. If we're building
/// from a workspace, then it might include additional targets that would trigger our
/// check.
let buildArguments = BuildArguments(project: project, scheme: scheme, configuration: configuration)
return shouldBuildScheme(buildArguments, platformAllowList)
.filter { $0 }
.map { _ in (scheme, project) }
}
.flatMap(.concurrent(limit: 4)) { scheme, project -> SignalProducer<(Scheme, ProjectLocator), CarthageError> in
return locator
// This scheduler hop is required to avoid disallowed recursive signals.
// See https://github.com/ReactiveCocoa/ReactiveCocoa/pull/2042.
.start(on: QueueScheduler(qos: .default, name: "org.carthage.CarthageKit.Xcode.buildInDirectory"))
// Pick up the first workspace which can build the scheme.
.flatMap(.concat) { project, schemes -> SignalProducer<ProjectLocator, CarthageError> in
switch project {
case .workspace where schemes.contains(scheme):
let buildArguments = BuildArguments(project: project, scheme: scheme, configuration: configuration)
return shouldBuildScheme(buildArguments, platformAllowList)
.filter { $0 }
.map { _ in project }
default:
return .empty
}
}
// If there is no appropriate workspace, use the project in
// which the scheme is defined instead.
.concat(value: project)
.take(first: 1)
.map { project in (scheme, project) }
}
.collect()
.flatMap(.merge) { (schemes: [(Scheme, ProjectLocator)]) -> SignalProducer<(Scheme, ProjectLocator), CarthageError> in
if !schemes.isEmpty {
return .init(schemes)
} else {
return .init(error: .noSharedFrameworkSchemes(.git(GitURL(directoryURL.path)), platformAllowList ?? []))
}
}
}
/// Sends pairs of a scheme and a project, the scheme actually resides in
/// the project.
public func schemesInProjects(_ projects: [(ProjectLocator, [Scheme])]) -> SignalProducer<[(Scheme, ProjectLocator)], CarthageError> {
return SignalProducer<(ProjectLocator, [Scheme]), CarthageError>(projects)
.map { (project: ProjectLocator, schemes: [Scheme]) in
// Only look for schemes that actually reside in the project
let containedSchemes = schemes.filter { scheme -> Bool in
let schemePath = project.fileURL.appendingPathComponent("xcshareddata/xcschemes/\(scheme).xcscheme").path
return FileManager.default.fileExists(atPath: schemePath)
}
return (project, containedSchemes)
}
.filter { (project: ProjectLocator, schemes: [Scheme]) in
switch project {
case .projectFile where !schemes.isEmpty:
return true
default:
return false
}
}
.flatMap(.concat) { project, schemes in
return SignalProducer<(Scheme, ProjectLocator), CarthageError>(schemes.map { ($0, project) })
}
.collect()
}
/// Describes the type of frameworks.
public enum FrameworkType: String, Codable {
/// A dynamic framework.
case dynamic
/// A static framework.
case `static`
init?(productType: ProductType, machOType: MachOType) {
switch (productType, machOType) {
case (.framework, .dylib):
self = .dynamic
case (.framework, .staticlib):
self = .static
case _:
return nil
}
}
/// Folder name for static framework's subdirectory
static let staticFolderName = "Static"
}
/// Describes the type of packages, given their CFBundlePackageType.
internal enum PackageType: String {
/// A .framework package.
case framework = "FMWK"
/// A .xcframework package
case xcframework = "XFWK"
/// A .bundle package. Some frameworks might have this package type code
/// (e.g. https://github.com/ResearchKit/ResearchKit/blob/1.3.0/ResearchKit/Info.plist#L15-L16).
case bundle = "BNDL"
/// A .dSYM package.
case dSYM = "dSYM"
}
/// Finds the built product for the given settings, then copies it (preserving
/// its name) into the given folder. The folder will be created if it does not
/// already exist.
///
/// If this built product has any *.bcsymbolmap files they will also be copied.
///
/// Returns a signal that will send the URL after copying upon .success.
private func copyBuildProductIntoDirectory(_ directoryURL: URL, _ settings: BuildSettings) -> SignalProducer<URL, CarthageError> {
let target = settings.wrapperName.map(directoryURL.appendingPathComponent)
return SignalProducer(result: target.fanout(settings.wrapperURL))
.flatMap(.merge) { target, source in
return copyProduct(source.resolvingSymlinksInPath(), target)
}
.flatMap(.merge) { url in
return copyBCSymbolMapsForBuildProductIntoDirectory(directoryURL, settings)
.then(SignalProducer<URL, CarthageError>(value: url))
}
}
/// Finds any *.bcsymbolmap files for the built product and copies them into
/// the given folder. Does nothing if bitcode is disabled.
///
/// Returns a signal that will send the URL after copying for each file.
private func copyBCSymbolMapsForBuildProductIntoDirectory(_ directoryURL: URL, _ settings: BuildSettings) -> SignalProducer<URL, CarthageError> {
if settings.bitcodeEnabled.value == true {
return SignalProducer(result: settings.wrapperURL)
.flatMap(.merge) { wrapperURL in BCSymbolMapsForFramework(wrapperURL) }
.copyFileURLsIntoDirectory(directoryURL)
} else {
return .empty
}
}
/// Attempts to merge the given executables into one fat binary, written to
/// the specified URL.
private func mergeExecutables(_ executableURLs: [URL], _ outputURL: URL) -> SignalProducer<(), CarthageError> {
precondition(outputURL.isFileURL)
return SignalProducer<URL, CarthageError>(executableURLs)
.attemptMap { url -> Result<String, CarthageError> in
if url.isFileURL {
return .success(url.path)
} else {
return .failure(.parseError(description: "expected file URL to built executable, got \(url)"))
}
}
.collect()
.flatMap(.merge) { executablePaths -> SignalProducer<TaskEvent<Data>, CarthageError> in
let lipoTask = Task("/usr/bin/xcrun", arguments: [ "lipo", "-create" ] + executablePaths + [ "-output", outputURL.path ])
return lipoTask.launch()
.mapError(CarthageError.taskError)
}
.then(SignalProducer<(), CarthageError>.empty)
}
private func mergeSwiftHeaderFiles(
_ simulatorExecutableURL: URL,
_ deviceExecutableURL: URL,
_ executableOutputURL: URL
) -> SignalProducer<(), CarthageError> {
precondition(simulatorExecutableURL.isFileURL)
precondition(deviceExecutableURL.isFileURL)
precondition(executableOutputURL.isFileURL)
let includeTargetConditionals = """
#ifndef TARGET_OS_SIMULATOR
#include <TargetConditionals.h>
#endif\n
"""
let conditionalPrefix = "#if TARGET_OS_SIMULATOR\n"
let conditionalElse = "\n#else\n"
let conditionalSuffix = "\n#endif\n"
let includeTargetConditionalsContents = includeTargetConditionals.data(using: .utf8)!
let conditionalPrefixContents = conditionalPrefix.data(using: .utf8)!
let conditionalElseContents = conditionalElse.data(using: .utf8)!
let conditionalSuffixContents = conditionalSuffix.data(using: .utf8)!
guard let simulatorHeaderURL = simulatorExecutableURL.deletingLastPathComponent().swiftHeaderURL() else { return .empty }
guard let simulatorHeaderContents = FileManager.default.contents(atPath: simulatorHeaderURL.path) else { return .empty }
guard let deviceHeaderURL = deviceExecutableURL.deletingLastPathComponent().swiftHeaderURL() else { return .empty }
guard let deviceHeaderContents = FileManager.default.contents(atPath: deviceHeaderURL.path) else { return .empty }
guard let outputURL = executableOutputURL.deletingLastPathComponent().swiftHeaderURL() else { return .empty }
var fileContents = Data()
fileContents.append(includeTargetConditionalsContents)
fileContents.append(conditionalPrefixContents)
fileContents.append(simulatorHeaderContents)
fileContents.append(conditionalElseContents)
fileContents.append(deviceHeaderContents)
fileContents.append(conditionalSuffixContents)
if FileManager.default.createFile(atPath: outputURL.path, contents: fileContents) {
return .empty
} else {
return .init(error: .writeFailed(outputURL, nil))
}
}
/// If the given source URL represents an LLVM module, copies its contents into
/// the destination module.
///
/// Sends the URL to each file after copying.
private func mergeModuleIntoModule(_ sourceModuleDirectoryURL: URL, _ destinationModuleDirectoryURL: URL) -> SignalProducer<URL, CarthageError> {
precondition(sourceModuleDirectoryURL.isFileURL)
precondition(destinationModuleDirectoryURL.isFileURL)
return FileManager.default.reactive
.enumerator(at: sourceModuleDirectoryURL, includingPropertiesForKeys: [], options: [ .skipsSubdirectoryDescendants, .skipsHiddenFiles ], catchErrors: true)
.attemptMap { _, url -> Result<URL, CarthageError> in
let lastComponent = url.lastPathComponent
let destinationURL = destinationModuleDirectoryURL.appendingPathComponent(lastComponent).resolvingSymlinksInPath()
return Result(at: destinationURL, attempt: {
try FileManager.default.copyItem(at: url, to: $0, avoiding·rdar·32984063: true)
return $0
})
}
}
/// Determines whether the specified framework type should be built automatically.
private func shouldBuildFrameworkType(_ frameworkType: FrameworkType?) -> Bool {
return frameworkType != nil
}
/// Determines whether the given scheme should be built automatically.
private func shouldBuildScheme(
_ buildArguments: BuildArguments,
_ platformAllowList: Set<SDK>? = nil
) -> SignalProducer<Bool, CarthageError> {
precondition(buildArguments.scheme != nil)
let setSignal = SDK.setsFromJSONShowSDKsWithFallbacks.promoteError(CarthageError.self)
return BuildSettings.load(with: buildArguments)
.flatMap(.merge) { (settings) -> SignalProducer<Set<SDK>, CarthageError> in
let supportedFrameworks = settings.buildSDKRawNames.map { sdk in SDK(name: sdk, simulatorHeuristic: "") }
guard settings.frameworkType.recover(nil) != nil else { return .empty }
return setSignal.map { $0.intersection(supportedFrameworks) }
}
.reduce(into: false) {
let filter = (platformAllowList ?? $1).contains
$0 = $0 || $1.firstIndex(where: filter) != nil
}
}
/// Aggregates all of the build settings sent on the given signal, associating
/// each with the name of its target.
///
/// Returns a signal which will send the aggregated dictionary upon completion
/// of the input signal, then itself complete.
private func settingsByTarget<Error>(_ producer: SignalProducer<TaskEvent<BuildSettings>, Error>) -> SignalProducer<TaskEvent<[String: BuildSettings]>, Error> {
return SignalProducer { observer, lifetime in
var settings: [String: BuildSettings] = [:]
producer.startWithSignal { signal, signalDisposable in
lifetime += signalDisposable
signal.observe { event in
switch event {
case let .value(settingsEvent):
let transformedEvent = settingsEvent.map { settings in [ settings.target: settings ] }
if let transformed = transformedEvent.value {
settings.merge(transformed) { _, new in new }
} else {
observer.send(value: transformedEvent)
}
case let .failed(error):
observer.send(error: error)
case .completed:
observer.send(value: .success(settings))
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
}
/// Combines the built products corresponding to the given settings, by creating
/// a fat binary of their executables and merging any Swift modules together,
/// generating a new built product in the given directory.
///
/// In order for this process to make any sense, the build products should have
/// been created from the same target, and differ only in the SDK they were
/// built for.
///
/// Any *.bcsymbolmap files for the built products are also copied.
///
/// Upon .success, sends the URL to the merged product, then completes.
private func mergeBuildProducts(
deviceBuildSettings: BuildSettings,
simulatorBuildSettings: BuildSettings,
into destinationFolderURL: URL
) -> SignalProducer<URL, CarthageError> {
let commonArchitectures = deviceBuildSettings.archs.fanout(simulatorBuildSettings.archs).map { deviceArchs, simulatorArchs in
deviceArchs.intersection(simulatorArchs)
}
return copyBuildProductIntoDirectory(destinationFolderURL, deviceBuildSettings)
.flatMap(.merge) { productURL -> SignalProducer<URL, CarthageError> in
let executableURLs = (deviceBuildSettings.executableURL.fanout(simulatorBuildSettings.executableURL)).map { [ $0, $1 ] }
let outputURL = deviceBuildSettings.executablePath.map(destinationFolderURL.appendingPathComponent)
let mergeProductBinaries = SignalProducer(result: executableURLs.fanout(outputURL))
.flatMap(.concat) { (executableURLs: [URL], outputURL: URL) -> SignalProducer<(), CarthageError> in
return mergeExecutables(
executableURLs.map { $0.resolvingSymlinksInPath() },
outputURL.resolvingSymlinksInPath()
)
}
let mergeProductSwiftHeaderFilesIfNeeded = SignalProducer.zip(simulatorBuildSettings.executableURL, deviceBuildSettings.executableURL, outputURL)
.flatMap(.concat) { (simulatorURL: URL, deviceURL: URL, outputURL: URL) -> SignalProducer<(), CarthageError> in
guard isSwiftFramework(productURL) else { return .empty }
return mergeSwiftHeaderFiles(
simulatorURL.resolvingSymlinksInPath(),
deviceURL.resolvingSymlinksInPath(),
outputURL.resolvingSymlinksInPath()
)
}
let sourceModulesURL = SignalProducer(result: simulatorBuildSettings.relativeModulesPath.fanout(simulatorBuildSettings.builtProductsDirectoryURL))
.filter { $0.0 != nil }
.map { modulesPath, productsURL in
return productsURL.appendingPathComponent(modulesPath!)
}
let destinationModulesURL = SignalProducer(result: deviceBuildSettings.relativeModulesPath)
.filter { $0 != nil }
.map { modulesPath -> URL in
return destinationFolderURL.appendingPathComponent(modulesPath!)
}
let mergeProductModules = SignalProducer.zip(sourceModulesURL, destinationModulesURL)
.flatMap(.merge) { (source: URL, destination: URL) -> SignalProducer<URL, CarthageError> in
return mergeModuleIntoModule(source, destination)
}
return mergeProductBinaries
.then(mergeProductSwiftHeaderFilesIfNeeded)
.then(mergeProductModules)
.then(copyBCSymbolMapsForBuildProductIntoDirectory(destinationFolderURL, simulatorBuildSettings))
.then(SignalProducer<URL, CarthageError>(value: productURL))
}
.mapError { error -> CarthageError in
if case .taskError(let taskError) = error,
let commonArchitectures = commonArchitectures.value,
let productName = deviceBuildSettings.productName.value {
return .xcframeworkRequired(.init(productName: productName, commonArchitectures: commonArchitectures, underlyingError: taskError))
} else {
return error
}
}
}
/// Extracts the built product and debug information from a build described by `settings` and adds it to an xcframework
/// in `directoryURL`. Sends the xcframework's URL when complete.
private func mergeIntoXCFramework(in directoryURL: URL, settings: BuildSettings) -> SignalProducer<URL, CarthageError> {
let xcframework = SignalProducer(result: settings.productName).map { productName in
directoryURL.appendingPathComponent(productName).appendingPathExtension("xcframework")
}
let framework = SignalProducer(result: settings.wrapperURL.map({ $0.resolvingSymlinksInPath() }))
let buildDSYMs = SignalProducer(result: settings.wrapperURL)
.filter { _ in settings.machOType.value != .staticlib }
.flatMap(.concat, createDebugInformation)
.ignoreTaskData()
.map({ $0 })
let buildSymbolMaps = SignalProducer(result: settings.wrapperURL)
.filter { _ in settings.bitcodeEnabled.value == true }
.flatMap(.concat, BCSymbolMapsForFramework)
.filter({ (try? $0.checkResourceIsReachable()) ?? false })
.map({ $0 })
let buildDebugSymbols = buildDSYMs.concat(buildSymbolMaps).collect()
let platformName = SignalProducer(result: settings.platformTripleOS)
let fileManager = FileManager.default
let createTemporaryDirectory = fileManager.reactive.createTemporaryDirectoryWithTemplate("carthage-xcframework-XXXXXX")
return SignalProducer.combineLatest(
framework,
buildDebugSymbols,
platformName,
xcframework,
createTemporaryDirectory
).flatMap(.concat) { frameworkURL, debugSymbols, platformName, xcframeworkURL, temporaryDirectory -> SignalProducer<URL, CarthageError> in
let outputURL = temporaryDirectory.appendingPathComponent(xcframeworkURL.lastPathComponent)
return mergeIntoXCFramework(
xcframeworkURL,
framework: frameworkURL,
debugSymbols: debugSymbols,
platformName: platformName,
variant: settings.platformTripleVariant.value,
outputURL: outputURL
)
.mapError(CarthageError.taskError)
.attempt { replacementURL in
return Result(at: xcframeworkURL) { url in
if fileManager.fileExists(atPath: url.path) {
try fileManager.removeItem(at: url)
}
try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try fileManager.copyItem(at: replacementURL, to: url)
}.flatMap { _ in
Result(at: temporaryDirectory) { try fileManager.removeItem(at: $0) }
}
}
.then(SignalProducer(value: xcframeworkURL))
}
}
/// A callback function used to determine whether or not an SDK should be built
public typealias SDKFilterCallback = (_ sdk: Set<SDK>, _ scheme: Scheme, _ configuration: String, _ project: ProjectLocator) -> Result<Set<SDK>, CarthageError>
/// Builds one scheme of the given project, for all supported SDKs.
///
/// Returns a signal of all standard output from `xcodebuild`, and a signal
/// which will send the URL to each product successfully built.
public func buildScheme( // swiftlint:disable:this function_body_length cyclomatic_complexity
_ scheme: Scheme,
withOptions options: BuildOptions,
inProject project: ProjectLocator,
rootDirectoryURL: URL,
workingDirectoryURL: URL,
sdkFilter: @escaping SDKFilterCallback = { sdks, _, _, _ in .success(sdks) }
) -> SignalProducer<TaskEvent<URL>, CarthageError> {
precondition(workingDirectoryURL.isFileURL)
let buildArgs = BuildArguments(
project: project,
scheme: scheme,
configuration: options.configuration,
derivedDataPath: options.derivedDataPath,
toolchain: options.toolchain
)
let buildURL = rootDirectoryURL.appendingPathComponent(Constants.binariesFolderPath)
return BuildSettings.SDKsForScheme(scheme, inProject: project)
.flatMap(.concat) { sdk -> SignalProducer<SDK, CarthageError> in
return BuildSettings.denySDKUnderXcodesSub14IfWatchOSOrTVOSAndProjectsDoesNotSpecifySatisfactoryBitcodeSetting(sdk, under: buildArgs)
.filterMap { $1 ? $0 as Optional<SDK> : nil }
}
.reduce(into: [] as Set) { $0.formUnion([$1]) }
.flatMap(.concat) { sdks -> SignalProducer<(String, [SDK]), CarthageError> in
if sdks.isEmpty { fatalError("No SDKs found for scheme \(scheme)") }
// fatalError in unlikely case that propogated logic error from Carthage authors
// has become unrecoverable
return sdkFilter(sdks, scheme, options.configuration, project).analysis(
ifSuccess: { filteredSDKs in
SignalProducer<(String, [SDK]), CarthageError>(
Dictionary(grouping: filteredSDKs, by: { $0.relativePath }).lazy.map { ($0, $1) }
)
}, ifFailure: { error in
SignalProducer<(String, [SDK]), CarthageError>(error: error)
})
}
.flatMap(.concat) { relativePath, sdks -> SignalProducer<TaskEvent<URL>, CarthageError> in
let folderURL = rootDirectoryURL.appendingPathComponent(relativePath, isDirectory: true).resolvingSymlinksInPath()
switch sdks.count {
case 1:
return build(sdk: sdks[0], with: buildArgs, in: workingDirectoryURL)
.flatMapTaskEvents(.merge) { settings in
if options.useXCFrameworks {
return mergeIntoXCFramework(in: buildURL, settings: settings)
} else {
return copyBuildProductIntoDirectory(settings.productDestinationPath(in: folderURL), settings)
}
}
case 2:
let (simulatorSDKs, deviceSDKs) = SDK.splitSDKs(sdks)
guard let deviceSDK = deviceSDKs.first else {
fatalError("Could not find device SDK in \(sdks)")
}
guard let simulatorSDK = simulatorSDKs.first else {
fatalError("Could not find simulator SDK in \(sdks)")
}
return settingsByTarget(build(sdk: deviceSDK, with: buildArgs, in: workingDirectoryURL))
.flatMap(.concat) { settingsEvent -> SignalProducer<TaskEvent<(BuildSettings, BuildSettings)>, CarthageError> in
switch settingsEvent {
case let .launch(task):
return SignalProducer(value: .launch(task))
case let .standardOutput(data):
return SignalProducer(value: .standardOutput(data))
case let .standardError(data):
return SignalProducer(value: .standardError(data))
case let .success(deviceSettingsByTarget):
return settingsByTarget(
build(sdk: simulatorSDK,
with: buildArgs,
in: workingDirectoryURL)
)
.flatMapTaskEvents(.concat) { (simulatorSettingsByTarget: [String: BuildSettings]) -> SignalProducer<(BuildSettings, BuildSettings), CarthageError> in
assert(
deviceSettingsByTarget.count == simulatorSettingsByTarget.count,
"Number of targets built for \(deviceSDK) (\(deviceSettingsByTarget.count)) does not match "
+ "number of targets built for \(simulatorSDK) (\(simulatorSettingsByTarget.count))"
)
return SignalProducer { observer, lifetime in
for (target, deviceSettings) in deviceSettingsByTarget {
if lifetime.hasEnded {
break
}
let simulatorSettings = simulatorSettingsByTarget[target]
assert(simulatorSettings != nil, "No \(simulatorSDK) build settings found for target \"\(target)\"")
observer.send(value: (deviceSettings, simulatorSettings!))
}
observer.sendCompleted()
}
}
}
}
.flatMapTaskEvents(.concat) { deviceSettings, simulatorSettings in
if options.useXCFrameworks {
return mergeIntoXCFramework(in: buildURL, settings: deviceSettings)
.concat(mergeIntoXCFramework(in: buildURL, settings: simulatorSettings))
} else {
return mergeBuildProducts(
deviceBuildSettings: deviceSettings,
simulatorBuildSettings: simulatorSettings,
into: deviceSettings.productDestinationPath(in: folderURL)
)
}
}
default:
fatalError("SDK count \(sdks.count) in scheme \(scheme) is not supported")
}
}
.flatMapTaskEvents(.concat) { builtProductURL -> SignalProducer<URL, CarthageError> in
guard !options.useXCFrameworks else {
// XCFrameworks have debug information embedded in them after being merged.
return SignalProducer(value: builtProductURL)
}
return UUIDsForFramework(builtProductURL)
// Only attempt to create debug info if there is at least
// one dSYM architecture UUID in the framework. This can
// occur if the framework is a static framework packaged
// like a dynamic framework.
.take(first: 1)
.flatMap(.concat) { _ -> SignalProducer<TaskEvent<URL>, CarthageError> in
return createDebugInformation(builtProductURL)
}
.then(SignalProducer<URL, CarthageError>(value: builtProductURL))
}
}
/// Fixes problem when more than one xcode target has the same Product name for same Deployment target and configuration by deleting TARGET_BUILD_DIR.
private func resolveSameTargetName(for settings: BuildSettings) -> SignalProducer<BuildSettings, CarthageError> {
switch settings.targetBuildDirectory {
case .success(let buildDir):
let result = Task("/usr/bin/xcrun", arguments: ["rm", "-rf", buildDir])
.launch()
.wait()
if let error = result.error {
return SignalProducer(error: CarthageError.taskError(error))
}
return SignalProducer(value: settings)
case .failure(let error):
return SignalProducer(error: error)
}
}
/// Using target architecture information in `settings`, copy platform-specific framework bundles from all
/// xcframeworks in `buildDirectory` to a temporary directory.
///
/// The extracted frameworks are used to support building projects which are not configured to use XCFramework products
/// from their Carthage/Build directory.
///
/// Sends the temporary directory or `nil` if there are no xcframeworks to extract. The directory is _not_ deleted
/// upon disposal, so that asynchronous build actions can use extracted frameworks after the producer has completed.
func extractXCFrameworks(in buildDirectory: URL, for settings: BuildSettings) -> SignalProducer<URL?, CarthageError> {
let isRelativeToBuildDirectory = { (url: URL) -> Bool in
// `url` might not exist (e.g. it's "Carthage/Build/iOS" and an "iOS" directory was never created). In order
// for resolvingSymlinksInPath to resolve as much of the path as it can, reduce it to the nearest extant ancestor.
var extantURL = url
while (try? extantURL.checkResourceIsReachable()) == nil {
extantURL.deleteLastPathComponent()
}
return extantURL.resolvingSymlinksInPath().path.starts(with: buildDirectory.resolvingSymlinksInPath().path)
}
guard let platformTripleOS = settings.platformTripleOS.value,
let frameworkSearchPaths = settings.frameworkSearchPaths.value,
frameworkSearchPaths.contains(where: isRelativeToBuildDirectory) else {
// Skip extracting xcframeworks if this project doesn't declare its OS triple, or if it doesn't link
// against any frameworks in Carthage/Build.
return SignalProducer(value: nil)
}
let findFrameworks = SignalProducer<[URL]?, CarthageError> {
try? FileManager.default.contentsOfDirectory(at: buildDirectory.resolvingSymlinksInPath(), includingPropertiesForKeys: nil)
}
.skipNil()
.flatten()
.filter { $0.pathExtension == "xcframework" }
.flatMap(.merge) { url -> SignalProducer<URL, CarthageError> in
frameworkBundlesInURL(url, compatibleWith: platformTripleOS, variant: settings.platformTripleVariant.value)
.mapError { .readFailed(url, $0 as NSError) }
.map { $0.bundleURL }
}
let makeTemporaryDirectory = SignalProducer<URL, CarthageError> { () -> Result<URL, CarthageError> in
var templatePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("carthage-xcframework-XXXX").utf8CString
let result = templatePath.withUnsafeMutableBufferPointer({ mkdtemp($0.baseAddress) })
let temporaryURL = URL(
fileURLWithPath: templatePath.withUnsafeBufferPointer { String(validatingUTF8: $0.baseAddress!)! }
)
guard result != nil else {
return .failure(.writeFailed(temporaryURL, NSError(domain: NSPOSIXErrorDomain, code: Int(errno))))
}
return .success(temporaryURL)
}
// Copy frameworks into the temporary directory. Send its URL once if _any_ frameworks were copied, or `nil` if
// no matching frameworks were found.
return makeTemporaryDirectory.flatMap(.concat) { temporaryURL -> SignalProducer<URL?, CarthageError> in
findFrameworks.attempt { url in
let destination = temporaryURL.appendingPathComponent(url.lastPathComponent)
return Result(at: destination) { try FileManager.default.copyItem(at: url, to: $0) }
}.map { _ in temporaryURL }
}
.concat(value: nil)
.collect()
.map { $0.first! }
}
/// Runs the build for a given sdk and build arguments, optionally performing a clean first
// swiftlint:disable:next function_body_length
private func build(
sdk: SDK,
with buildArgs: BuildArguments,
in workingDirectoryURL: URL
) -> SignalProducer<TaskEvent<BuildSettings>, CarthageError> {
var argsForLoading = buildArgs
argsForLoading.sdk = sdk
argsForLoading.onlyActiveArchitecture = false
var argsForBuilding = argsForLoading
// If SDK is the iOS simulator, then also find and set a valid destination.
// This fixes problems when the project deployment version is lower than
// the target's one and includes simulators unsupported by the target.
//
// Example: Target is at 8.0, project at 7.0, xcodebuild chooses the first
// simulator on the list, iPad 2 7.1, which is invalid for the target.
//
// See https://github.com/Carthage/Carthage/issues/417.
func fetchDestination() -> SignalProducer<String?, CarthageError> {
// Specifying destination seems to be required for building with
// simulator SDKs since Xcode 7.2.
if sdk.isSimulator {
let destinationLookup = Task("/usr/bin/xcrun", arguments: [ "simctl", "list", "devices", "--json" ])
return destinationLookup.launch()
.mapError(CarthageError.taskError)
.ignoreTaskData()
.flatMap(.concat) { (data: Data) -> SignalProducer<Simulator, CarthageError> in
if let selectedSimulator = selectAvailableSimulator(of: sdk, from: data) {
return .init(value: selectedSimulator)
} else {
return .init(error: CarthageError.noAvailableSimulators(platformName: sdk.platformSimulatorlessFromHeuristic))
}
}
.map { "platform=\(sdk.platformSimulatorlessFromHeuristic) Simulator,id=\($0.udid.uuidString)" }
}
return SignalProducer(value: nil)
}
return fetchDestination()
.flatMap(.concat) { destination -> SignalProducer<TaskEvent<BuildSettings>, CarthageError> in
if let destination = destination {
argsForBuilding.destination = destination
// Also set the destination lookup timeout. Since we're building
// for the simulator the lookup shouldn't take more than a
// fraction of a second, but we set to 3 just to be safe.
argsForBuilding.destinationTimeout = 3
}
// Use `archive` action when building device SDKs to disable LLVM Instrumentation.
//
// See https://github.com/Carthage/Carthage/issues/2056
// and https://developer.apple.com/library/content/qa/qa1964/_index.html.
let xcodebuildAction: BuildArguments.Action = sdk.isDevice ? .archive : .build
return BuildSettings.load(with: argsForLoading, for: xcodebuildAction)
.filter { settings in
// Only copy build products that are frameworks
guard let frameworkType = settings.frameworkType.value, shouldBuildFrameworkType(frameworkType), let projectPath = settings.projectPath.value else {
return false
}
// Do not copy build products that originate from the current project's own carthage dependencies
let projectURL = URL(fileURLWithPath: projectPath)
let dependencyCheckoutDir = workingDirectoryURL.appendingPathComponent(Constants.checkoutsFolderPath, isDirectory: true)
return !dependencyCheckoutDir.hasSubdirectory(projectURL)
}
.flatMap(.concat) { settings in resolveSameTargetName(for: settings) }
.collect()
.flatMap(.concat) { settings -> SignalProducer<([BuildSettings], URL?), CarthageError> in
// Use the build settings of an arbitrary target to extract platform-specific frameworks from any xcframeworks.
// Theoretically, different targets in the scheme could map to different LLVM targets, but it's hard to
// imagine how that would work since they are all building to the same destination.
guard let firstTargetSettings = settings.first else { return .empty }
let buildDirectoryURL = workingDirectoryURL.appendingPathComponent(Constants.binariesFolderPath)
return extractXCFrameworks(in: buildDirectoryURL, for: firstTargetSettings).map { (settings, $0) }
}
.flatMap(.concat) { settings, extractedXCFrameworksDir -> SignalProducer<TaskEvent<BuildSettings>, CarthageError> in
let actions: [String] = {
var result: [String] = [xcodebuildAction.rawValue]
if settings.contains(where: { UInt64($0["XCODE_VERSION_ACTUAL"].recover("")) ?? 0 >= 1230 }) {
// Fixes Xcode 12.3 refusing to link against fat binaries
// "Building for iOS Simulator, but the linked and embedded framework 'REDACTED.framework' was built for iOS + iOS Simulator."
result += [ "VALIDATE_WORKSPACE=NO" ]
}
if xcodebuildAction == .archive {
result += [
// Prevent generating unnecessary empty `.xcarchive`
// directories.
"-archivePath", (NSTemporaryDirectory() as NSString).appendingPathComponent(workingDirectoryURL.lastPathComponent),
// Disable installing when running `archive` action
// to prevent built frameworks from being deleted
// from derived data folder.
"SKIP_INSTALL=YES",
// Disable the “Instrument Program Flow” build
// setting for both GCC and LLVM as noted in
// https://developer.apple.com/library/content/qa/qa1964/_index.html.
"GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO",
// Disable the “Generate Test Coverage Files” build
// setting for GCC as noted in
// https://developer.apple.com/library/content/qa/qa1964/_index.html.
"CLANG_ENABLE_CODE_COVERAGE=NO",
// Disable the "Strip Linked Product" build
// setting so we can later generate a dSYM