forked from nsoperations/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FrameworkExtensions.swift
463 lines (389 loc) · 17.2 KB
/
FrameworkExtensions.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
import Foundation
import Result
import ReactiveSwift
import ReactiveTask
extension String {
/// Returns a producer that will enumerate each line of the receiver, then
/// complete.
internal var linesProducer: SignalProducer<String, NoError> {
return SignalProducer { observer, lifetime in
self.enumerateLines { line, stop in
observer.send(value: line)
if lifetime.hasEnded {
stop = true
}
}
observer.sendCompleted()
}
}
}
extension Signal {
/// 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> {
// swiftlint:disable:previous cyclomatic_complexity function_body_length
return Signal<(Value, U), Error> { observer, lifetime 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()
lifetime += 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()
}
}
}
}
}
extension SignalProducer {
/// 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>(value: true))
.flatMapError { _ in .init(value: false) }
}
}
extension SignalProducer 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 SignalProducer {
/// Start the producer, then block, waiting for events: `value` and
/// `completed`.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, or when more
/// than one value is sent, a CarthageError.internalError will be returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// CarthageError.internalError when 0 or more than 1 events are received.
public func only(file: String = #file, line: Int = #line) -> Result<Value, Error> {
guard let result = self.single() else {
fatalError("Got no result while result was expected in file \(file) line #\(line)")
}
return result
}
@discardableResult
public func getOnly(file: String = #file, line: Int = #line) throws -> Value {
return try self.only(file: file, line: line).get()
}
}
extension Signal 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<Value.Value, Error> { observer, lifetime in
var receivedValue = false
var receivedError: Error?
lifetime += 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 SignalProducer 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() }
}
}
typealias CarthageResult<Value> = Result<Value, CarthageError>
extension Result where Error == CarthageError {
/// Constructs a result from a throwing closure taking a `URL`, failing with `CarthageError` if throw occurs.
/// - parameter carthageError: Defaults to `CarthageError.writeFailed`.
internal init(
at url: URL,
carthageError: (URL, NSError) -> CarthageError = CarthageError.writeFailed,
attempt closure: (URL) throws -> Value
) {
do {
self = .success(try closure(url))
} catch let error as NSError {
self = .failure(carthageError(url, error))
}
}
static func catching(file: String = #file, line: Int = #line, _ body: () throws -> Success) -> CarthageResult<Value> {
do {
return .success(try body())
} catch let error as CarthageError {
return .failure(error)
} catch {
return .failure(CarthageError.assertionError(file: file, line: line, description: "Unexpected error thrown: \(error)"))
}
}
}
extension URL {
fileprivate func volumeSupportsFileCloning() throws -> Bool {
guard #available(macOS 10.12, *) else { return false }
let key = URLResourceKey.volumeSupportsFileCloningKey
let values = try self.resourceValues(forKeys: [key]).allValues
func error(failureReason: String) -> NSError {
return NSError(
domain: NSCocoaErrorDomain,
code: CocoaError.fileReadUnknown.rawValue,
userInfo: [NSURLErrorKey: self, NSLocalizedFailureReasonErrorKey: failureReason]
)
}
guard values.count == 1 else {
throw error(failureReason: "Expected single resource value: «actual count: \(values.count)».")
}
guard let volumeSupportsFileCloning = values[key] as? NSNumber else {
throw error(failureReason: "Unable to extract a NSNumber from «\(String(describing: values.first))».")
}
return volumeSupportsFileCloning.boolValue
}
}
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)
}
// swiftlint:disable identifier_name
/// rdar://32984063 When on APFS, `FileManager.copyItem(at:to)` can result in zero'd out binary files, due to the cloning functionality.
/// To avoid this, we drop down to the copyfile c API, explicitly not passing the 'CLONE' flags so we always copy the data normally.
/// - Parameter avoiding·rdar·32984063: When `false`, passthrough to Foundation’s `FileManager.copyItem(at:to:)`.
internal func copyItem(at from: URL, to: URL, avoiding·rdar·32984063: Bool) throws {
guard avoiding·rdar·32984063, try from.volumeSupportsFileCloning() else {
return try self.copyItem(at: from, to: to)
}
try from.path.withCString { fromCStr in
try to.path.withCString { toCStr in
let state = copyfile_state_alloc()
// Can't use COPYFILE_NOFOLLOW. Restriction relaxed to COPYFILE_NOFOLLOW_SRC
// http://openradar.appspot.com/32984063
let status = copyfile(fromCStr, toCStr, state, UInt32(COPYFILE_ALL | COPYFILE_RECURSIVE | COPYFILE_NOFOLLOW_SRC))
copyfile_state_free(state)
if status < 0 {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil)
}
}
}
}
}
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, lifetime 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 !lifetime.hasEnded {
if let url = enumerator.nextObject() as? URL {
let value = (enumerator, url)
observer.send(value: value)
} else {
break
}
}
observer.sendCompleted()
}
}
/// Creates a temporary directory with the given template name. Sends the
/// URL of the temporary directory and completes if successful, else errors.
///
/// The template name should adhere to the format required by the mkdtemp()
/// function.
public func createTemporaryDirectoryWithTemplate(_ template: String) -> SignalProducer<URL, CarthageError> {
return SignalProducer { [base = self.base] () -> Result<URL, CarthageError> in
return base.createTemporaryDirectoryWithTemplate(template)
}
}
public func createTemporaryDirectory() -> SignalProducer<URL, CarthageError> {
return createTemporaryDirectoryWithTemplate(Files.tempDirTemplate)
}
}
extension FileManager {
func createTemporaryDirectory() -> Result<URL, CarthageError> {
return createTemporaryDirectoryWithTemplate(Files.tempDirTemplate)
}
func createTemporaryDirectoryWithTemplate(_ template: String) -> Result<URL, CarthageError> {
let temporaryDirectory: NSString
if #available(macOS 10.12, *) {
temporaryDirectory = self.temporaryDirectory.path as NSString
} else {
temporaryDirectory = NSTemporaryDirectory() as NSString
}
var temporaryDirectoryTemplate: ContiguousArray<CChar> = temporaryDirectory.appendingPathComponent(template).utf8CString
let result: UnsafeMutablePointer<Int8>? = temporaryDirectoryTemplate
.withUnsafeMutableBufferPointer { (template: inout UnsafeMutableBufferPointer<CChar>) -> UnsafeMutablePointer<CChar> in
mkdtemp(template.baseAddress)
}
if result == nil {
return .failure(.taskError(.posixError(errno)))
}
let temporaryPath = temporaryDirectoryTemplate.withUnsafeBufferPointer { (ptr: UnsafeBufferPointer<CChar>) -> String in
return String(validatingUTF8: ptr.baseAddress!)!
}
return .success(URL(fileURLWithPath: temporaryPath, isDirectory: true))
}
}
private let defaultSessionError = NSError(domain: Constants.bundleIdentifier, 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, lifetime 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))
}
}
lifetime.observeEnded {
task.cancel()
}
task.resume()
}
}
}
extension Task {
init(launchCommand: String, shell: String = "/bin/sh", workingDirectoryPath: String? = nil, environment: [String: String]? = nil) {
let arguments = ["-c", launchCommand]
self.init(shell, arguments: arguments, workingDirectoryPath: workingDirectoryPath, environment: environment)
}
func getData(input: Data? = nil) -> Result<(stdOut: Data, stdErr: Data), TaskError> {
var stdOutData = Data()
var stdErrData = Data()
return launch(standardInput: input.map { SignalProducer(value: $0) })
.on(value: { (taskEvent: TaskEvent<Data>) in
switch taskEvent {
case .standardError(let data):
stdOutData += data
case .standardOutput(let data):
stdErrData += data
default:
break
}
}
)
.wait()
.map { return (stdOutData, stdErrData) }
}
func getStdOutData(input: Data? = nil) -> Result<Data, TaskError> {
return launch(standardInput: input.map { SignalProducer(value: $0) })
.ignoreTaskData()
.first() ?? Result.success(Data())
}
func getStdOutString(input: Data? = nil, encoding: String.Encoding = .utf8) -> Result<String, TaskError> {
return getStdOutData(input: input)
.map { String(data: $0, encoding: encoding) ?? "" }
}
}