forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Xcode.swift
1400 lines (1218 loc) · 54.5 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> {
guard
let swiftHeaderURL = frameworkURL.swiftHeaderURL(),
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)
}
internal func dSYMSwiftVersion(_ dSYMURL: URL) -> SignalProducer<String, SwiftVersionError> {
// Pick one architecture
guard let arch = architecturesInPackage(dSYMURL).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
}
/// Emits the framework URL if it matches the local Swift version and errors if not.
internal func checkSwiftFrameworkCompatibility(_ frameworkURL: URL, usingToolchain toolchain: String?) -> SignalProducer<URL, SwiftVersionError> {
return SignalProducer.combineLatest(swiftVersion(usingToolchain: toolchain), frameworkSwiftVersion(frameworkURL))
.attemptMap { localSwiftVersion, frameworkSwiftVersion in
return localSwiftVersion == frameworkSwiftVersion
? .success(frameworkURL)
: .failure(.incompatibleFrameworkSwiftVersions(local: localSwiftVersion, framework: frameworkSwiftVersion))
}
}
/// Emits the framework URL if it is compatible with the build environment and errors if not.
internal func checkFrameworkCompatibility(_ frameworkURL: URL, usingToolchain toolchain: String?) -> SignalProducer<URL, SwiftVersionError> {
if isSwiftFramework(frameworkURL) {
return checkSwiftFrameworkCompatibility(frameworkURL, usingToolchain: toolchain)
} else {
return SignalProducer(value: frameworkURL)
}
}
/// Creates a task description for executing `xcodebuild` with the given
/// arguments.
public func xcodebuildTask(_ tasks: [String], _ buildArguments: BuildArguments) -> Task {
return Task("/usr/bin/xcrun", arguments: buildArguments.arguments + tasks)
}
/// Creates a task description for executing `xcodebuild` with the given
/// arguments.
public func xcodebuildTask(_ task: String, _ buildArguments: BuildArguments) -> 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 platforms: Set<Platform> = []
) -> SignalProducer<(Scheme, ProjectLocator), CarthageError> {
precondition(directoryURL.isFileURL)
let locator = ProjectLocator
.locate(in: directoryURL)
.flatMap(.concat) { 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, platforms)
.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, platforms)
.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)), platforms))
}
}
}
/// 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.
internal enum FrameworkType {
/// 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 .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, _ forPlatforms: Set<Platform>) -> SignalProducer<Bool, CarthageError> {
precondition(buildArguments.scheme != nil)
return BuildSettings.load(with: buildArguments)
.flatMap(.concat) { settings -> SignalProducer<FrameworkType?, CarthageError> in
let frameworkType = SignalProducer(result: settings.frameworkType)
if forPlatforms.isEmpty {
return frameworkType
.flatMapError { _ in .empty }
} else {
return settings.buildSDKs
.filter { forPlatforms.contains($0.platform) }
.flatMap(.merge) { _ in frameworkType }
.flatMapError { _ in .empty }
}
}
.filter(shouldBuildFrameworkType)
// If we find any framework target, we should indeed build this scheme.
.map { _ in true }
// Otherwise, nope.
.concat(value: false)
.take(first: 1)
}
/// 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> {
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))
}
}
/// A callback function used to determine whether or not an SDK should be built
public typealias SDKFilterCallback = (_ sdks: [SDK], _ scheme: Scheme, _ configuration: String, _ project: ProjectLocator) -> Result<[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
)
return BuildSettings.SDKsForScheme(scheme, inProject: project)
.flatMap(.concat) { sdk -> SignalProducer<SDK, CarthageError> in
var argsForLoading = buildArgs
argsForLoading.sdk = sdk
return BuildSettings
.load(with: argsForLoading)
.filter { settings in
// Filter out SDKs that require bitcode when bitcode is disabled in
// project settings. This is necessary for testing frameworks, which
// must add a User-Defined setting of ENABLE_BITCODE=NO.
return settings.bitcodeEnabled.value == true || ![.tvOS, .watchOS].contains(sdk)
}
.map { _ in sdk }
}
.reduce(into: [:]) { (sdksByPlatform: inout [Platform: Set<SDK>], sdk: SDK) in
let platform = sdk.platform
if var sdks = sdksByPlatform[platform] {
sdks.insert(sdk)
sdksByPlatform.updateValue(sdks, forKey: platform)
} else {
sdksByPlatform[platform] = [sdk]
}
}
.flatMap(.concat) { sdksByPlatform -> SignalProducer<(Platform, [SDK]), CarthageError> in
if sdksByPlatform.isEmpty {
fatalError("No SDKs found for scheme \(scheme)")
}
let values = sdksByPlatform.map { ($0, Array($1)) }
return SignalProducer(values)
}
.flatMap(.concat) { platform, sdks -> SignalProducer<(Platform, [SDK]), CarthageError> in
let filterResult = sdkFilter(sdks, scheme, options.configuration, project)
return SignalProducer(result: filterResult.map { (platform, $0) })
}
.filter { _, sdks in
return !sdks.isEmpty
}
.flatMap(.concat) { platform, sdks -> SignalProducer<TaskEvent<URL>, CarthageError> in
let folderURL = rootDirectoryURL.appendingPathComponent(platform.relativePath, isDirectory: true).resolvingSymlinksInPath()
switch sdks.count {
case 1:
return build(sdk: sdks[0], with: buildArgs, in: workingDirectoryURL)
.flatMapTaskEvents(.merge) { settings in
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
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
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)
}
}
/// 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
var argsForBuilding = argsForLoading
argsForBuilding.onlyActiveArchitecture = false
// 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.platform.rawValue))
}
}
.map { "platform=\(sdk.platform.rawValue) 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(carthageProjectCheckoutsPath, isDirectory: true)
return !dependencyCheckoutDir.hasSubdirectory(projectURL)
}
.flatMap(.concat) { settings in resolveSameTargetName(for: settings) }
.collect()
.flatMap(.concat) { settings -> SignalProducer<TaskEvent<BuildSettings>, CarthageError> in
let actions: [String] = {
var result: [String] = [xcodebuildAction.rawValue]
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
"STRIP_INSTALLED_PRODUCT=NO",
]
}
return result
}()
var buildScheme = xcodebuildTask(actions, argsForBuilding)
buildScheme.workingDirectoryPath = workingDirectoryURL.path
return buildScheme.launch()
.flatMapTaskEvents(.concat) { _ in SignalProducer(settings) }
.mapError(CarthageError.taskError)
}
}
}
/// Creates a dSYM for the provided dynamic framework.
public func createDebugInformation(_ builtProductURL: URL) -> SignalProducer<TaskEvent<URL>, CarthageError> {
let dSYMURL = builtProductURL.appendingPathExtension("dSYM")
let executableName = builtProductURL.deletingPathExtension().lastPathComponent
if !executableName.isEmpty {
let executable = builtProductURL.appendingPathComponent(executableName).path
let dSYM = dSYMURL.path
let dsymutilTask = Task("/usr/bin/xcrun", arguments: ["dsymutil", executable, "-o", dSYM])
return dsymutilTask.launch()
.mapError(CarthageError.taskError)
.flatMapTaskEvents(.concat) { _ in SignalProducer(value: dSYMURL) }
} else {
return .empty
}
}
/// A producer representing a scheme to be built.
///
/// A producer of this type will send the project and scheme name when building
/// begins, then complete or error when building terminates.
public typealias BuildSchemeProducer = SignalProducer<TaskEvent<(ProjectLocator, Scheme)>, CarthageError>
/// Attempts to build the dependency, then places its build product into the
/// root directory given.
///
/// Returns producers in the same format as buildInDirectory().
public func build(
dependency: Dependency,
version: PinnedVersion,
_ rootDirectoryURL: URL,
withOptions options: BuildOptions,
sdkFilter: @escaping SDKFilterCallback = { sdks, _, _, _ in .success(sdks) }
) -> BuildSchemeProducer {
let rawDependencyURL = rootDirectoryURL.appendingPathComponent(dependency.relativePath, isDirectory: true)
let dependencyURL = rawDependencyURL.resolvingSymlinksInPath()
return buildInDirectory(dependencyURL,
withOptions: options,
dependency: (dependency, version),
rootDirectoryURL: rootDirectoryURL,
sdkFilter: sdkFilter
).mapError { error in
switch (dependency, error) {
case let (_, .noSharedFrameworkSchemes(_, platforms)):
return .noSharedFrameworkSchemes(dependency, platforms)
case let (.gitHub(repo), .noSharedSchemes(project, _)):
return .noSharedSchemes(project, repo)
default:
return error
}
}
}
/// Builds the any shared framework schemes found within the given directory.
///
/// Returns a signal of all standard output from `xcodebuild`, and each scheme being built.
public func buildInDirectory( // swiftlint:disable:this function_body_length
_ directoryURL: URL,
withOptions options: BuildOptions,
dependency: (dependency: Dependency, version: PinnedVersion)? = nil,
rootDirectoryURL: URL,
sdkFilter: @escaping SDKFilterCallback = { sdks, _, _, _ in .success(sdks) }
) -> BuildSchemeProducer {
precondition(directoryURL.isFileURL)
return BuildSchemeProducer { observer, lifetime in
// Use SignalProducer.replayLazily to avoid enumerating the given directory
// multiple times.
buildableSchemesInDirectory(directoryURL,
withConfiguration: options.configuration,
forPlatforms: options.platforms
)
.flatMap(.concat) { (scheme: Scheme, project: ProjectLocator) -> SignalProducer<TaskEvent<URL>, CarthageError> in
let initialValue = (project, scheme)
let wrappedSDKFilter: SDKFilterCallback = { sdks, scheme, configuration, project in
let filteredSDKs: [SDK]
if options.platforms.isEmpty {
filteredSDKs = sdks
} else {
filteredSDKs = sdks.filter { options.platforms.contains($0.platform) }
}
return sdkFilter(filteredSDKs, scheme, configuration, project)
}
return buildScheme(
scheme,
withOptions: options,
inProject: project,
rootDirectoryURL: rootDirectoryURL,
workingDirectoryURL: directoryURL,
sdkFilter: wrappedSDKFilter
)
.mapError { error -> CarthageError in
if case let .taskError(taskError) = error {
return .buildFailed(taskError, log: nil)
} else {
return error
}
}
.on(started: {
observer.send(value: .success(initialValue))
})
}
.collectTaskEvents()
.flatMapTaskEvents(.concat) { (urls: [URL]) -> SignalProducer<(), CarthageError> in
guard let dependency = dependency else {
return createVersionFileForCurrentProject(platforms: options.platforms,
buildProducts: urls,
rootDirectoryURL: rootDirectoryURL
)
.flatMapError { _ in .empty }
}
return createVersionFile(
for: dependency.dependency,
version: dependency.version,
platforms: options.platforms,
buildProducts: urls,
rootDirectoryURL: rootDirectoryURL
)
.flatMapError { _ in .empty }
}
// Discard any Success values, since we want to
// use our initial value instead of waiting for
// completion.
.map { taskEvent -> TaskEvent<(ProjectLocator, Scheme)> in
let ignoredValue = (ProjectLocator.workspace(URL(string: ".")!), Scheme(""))
return taskEvent.map { _ in ignoredValue }
}
.filter { taskEvent in
taskEvent.value == nil
}
.startWithSignal({ signal, signalDisposable in
lifetime += signalDisposable
signal.observe(observer)
})
}
}
/// Strips a framework from unexpected architectures and potentially debug symbols,
/// optionally codesigning the result.
public func stripFramework(
_ frameworkURL: URL,
keepingArchitectures: [String],
strippingDebugSymbols: Bool,
codesigningIdentity: String? = nil
) -> SignalProducer<(), CarthageError> {
let stripArchitectures = stripBinary(frameworkURL, keepingArchitectures: keepingArchitectures)
let stripSymbols = strippingDebugSymbols ? stripDebugSymbols(frameworkURL) : .empty
// Xcode doesn't copy `Headers`, `PrivateHeaders` and `Modules` directory at
// all.
let stripHeaders = stripHeadersDirectory(frameworkURL)
let stripPrivateHeaders = stripPrivateHeadersDirectory(frameworkURL)
let stripModules = stripModulesDirectory(frameworkURL)
let sign = codesigningIdentity.map { codesign(frameworkURL, $0) } ?? .empty
return stripArchitectures