forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrameworkExtensions.swift
More file actions
369 lines (309 loc) · 10.8 KB
/
FrameworkExtensions.swift
File metadata and controls
369 lines (309 loc) · 10.8 KB
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
//
// FrameworkExtensions.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-10-31.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
import ReactiveSwift
extension String {
/// Returns a producer that will enumerate each line of the receiver, then
/// complete.
internal var linesProducer: SignalProducer<String, NoError> {
return SignalProducer { observer, disposable in
self.enumerateLines { line, stop in
observer.send(value: line)
if disposable.isDisposed {
stop = true
}
}
observer.sendCompleted()
}
}
/// Strips off a trailing string, if present.
internal func stripping(suffix: String) -> String {
if hasSuffix(suffix) {
let end = characters.index(endIndex, offsetBy: -suffix.characters.count)
return self[startIndex..<end]
} else {
return self
}
}
}
/// Merges `rhs` into `lhs` and returns the result.
internal func combineDictionaries<K, V>(_ lhs: [K: V], rhs: [K: V]) -> [K: V] {
var result = lhs
for (key, value) in rhs {
result.updateValue(value, forKey: key)
}
return result
}
extension SignalProtocol {
/// Sends each value that occurs on `signal` combined with each value that
/// occurs on `otherSignal` (repeats included).
fileprivate func permute<U>(with otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let lock = NSLock()
lock.name = "org.carthage.CarthageKit.permute"
var signalValues: [Value] = []
var signalCompleted = false
var otherValues: [U] = []
var otherCompleted = false
let compositeDisposable = CompositeDisposable()
compositeDisposable += self.observe { event in
switch event {
case let .value(value):
lock.lock()
signalValues.append(value)
for otherValue in otherValues {
observer.send(value: (value, otherValue))
}
lock.unlock()
case let .failed(error):
observer.send(error: error)
case .completed:
lock.lock()
signalCompleted = true
if otherCompleted {
observer.sendCompleted()
}
lock.unlock()
case .interrupted:
observer.sendInterrupted()
}
}
compositeDisposable += otherSignal.observe { event in
switch event {
case let .value(value):
lock.lock()
otherValues.append(value)
for signalValue in signalValues {
observer.send(value: (signalValue, value))
}
lock.unlock()
case let .failed(error):
observer.send(error: error)
case .completed:
lock.lock()
otherCompleted = true
if signalCompleted {
observer.sendCompleted()
}
lock.unlock()
case .interrupted:
observer.sendInterrupted()
}
}
return compositeDisposable
}
}
}
extension SignalProducerProtocol {
/// Sends each value that occurs on `producer` combined with each value that
/// occurs on `otherProducer` (repeats included).
fileprivate func permute<U>(with otherProducer: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return lift(Signal.permute(with:))(otherProducer)
}
/// Sends a boolean of whether the producer succeeded or failed.
internal func succeeded() -> SignalProducer<Bool, NoError> {
return self
.then(SignalProducer<Bool, Error>.init(value: true))
.flatMapError { _ in .init(value: false) }
}
}
extension SignalProducerProtocol where Value: SignalProducerProtocol, Error == Value.Error {
/// Sends all permutations of the values from the inner producers, as they arrive.
///
/// If no producers are received, sends a single empty array then completes.
internal func permute() -> SignalProducer<[Value.Value], Error> {
return self
.collect()
.flatMap(.concat) { (producers: [Value]) -> SignalProducer<[Value.Value], Error> in
var combined = SignalProducer<[Value.Value], Error>(value: [])
for producer in producers {
combined = combined
.permute(with: producer.producer)
.map { array, value in
var array = array
array.append(value)
return array
}
}
return combined
}
}
}
extension SignalProtocol where Value: EventProtocol, Value.Error == Error {
/// Dematerializes the signal, like dematerialize(), but only yields inner
/// Error events if no values were sent.
internal func dematerializeErrorsIfEmpty() -> Signal<Value.Value, Error> {
return Signal { observer in
var receivedValue = false
var receivedError: Error? = nil
return self.observe { event in
switch event {
case let .value(innerEvent):
switch innerEvent.event {
case let .value(value):
receivedValue = true
observer.send(value: value)
case let .failed(error):
receivedError = error
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
case let .failed(error):
observer.send(error: error)
case .completed:
if let receivedError = receivedError, !receivedValue {
observer.send(error: receivedError)
}
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
}
extension SignalProducerProtocol where Value: EventProtocol, Value.Error == Error {
/// Dematerializes the producer, like dematerialize(), but only yields inner
/// Error events if no values were sent.
internal func dematerializeErrorsIfEmpty() -> SignalProducer<Value.Value, Error> {
return lift { $0.dematerializeErrorsIfEmpty() }
}
}
extension Scanner {
/// Returns the current line being scanned.
internal var currentLine: String {
// Force Foundation types, so we don't have to use Swift's annoying
// string indexing.
let nsString = string as NSString
let scanRange: NSRange = NSMakeRange(scanLocation, 0)
let lineRange: NSRange = nsString.lineRange(for: scanRange)
return nsString.substring(with: lineRange)
}
}
extension URL {
/// The type identifier of the receiver, or an error if it was unable to be
/// determined.
internal var typeIdentifier: Result<String, CarthageError> {
var error: NSError?
do {
let typeIdentifier = try resourceValues(forKeys: [ .typeIdentifierKey ]).typeIdentifier
if let identifier = typeIdentifier {
return .success(identifier)
}
} catch let err as NSError {
error = err
}
return .failure(.readFailed(self, error))
}
public func hasSubdirectory(_ possibleSubdirectory: URL) -> Bool {
let standardizedSelf = self.standardizedFileURL
let standardizedOther = possibleSubdirectory.standardizedFileURL
let path = standardizedSelf.pathComponents
let otherPath = standardizedOther.pathComponents
if scheme == standardizedOther.scheme && path.count <= otherPath.count {
return Array(otherPath[path.indices]) == path
}
return false
}
/// Returns the first `URL` to match `<self>/Headers/*-Swift.h`. Otherwise `nil`.
internal func swiftHeaderURL() -> URL? {
let headersURL = self.appendingPathComponent("Headers", isDirectory: true).resolvingSymlinksInPath()
let dirContents = try? FileManager.default.contentsOfDirectory(at: headersURL, includingPropertiesForKeys: [], options: [])
return dirContents?.filter { $0.absoluteString.contains("-Swift.h") }.first
}
/// Returns the first `URL` to match `<self>/Modules/*.swiftmodule`. Otherwise `nil`.
internal func swiftmoduleURL() -> URL? {
let headersURL = self.appendingPathComponent("Modules", isDirectory: true).resolvingSymlinksInPath()
let dirContents = try? FileManager.default.contentsOfDirectory(at: headersURL, includingPropertiesForKeys: [], options: [])
return dirContents?.filter { $0.absoluteString.contains("swiftmodule") }.first
}
}
extension FileManager: ReactiveExtensionsProvider {
@available(*, deprecated, message: "Use reactive.enumerator instead")
public func carthage_enumerator(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]? = nil, options: FileManager.DirectoryEnumerationOptions = [], catchErrors: Bool = false) -> SignalProducer<(FileManager.DirectoryEnumerator, URL), CarthageError> {
return reactive.enumerator(at: url, includingPropertiesForKeys: keys, options: options, catchErrors: catchErrors)
}
}
extension Reactive where Base: FileManager {
/// Creates a directory enumerator at the given URL. Sends each URL
/// enumerated, along with the enumerator itself (so it can be introspected
/// and modified as enumeration progresses).
public func enumerator(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]? = nil, options: FileManager.DirectoryEnumerationOptions = [], catchErrors: Bool = false) -> SignalProducer<(FileManager.DirectoryEnumerator, URL), CarthageError> {
return SignalProducer { [base = self.base] observer, disposable in
let enumerator = base.enumerator(at: url, includingPropertiesForKeys: keys, options: options) { (url, error) in
if catchErrors {
return true
} else {
observer.send(error: CarthageError.readFailed(url, error as NSError))
return false
}
}!
while !disposable.isDisposed {
if let url = enumerator.nextObject() as? URL {
let value = (enumerator, url)
observer.send(value: value)
} else {
break
}
}
observer.sendCompleted()
}
}
}
private let defaultSessionError = NSError(domain: CarthageKitBundleIdentifier,
code: 1,
userInfo: nil)
extension Reactive where Base: URLSession {
/// Returns a SignalProducer which performs a downloadTask associated with an
/// `NSURLSession`
///
/// - parameters:
/// - request: A request that will be performed when the producer is
/// started
///
/// - returns: A producer that will execute the given request once for each
/// invocation of `start()`.
///
/// - note: This method will not send an error event in the case of a server
/// side error (i.e. when a response with status code other than
/// 200...299 is received).
internal func download(with request: URLRequest) -> SignalProducer<(URL, URLResponse), AnyError> {
return SignalProducer { [base = self.base] observer, disposable in
let task = base.downloadTask(with: request) { url, response, error in
if let url = url, let response = response {
observer.send(value: (url, response))
observer.sendCompleted()
} else {
observer.send(error: AnyError(error ?? defaultSessionError))
}
}
disposable += {
task.cancel()
}
task.resume()
}
}
}
/// Creates a counted set from a sequence. The counted set is represented as a
/// dictionary where the keys are elements from the sequence and values count
/// how many times elements are present in the sequence.
internal func buildCountedSet<S: Sequence>(_ sequence: S) -> [S.Iterator.Element: Int] {
return sequence.reduce([:]) { set, elem in
var set = set
if let count = set[elem] {
set[elem] = count + 1
}
else {
set[elem] = 1
}
return set
}
}