forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXcode.swift
1567 lines (1330 loc) · 57.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
//
// Xcode.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-10-11.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
import ReactiveCocoa
import ReactiveTask
/// The name of the folder into which Carthage puts binaries it builds (relative
/// to the working directory).
public let CarthageBinariesFolderPath = "Carthage/Build"
/// Describes how to locate the actual project or workspace that Xcode should
/// build.
public enum ProjectLocator: Comparable {
/// The `xcworkspace` at the given file URL should be built.
case Workspace(NSURL)
/// The `xcodeproj` at the given file URL should be built.
case ProjectFile(NSURL)
/// The file URL this locator refers to.
public var fileURL: NSURL {
switch self {
case let .Workspace(URL):
assert(URL.fileURL)
return URL
case let .ProjectFile(URL):
assert(URL.fileURL)
return URL
}
}
/// The number of levels deep the current object is in the directory hierarchy.
public var level: Int {
return fileURL.pathComponents!.count - 1
}
}
public func ==(lhs: ProjectLocator, rhs: ProjectLocator) -> Bool {
switch (lhs, rhs) {
case let (.Workspace(left), .Workspace(right)):
return left == right
case let (.ProjectFile(left), .ProjectFile(right)):
return left == right
default:
return false
}
}
public func <(lhs: ProjectLocator, rhs: ProjectLocator) -> Bool {
// Prefer top-level directories
let leftLevel = lhs.level
let rightLevel = rhs.level
guard leftLevel == rightLevel else {
return leftLevel < rightLevel
}
// Prefer workspaces over projects.
switch (lhs, rhs) {
case (.Workspace, .ProjectFile):
return true
case (.ProjectFile, .Workspace):
return false
default:
return lhs.fileURL.path!.characters.lexicographicalCompare(rhs.fileURL.path!.characters)
}
}
extension ProjectLocator: CustomStringConvertible {
public var description: String {
return fileURL.lastPathComponent!
}
}
/// Attempts to locate projects and workspaces within the given directory.
///
/// Sends all matches in preferential order.
public func locateProjectsInDirectory(directoryURL: NSURL) -> SignalProducer<ProjectLocator, CarthageError> {
let enumerationOptions: NSDirectoryEnumerationOptions = [ .SkipsHiddenFiles, .SkipsPackageDescendants ]
return gitmodulesEntriesInRepository(directoryURL, revision: nil)
.map { directoryURL.appendingPathComponent($0.path) }
.concat(value: directoryURL.appendingPathComponent(CarthageProjectCheckoutsPath))
.collect()
.flatMap(.Merge) { directoriesToSkip in
return NSFileManager.defaultManager()
.carthage_enumeratorAtURL(directoryURL.URLByResolvingSymlinksInPath!, includingPropertiesForKeys: [ NSURLTypeIdentifierKey ], options: enumerationOptions, catchErrors: true)
.map { _, URL in URL }
.filter { URL in
return !directoriesToSkip.contains { $0.hasSubdirectory(URL) }
}
}
.map { URL -> ProjectLocator? in
if let UTI = URL.typeIdentifier.value {
if (UTTypeConformsTo(UTI, "com.apple.dt.document.workspace")) {
return .Workspace(URL)
} else if (UTTypeConformsTo(UTI, "com.apple.xcode.project")) {
return .ProjectFile(URL)
}
}
return nil
}
.ignoreNil()
.collect()
.map { $0.sort() }
.flatMap(.Merge) { SignalProducer<ProjectLocator, CarthageError>(values: $0) }
}
/// 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)
}
/// Sends each scheme found in the given project.
public func schemesInProject(project: ProjectLocator) -> SignalProducer<String, CarthageError> {
let task = xcodebuildTask("-list", BuildArguments(project: project))
return launchTask(task)
.ignoreTaskData()
.mapError(CarthageError.TaskError)
// xcodebuild has a bug where xcodebuild -list can sometimes hang
// indefinitely on projects that don't share any schemes, so
// automatically bail out if it looks like that's happening.
.timeoutWithError(.XcodebuildTimeout(project), afterInterval: 60, onScheduler: QueueScheduler(qos: QOS_CLASS_DEFAULT))
.retry(2)
.map { (data: NSData) -> String in
return NSString(data: data, encoding: NSStringEncoding(NSUTF8StringEncoding))! as String
}
.flatMap(.Merge) { string in
return string.linesProducer
}
.flatMap(.Merge) { line -> SignalProducer<String, CarthageError> in
// Matches one of these two possible messages:
//
// ' This project contains no schemes.'
// 'There are no schemes in workspace "Carthage".'
if line.hasSuffix("contains no schemes.") || line.hasPrefix("There are no schemes") {
return SignalProducer(error: .NoSharedSchemes(project, nil))
} else {
return SignalProducer(value: line)
}
}
.skipWhile { line in !line.hasSuffix("Schemes:") }
.skip(1)
.takeWhile { line in !line.isEmpty }
.map { (line: String) -> String in line.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }
}
/// Finds schemes of projects or workspaces, which Carthage should build, found
/// within the given directory.
public func buildableSchemesInDirectory(directoryURL: NSURL, withConfiguration configuration: String, forPlatforms platforms: Set<Platform> = []) -> SignalProducer<(ProjectLocator, [String]), CarthageError> {
precondition(directoryURL.fileURL)
return locateProjectsInDirectory(directoryURL)
.flatMap(.Concat) { project -> SignalProducer<(ProjectLocator, [String]), CarthageError> in
return schemesInProject(project)
.flatMap(.Merge) { scheme -> SignalProducer<String, CarthageError> in
let buildArguments = BuildArguments(project: project, scheme: scheme, configuration: configuration)
return shouldBuildScheme(buildArguments, platforms)
.filter { $0 }
.map { _ in scheme }
}
.collect()
.flatMapError { error in
if case .NoSharedSchemes = error {
return .init(value: [])
} else {
return .init(error: error)
}
}
.map { (project, $0) }
}
}
/// Sends pairs of a scheme and a project, the scheme actually resides in
/// the project.
public func schemesInProjects(projects: [(ProjectLocator, [String])]) -> SignalProducer<[(String, ProjectLocator)], CarthageError> {
return SignalProducer(values: projects)
.map { (project: ProjectLocator, schemes: [String]) in
// Only look for schemes that actually reside in the project
let containedSchemes = schemes.filter { (scheme: String) -> Bool in
if let schemePath = project.fileURL.appendingPathComponent("xcshareddata/xcschemes/\(scheme).xcscheme").path {
return NSFileManager.defaultManager().fileExistsAtPath(schemePath)
}
return false
}
return (project, containedSchemes)
}
.filter { (project: ProjectLocator, schemes: [String]) in
switch project {
case .ProjectFile where !schemes.isEmpty:
return true
default:
return false
}
}
.flatMap(.Concat) { project, schemes in
return .init(values: schemes.map { ($0, project) })
}
.collect()
}
/// Represents a platform to build for.
public enum Platform: String {
/// Mac OS X.
case Mac
/// iOS for device and simulator.
case iOS
/// Apple Watch device and simulator.
case watchOS
/// Apple TV device and simulator.
case tvOS
/// All supported build platforms.
public static let supportedPlatforms: [Platform] = [ .Mac, .iOS, .watchOS, .tvOS ]
/// The relative path at which binaries corresponding to this platform will
/// be stored.
public var relativePath: String {
let subfolderName = rawValue
return (CarthageBinariesFolderPath as NSString).stringByAppendingPathComponent(subfolderName)
}
/// The SDKs that need to be built for this platform.
public var SDKs: [SDK] {
switch self {
case .Mac:
return [ .MacOSX ]
case .iOS:
return [ .iPhoneSimulator, .iPhoneOS ]
case .watchOS:
return [ .watchOS, .watchSimulator ]
case .tvOS:
return [ .tvOS, .tvSimulator ]
}
}
}
// TODO: this won't be necessary anymore with Swift 2.
extension Platform: CustomStringConvertible {
public var description: String {
return rawValue
}
}
/// Represents an SDK buildable by Xcode.
public enum SDK: String {
/// Mac OS X.
case MacOSX = "macosx"
/// iOS, for device.
case iPhoneOS = "iphoneos"
/// iOS, for the simulator.
case iPhoneSimulator = "iphonesimulator"
/// watchOS, for the Apple Watch device.
case watchOS = "watchos"
/// watchSimulator, for the Apple Watch simulator.
case watchSimulator = "watchsimulator"
/// tvOS, for the Apple TV device.
case tvOS = "appletvos"
/// tvSimulator, for the Apple TV simulator.
case tvSimulator = "appletvsimulator"
public static let allSDKs: Set<SDK> = [.MacOSX, .iPhoneOS, .iPhoneSimulator, .watchOS, .watchSimulator, .tvOS, .tvSimulator]
/// Attempts to parse an SDK name from a string returned from `xcodebuild`.
public static func fromString(string: String) -> Result<SDK, CarthageError> {
return Result(self.init(rawValue: string.lowercaseString), failWith: .ParseError(description: "unexpected SDK key \"\(string)\""))
}
/// Split the given SDKs into simulator ones and device ones.
private static func splitSDKs<S: SequenceType where S.Generator.Element == SDK>(sdks: S) -> (simulators: [SDK], devices: [SDK]) {
return (
simulators: sdks.filter { $0.isSimulator },
devices: sdks.filter { !$0.isSimulator }
)
}
/// Returns whether this is a simulator SDK.
public var isSimulator: Bool {
switch self {
case .iPhoneSimulator, .watchSimulator, .tvSimulator:
return true
case _:
return false
}
}
/// The platform that this SDK targets.
public var platform: Platform {
switch self {
case .iPhoneOS, .iPhoneSimulator:
return .iOS
case .watchOS, .watchSimulator:
return .watchOS
case .tvOS, .tvSimulator:
return .tvOS
case .MacOSX:
return .Mac
}
}
}
// TODO: this won't be necessary anymore in Swift 2.
extension SDK: CustomStringConvertible {
public var description: String {
switch self {
case .iPhoneOS:
return "iOS Device"
case .iPhoneSimulator:
return "iOS Simulator"
case .MacOSX:
return "Mac OS X"
case .watchOS:
return "watchOS"
case .watchSimulator:
return "watchOS Simulator"
case .tvOS:
return "tvOS"
case .tvSimulator:
return "tvOS Simulator"
}
}
}
/// Represents a build setting whether full bitcode should be embedded in the
/// binary.
public enum BitcodeGenerationMode: String {
/// Only bitcode marker will be embedded.
case Marker = "marker"
/// Full bitcode will be embedded.
case Bitcode = "bitcode"
}
/// Describes the type of product built by an Xcode target.
public enum ProductType: String {
/// A framework bundle.
case Framework = "com.apple.product-type.framework"
/// A static library.
case StaticLibrary = "com.apple.product-type.library.static"
/// A unit test bundle.
case TestBundle = "com.apple.product-type.bundle.unit-test"
/// Attempts to parse a product type from a string returned from
/// `xcodebuild`.
public static func fromString(string: String) -> Result<ProductType, CarthageError> {
return Result(self.init(rawValue: string), failWith: .ParseError(description: "unexpected product type \"\(string)\""))
}
}
/// Describes the type of Mach-O files.
/// See https://developer.apple.com/library/mac/documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW73.
public enum MachOType: String {
/// Executable binary.
case Executable = "mh_executable"
/// Bundle binary.
case Bundle = "mh_bundle"
/// Relocatable object file.
case Object = "mh_object"
/// Dynamic library binary.
case Dylib = "mh_dylib"
/// Static library binary.
case Staticlib = "staticlib"
/// Attempts to parse a Mach-O type from a string returned from `xcodebuild`.
public static func fromString(string: String) -> Result<MachOType, CarthageError> {
return Result(self.init(rawValue: string), failWith: .ParseError(description: "unexpected Mach-O type \"\(string)\""))
}
}
/// Describes the type of frameworks.
private 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
}
}
}
/// Describes the type of packages, given their CFBundlePackageType.
private 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"
}
/// A map of build settings and their values, as generated by Xcode.
public struct BuildSettings {
/// The target to which these settings apply.
public let target: String
/// All build settings given at initialization.
public let settings: Dictionary<String, String>
public init(target: String, settings: Dictionary<String, String>) {
self.target = target
self.settings = settings
}
/// Matches lines of the forms:
///
/// Build settings for action build and target "ReactiveCocoaLayout Mac":
/// Build settings for action test and target CarthageKitTests:
private static let targetSettingsRegex = try! NSRegularExpression(pattern: "^Build settings for action (?:\\S+) and target \\\"?([^\":]+)\\\"?:$", options: [ .CaseInsensitive, .AnchorsMatchLines ])
/// Invokes `xcodebuild` to retrieve build settings for the given build
/// arguments.
///
/// Upon .success, sends one BuildSettings value for each target included in
/// the referenced scheme.
public static func loadWithArguments(arguments: BuildArguments) -> SignalProducer<BuildSettings, CarthageError> {
// xcodebuild (in Xcode 8) has a bug where xcodebuild -showBuildSettings
// can hang indefinitely on projects that contain core data models.
// rdar://27052195
// Including the action "clean" works around this issue, which is further
// discussed here: https://forums.developer.apple.com/thread/50372
let task = xcodebuildTask(["clean", "-showBuildSettings"], arguments)
return launchTask(task)
.ignoreTaskData()
.mapError(CarthageError.TaskError)
// xcodebuild has a bug where xcodebuild -showBuildSettings
// can sometimes hang indefinitely on projects that don't
// share any schemes, so automatically bail out if it looks
// like that's happening.
.timeoutWithError(.XcodebuildTimeout(arguments.project), afterInterval: 30, onScheduler: QueueScheduler(qos: QOS_CLASS_DEFAULT))
.retry(5)
.map { (data: NSData) -> String in
return NSString(data: data, encoding: NSStringEncoding(NSUTF8StringEncoding))! as String
}
.flatMap(.Merge) { (string: String) -> SignalProducer<BuildSettings, CarthageError> in
return SignalProducer { observer, disposable in
var currentSettings: [String: String] = [:]
var currentTarget: String?
let flushTarget = { () -> () in
if let currentTarget = currentTarget {
let buildSettings = self.init(target: currentTarget, settings: currentSettings)
observer.sendNext(buildSettings)
}
currentTarget = nil
currentSettings = [:]
}
(string as NSString).enumerateLinesUsingBlock { (line, stop) in
if disposable.disposed {
stop.memory = true
return
}
if let result = self.targetSettingsRegex.firstMatchInString(line, options: [], range: NSMakeRange(0, (line as NSString).length)) {
let targetRange = result.rangeAtIndex(1)
flushTarget()
currentTarget = (line as NSString).substringWithRange(targetRange)
return
}
let trimSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let components = line.characters
.split(1) { $0 == "=" }
.map { String($0).stringByTrimmingCharactersInSet(trimSet) }
if components.count == 2 {
currentSettings[components[0]] = components[1]
}
}
flushTarget()
observer.sendCompleted()
}
}
}
/// Determines which SDKs the given scheme builds for, by default.
///
/// If an SDK is unrecognized or could not be determined, an error will be
/// sent on the returned signal.
public static func SDKsForScheme(scheme: String, inProject project: ProjectLocator) -> SignalProducer<SDK, CarthageError> {
return loadWithArguments(BuildArguments(project: project, scheme: scheme))
.take(1)
.flatMap(.Merge) { $0.buildSDKs }
}
/// Returns the value for the given build setting, or an error if it could
/// not be determined.
public subscript(key: String) -> Result<String, CarthageError> {
if let value = settings[key] {
return .Success(value)
} else {
return .Failure(.MissingBuildSetting(key))
}
}
/// Attempts to determine the SDKs this scheme builds for.
public var buildSDKs: SignalProducer<SDK, CarthageError> {
let supportedPlatforms = self["SUPPORTED_PLATFORMS"]
if let supportedPlatforms = supportedPlatforms.value {
let platforms = supportedPlatforms.characters.split { $0 == " " }.map(String.init)
return SignalProducer<String, CarthageError>(values: platforms)
.map { platform in SignalProducer(result: SDK.fromString(platform)) }
.flatten(.Merge)
}
let firstBuildSDK = self["PLATFORM_NAME"].flatMap(SDK.fromString)
return SignalProducer(result: firstBuildSDK)
}
/// Attempts to determine the ProductType specified in these build settings.
public var productType: Result<ProductType, CarthageError> {
return self["PRODUCT_TYPE"].flatMap(ProductType.fromString)
}
/// Attempts to determine the MachOType specified in these build settings.
public var machOType: Result<MachOType, CarthageError> {
return self["MACH_O_TYPE"].flatMap(MachOType.fromString)
}
/// Attempts to determine the FrameworkType identified by these build settings.
private var frameworkType: Result<FrameworkType?, CarthageError> {
return (productType &&& machOType).map(FrameworkType.init)
}
/// Attempts to determine the URL to the built products directory.
public var builtProductsDirectoryURL: Result<NSURL, CarthageError> {
return self["BUILT_PRODUCTS_DIR"].map { productsDir in
return NSURL.fileURLWithPath(productsDir, isDirectory: true)
}
}
/// Attempts to determine the relative path (from the build folder) to the
/// built executable.
public var executablePath: Result<String, CarthageError> {
return self["EXECUTABLE_PATH"]
}
/// Attempts to determine the URL to the built executable.
public var executableURL: Result<NSURL, CarthageError> {
return builtProductsDirectoryURL.flatMap { builtProductsURL in
return self.executablePath.map { executablePath in
return builtProductsURL.appendingPathComponent(executablePath)
}
}
}
/// Attempts to determine the name of the built product's wrapper bundle.
public var wrapperName: Result<String, CarthageError> {
return self["WRAPPER_NAME"]
}
/// Attempts to determine the URL to the built product's wrapper.
public var wrapperURL: Result<NSURL, CarthageError> {
return builtProductsDirectoryURL.flatMap { builtProductsURL in
return self.wrapperName.map { wrapperName in
return builtProductsURL.appendingPathComponent(wrapperName)
}
}
}
/// Attempts to determine whether bitcode is enabled or not.
public var bitcodeEnabled: Result<Bool, CarthageError> {
return self["ENABLE_BITCODE"].map { $0 == "YES" }
}
/// Attempts to determine the relative path (from the build folder) where
/// the Swift modules for the built product will exist.
///
/// If the product does not build any modules, `nil` will be returned.
private var relativeModulesPath: Result<String?, CarthageError> {
if let moduleName = self["PRODUCT_MODULE_NAME"].value {
return self["CONTENTS_FOLDER_PATH"].map { contentsPath in
let path1 = (contentsPath as NSString).stringByAppendingPathComponent("Modules")
let path2 = (path1 as NSString).stringByAppendingPathComponent(moduleName)
return (path2 as NSString).stringByAppendingPathExtension("swiftmodule")
}
} else {
return .Success(nil)
}
}
/// Attempts to determine the code signing identity.
public var codeSigningIdentity: Result<String, CarthageError> {
return self["CODE_SIGN_IDENTITY"]
}
/// Attempts to determine if ad hoc code signing is allowed.
public var adHocCodeSigningAllowed: Result<Bool, CarthageError> {
return self["AD_HOC_CODE_SIGNING_ALLOWED"].map { $0 == "YES" }
}
}
extension BuildSettings: CustomStringConvertible {
public var description: String {
return "Build settings for target \"\(target)\": \(settings)"
}
}
/// 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: NSURL, _ settings: BuildSettings) -> SignalProducer<NSURL, CarthageError> {
let target = settings.wrapperName.map(directoryURL.appendingPathComponent)
return SignalProducer(result: target &&& settings.wrapperURL)
.flatMap(.Merge) { (target, source) in
return copyProduct(source, target)
}
.flatMap(.Merge) { url in
return copyBCSymbolMapsForBuildProductIntoDirectory(directoryURL, settings)
.then(SignalProducer(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: NSURL, _ settings: BuildSettings) -> SignalProducer<NSURL, 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: [NSURL], _ outputURL: NSURL) -> SignalProducer<(), CarthageError> {
precondition(outputURL.fileURL)
return SignalProducer<NSURL, CarthageError>(values: executableURLs)
.attemptMap { URL -> Result<String, CarthageError> in
if let path = URL.path {
return .Success(path)
} else {
return .Failure(.ParseError(description: "expected file URL to built executable, got (URL)"))
}
}
.collect()
.flatMap(.Merge) { executablePaths -> SignalProducer<TaskEvent<NSData>, CarthageError> in
let lipoTask = Task("/usr/bin/xcrun", arguments: [ "lipo", "-create" ] + executablePaths + [ "-output", outputURL.path! ])
return launchTask(lipoTask)
.mapError(CarthageError.TaskError)
}
.then(.empty)
}
/// 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: NSURL, _ destinationModuleDirectoryURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
precondition(sourceModuleDirectoryURL.fileURL)
precondition(destinationModuleDirectoryURL.fileURL)
return NSFileManager.defaultManager().carthage_enumeratorAtURL(sourceModuleDirectoryURL, includingPropertiesForKeys: [], options: [ .SkipsSubdirectoryDescendants, .SkipsHiddenFiles ], catchErrors: true)
.attemptMap { _, URL -> Result<NSURL, CarthageError> in
let lastComponent: String? = URL.lastPathComponent
let destinationURL = destinationModuleDirectoryURL.appendingPathComponent(lastComponent!).URLByResolvingSymlinksInPath!
do {
try NSFileManager.defaultManager().copyItemAtURL(URL, toURL: destinationURL)
return .Success(destinationURL)
} catch let error as NSError {
return .Failure(.WriteFailed(destinationURL, error))
}
}
}
/// Determines whether the specified framework type should be built automatically.
private func shouldBuildFrameworkType(frameworkType: FrameworkType?) -> Bool {
return frameworkType == .Dynamic
}
/// 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.loadWithArguments(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 dynamic framework target, we should indeed build this scheme.
.map { _ in true }
// Otherwise, nope.
.concat(value: false)
.take(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, disposable in
var settings: [String: BuildSettings] = [:]
producer.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
signal.observe { event in
switch event {
case let .Next(settingsEvent):
let transformedEvent = settingsEvent.map { settings in [ settings.target: settings ] }
if let transformed = transformedEvent.value {
settings = combineDictionaries(settings, rhs: transformed)
} else {
observer.sendNext(transformedEvent)
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
observer.sendNext(.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 mergeBuildProductsIntoDirectory(firstProductSettings: BuildSettings, _ secondProductSettings: BuildSettings, _ destinationFolderURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
return copyBuildProductIntoDirectory(destinationFolderURL, firstProductSettings)
.flatMap(.Merge) { productURL -> SignalProducer<NSURL, CarthageError> in
let executableURLs = (firstProductSettings.executableURL &&& secondProductSettings.executableURL).map { [ $0, $1 ] }
let outputURL = firstProductSettings.executablePath.map(destinationFolderURL.appendingPathComponent)
let mergeProductBinaries = SignalProducer(result: executableURLs &&& outputURL)
.flatMap(.Concat) { (executableURLs: [NSURL], outputURL: NSURL) -> SignalProducer<(), CarthageError> in
return mergeExecutables(executableURLs, outputURL.URLByResolvingSymlinksInPath!)
}
let sourceModulesURL = SignalProducer(result: secondProductSettings.relativeModulesPath &&& secondProductSettings.builtProductsDirectoryURL)
.filter { $0.0 != nil }
.map { (modulesPath, productsURL) -> NSURL in
return productsURL.appendingPathComponent(modulesPath!)
}
let destinationModulesURL = SignalProducer(result: firstProductSettings.relativeModulesPath)
.filter { $0 != nil }
.map { modulesPath -> NSURL in
return destinationFolderURL.appendingPathComponent(modulesPath!)
}
let mergeProductModules = zip(sourceModulesURL, destinationModulesURL)
.flatMap(.Merge) { (source: NSURL, destination: NSURL) -> SignalProducer<NSURL, CarthageError> in
return mergeModuleIntoModule(source, destination)
}
return mergeProductBinaries
.then(mergeProductModules)
.then(copyBCSymbolMapsForBuildProductIntoDirectory(destinationFolderURL, secondProductSettings))
.then(SignalProducer(value: productURL))
}
}
/// A callback function used to determine whether or not an SDK should be built
public typealias SDKFilterCallback = (sdks: [SDK], scheme: String, 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(scheme: String, withConfiguration configuration: String, inProject project: ProjectLocator, workingDirectoryURL: NSURL, derivedDataPath: String?, toolchain: String?, sdkFilter: SDKFilterCallback = { .Success($0.0) }) -> SignalProducer<TaskEvent<NSURL>, CarthageError> {
precondition(workingDirectoryURL.fileURL)
let buildArgs = BuildArguments(project: project, scheme: scheme, configuration: configuration, derivedDataPath: derivedDataPath, toolchain: toolchain)
let buildSDK = { (sdk: SDK) -> SignalProducer<TaskEvent<BuildSettings>, CarthageError> in
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" ])
return launchTask(destinationLookup)
.ignoreTaskData()
.map { data in
let string = NSString(data: data, encoding: NSStringEncoding(NSUTF8StringEncoding))!
// The output as of Xcode 6.4 is structured text so we
// parse it using regex. The destination will be omitted
// altogether if parsing fails. Xcode 7.0 beta 4 added a
// JSON output option as `xcrun simctl list devices --json`
// so this can be switched once 7.0 becomes a requirement.
let platformName = sdk.platform.rawValue
let regex = try! NSRegularExpression(pattern: "-- \(platformName) [0-9.]+ --\\n.*?\\(([0-9A-Z]{8}-([0-9A-Z]{4}-){3}[0-9A-Z]{12})\\)", options: [])
let lastDeviceResult = regex.matchesInString(string as String, options: [], range: NSRange(location: 0, length: string.length)).last
return lastDeviceResult.map { result in
// We use the ID here instead of the name as it's guaranteed to be unique, the name isn't.
let deviceID = string.substringWithRange(result.rangeAtIndex(1))
return "platform=\(platformName) Simulator,id=\(deviceID)"
}
}
.mapError(CarthageError.TaskError)
}
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
}
return BuildSettings.loadWithArguments(argsForLoading)
.filter { settings in
// Only copy build products for the framework type we care about.
if let frameworkType = settings.frameworkType.value {
return shouldBuildFrameworkType(frameworkType)
} else {
return false
}
}
.flatMap(.Concat) { settings -> SignalProducer<TaskEvent<BuildSettings>, CarthageError> in
if settings.bitcodeEnabled.value == true {
argsForBuilding.bitcodeGenerationMode = .Bitcode
}
var buildScheme = xcodebuildTask(["clean", "build"], argsForBuilding)
buildScheme.workingDirectoryPath = workingDirectoryURL.path!
return launchTask(buildScheme)
.map { taskEvent in
taskEvent.map { _ in settings }
}
.mapError(CarthageError.TaskError)
}
}
}
return BuildSettings.SDKsForScheme(scheme, inProject: project)
.flatMap(.Concat) { sdk -> SignalProducer<SDK, CarthageError> in
var argsForLoading = buildArgs
argsForLoading.sdk = sdk
return BuildSettings
.loadWithArguments(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([:]) { (sdksByPlatform: [Platform: Set<SDK>], sdk: SDK) in
var sdksByPlatform = sdksByPlatform
let platform = sdk.platform
if var sdks = sdksByPlatform[platform] {
sdks.insert(sdk)
sdksByPlatform.updateValue(sdks, forKey: platform)
} else {
sdksByPlatform[platform] = Set(arrayLiteral: sdk)
}
return sdksByPlatform
}
.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: values)
}
.flatMap(.Concat) { platform, sdks -> SignalProducer<(Platform, [SDK]), CarthageError> in
let filterResult = sdkFilter(sdks: sdks, scheme: scheme, configuration: configuration, project: project)
return SignalProducer(result: filterResult.map { (platform, $0) })
}
.filter { _, sdks in
return !sdks.isEmpty
}
.flatMap(.Concat) { platform, sdks -> SignalProducer<TaskEvent<NSURL>, CarthageError> in
let folderURL = workingDirectoryURL.appendingPathComponent(platform.relativePath, isDirectory: true).URLByResolvingSymlinksInPath!
// TODO: Generalize this further?
switch sdks.count {
case 1: