-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLSFileWrapper.m
747 lines (663 loc) · 25.9 KB
/
LSFileWrapper.m
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
//
// Copyright (c) 2013 Luke Scott
// https://github.com/lukescott/LSFileWrapper
// Copyright (c) 2020 Adam Kopeć
// https://github.com/admkopec/LSFileWrapper
// Distributed under MIT license
//
#import "LSFileWrapper.h"
@interface LSFileWrapper ()
@property (weak, nonatomic) LSFileWrapper *parent;
@property (strong, nonatomic) NSMutableDictionary<NSString*, LSFileWrapper*> *fileWrappers;
@property (strong, nonatomic) NSString *filename;
@property (strong, nonatomic) NSURL *writtenURL;
@property (strong, nonatomic) id<NSObject> content;
@property (assign, nonatomic) BOOL updated;
@property (assign, nonatomic) BOOL deleted;
@property (assign, nonatomic) BOOL cacheFile;
@end
@interface LSFileWrapper (Internal)
- (LSFileWrapper *)walkDirectoryPath:(NSString *)path create:(BOOL)create;
- (NSString *)setFileWrapper:(LSFileWrapper *)fileWrapper filename:(NSString *)filename_ replace:(BOOL)replace;
- (BOOL)getParentUpdates:(NSMutableArray *)updates withURL:(NSURL *)url;
- (void)getUpdates:(NSMutableArray *)updates withURL:(NSURL *)url;
- (void)getAll:(NSMutableArray *)updates withURL:(NSURL *)url;
- (BOOL)writeUpdates:(NSArray *)updates filemanager:(NSFileManager *)fileManager error:(NSError *__autoreleasing *)outError;
@end
@implementation LSFileWrapper
@synthesize parent;
@synthesize fileWrappers;
@synthesize filename;
@synthesize writtenURL;
@synthesize content;
@synthesize updated;
@synthesize deleted;
@synthesize cacheFile;
@synthesize isDirectory;
- (id)initFile
{
self = [super self];
if (self) {
isDirectory = NO;
_reserve = 0;
}
return self;
}
- (id)initDirectory
{
self = [super init];
if (self) {
isDirectory = YES;
_reserve = 0;
fileWrappers = [[NSMutableDictionary alloc] init];
}
return self;
}
- (id)initWithURL:(NSURL *)url isDirectory:(BOOL)isDir
{
self = [super init];
if (self) {
filename = [url lastPathComponent];
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path] isDirectory:&isDir]) {
writtenURL = url;
}
isDirectory = isDir;
_reserve = 0;
if (isDirectory) {
fileWrappers = [[NSMutableDictionary alloc] init];
for (NSURL *childUrl in [[NSFileManager defaultManager] contentsOfDirectoryAtURL:url
includingPropertiesForKeys:nil
options:0
error:nil]) {
LSFileWrapper *fileWrapper = [[LSFileWrapper alloc] initWithURL:childUrl isDirectory:NO];
[fileWrapper setParent:self];
[fileWrappers setObject:fileWrapper forKey:[childUrl lastPathComponent]];
}
}
}
return self;
}
- (NSData *)data
{
if (content == nil && writtenURL != nil) {
content = [NSData dataWithContentsOfURL:writtenURL];
// cacheFile = YES;
}
if ([content isKindOfClass:[NSData class]]) {
NSData * contentAsData = (NSData *)content;
if (!updated && writtenURL != nil) {
content = nil;
}
return contentAsData;
}
return nil;
}
- (NSString *)string
{
if (content == nil && writtenURL != nil) {
content = [NSData dataWithContentsOfURL:writtenURL];
cacheFile = YES;
}
if ([content isKindOfClass:[NSData class]]) {
content = [[NSString alloc] initWithData:(NSData*)content encoding:NSUTF8StringEncoding];
}
if ([content isKindOfClass:[NSString class]]) {
return (NSString *)content;
}
return nil;
}
- (NSDictionary *)dictionary
{
if (content == nil && writtenURL != nil) {
content = [NSData dataWithContentsOfURL:writtenURL];
cacheFile = YES;
}
if ([content isKindOfClass:[NSData class]]) {
id propList = [NSPropertyListSerialization propertyListWithData:(NSData*)content
options:NSPropertyListImmutable
format:NULL
error:NULL];
if ([propList isKindOfClass:[NSDictionary class]])
{
content = (NSDictionary*)propList;
}
}
if ([content isKindOfClass:[NSDictionary class]]) {
return (NSDictionary *)content;
}
return nil;
}
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
- (UIImage *)image
{
if (content == nil && writtenURL != nil) {
content = [UIImage imageWithContentsOfFile:writtenURL.path];
cacheFile = YES;
return (UIImage *)content;
}
if ([content isKindOfClass:[NSData class]]) {
content = [UIImage imageWithData:(NSData *)content];
}
if ([content isKindOfClass:[UIImage class]]) {
return (UIImage *)content;
}
return nil;
}
#elif TARGET_OS_OSX
- (NSImage *)image
{
if (content == nil && writtenURL != nil) {
content = [[NSImage alloc] initWithContentsOfFile:writtenURL.path];
cacheFile = YES;
return (NSImage *)content;
}
if ([content isKindOfClass:[NSData class]]) {
content = [[NSImage alloc] initWithData:(NSData *)content];
}
if ([content isKindOfClass:[NSImage class]]) {
return (NSImage *)content;
}
return nil;
}
#endif
- (void)updateContent:(id<NSObject>)content_
{
if (isDirectory) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"LSFileWrapper directory is not a file."
userInfo:nil];
return;
}
content = content_;
updated = YES;
deleted = NO;
}
- (void)deleteContent
{
content = nil;
updated = NO;
deleted = YES;
}
- (void)incReserve
{
self.reserve++;
}
- (void)decReserve
{
self.reserve--;
}
- (void)deleteUnreserved
{
if (isDirectory && fileWrappers.count > 0) {
for (LSFileWrapper *fileWrapper in [fileWrappers objectEnumerator]) {
[fileWrapper deleteUnreserved];
}
}
else if (self.reserve < 1) {
[self deleteContent];
}
}
- (LSFileWrapper *)fileWrapperWithPath:(NSString *)path
{
return [self fileWrapperWithPath:path create:NO isDirectory:NO];
}
- (NSArray<LSFileWrapper*> *)fileWrappersInPath:(NSString *)path
{
NSMutableArray<LSFileWrapper*> *array = [[NSMutableArray alloc] init];
LSFileWrapper *dirFileWrapper = ([path isEqual: @"/"] || [path isEqual: @""]) ? self : [self fileWrapperWithPath:path];
if (dirFileWrapper) {
[dirFileWrapper.fileWrappers enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, LSFileWrapper * _Nonnull obj, BOOL * _Nonnull stop) {
[array addObject:obj];
}];
}
return [array copy];
}
- (LSFileWrapper *)fileWrapperWithPath:(NSString *)path create:(BOOL)create isDirectory:(BOOL)isDir
{
NSString *dirpath = [path stringByDeletingLastPathComponent];
NSString *filename_ = [path lastPathComponent];
LSFileWrapper *dirFileWrapper = [self walkDirectoryPath:dirpath create:create];
if (!dirFileWrapper) {
return nil;
}
LSFileWrapper *fileWrapper = [dirFileWrapper.fileWrappers objectForKey:filename_];
if (!fileWrapper) {
if (!create) {
return nil;
}
if (isDir) {
fileWrapper = [[[self class] alloc] initDirectory];
}
else {
fileWrapper = [[[self class] alloc] initFile];
}
[dirFileWrapper setFileWrapper:fileWrapper filename:filename_ replace:YES];
}
return fileWrapper;
}
- (NSString *)addFileWrapper:(LSFileWrapper *)fileWrapper withFilename:(NSString *)filename_;
{
return [self setFileWrapper:fileWrapper filename:filename_ replace:NO];
}
- (void)setFileWrapper:(LSFileWrapper *)fileWrapper withFilename:(NSString *)filename_
{
[self setFileWrapper:fileWrapper filename:filename_ replace:YES];
}
- (void)removeFileWrapper:(LSFileWrapper *)fileWrapper
{
if (!isDirectory) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"LSFileWrapper file is not a directory."
userInfo:nil];
return;
}
if (fileWrapper == self) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"Cannot remove LSFileWrapper from itself."
userInfo:nil];
return;
}
[self removeFileWrapperWithPath:fileWrapper.filename];
}
- (void)removeFileWrapperWithPath:(NSString *)path
{
NSString *dirpath = [path stringByDeletingLastPathComponent];
NSString *filename_ = [path lastPathComponent];
LSFileWrapper *dirFileWrapper = [self walkDirectoryPath:dirpath create:NO];
if (!dirFileWrapper) {
return;
}
LSFileWrapper *existing = [dirFileWrapper.fileWrappers objectForKey:filename_];
if (existing.writtenURL) {
existing.deleted = YES;
}
else {
[[dirFileWrapper fileWrappers] removeObjectForKey:filename_];
}
dirFileWrapper.updated = YES;
}
- (NSString *)addContent:(id<NSObject>)content_ withFilename:(NSString *)filename_
{
LSFileWrapper *fileWrapper = [[LSFileWrapper alloc] initFile];
[fileWrapper updateContent:content_];
return [self setFileWrapper:fileWrapper filename:filename_ replace:NO];
}
- (void)setContent:(id<NSObject>)content_ withFilename:(NSString *)filename_
{
LSFileWrapper *fileWrapper = [fileWrappers objectForKey:filename_];
if (!fileWrapper) {
fileWrapper = [[LSFileWrapper alloc] initFile];
[self setFileWrapper:fileWrapper filename:filename_ replace:YES];
}
[fileWrapper updateContent:content_];
}
- (BOOL)writeUpdatesToURL:(NSURL *)url error:(NSError *__autoreleasing *)outError
{
NSMutableArray *updates = [[NSMutableArray alloc] init];
if (!updated && !isDirectory) {
return YES;
}
if (parent) {
BOOL parentOK = [self getParentUpdates:updates withURL:url];
if (parentOK == NO) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"LSFileWrapper child cannot be written to a different directory"
userInfo:nil];
}
}
[self getUpdates:updates withURL:url];
return [self writeUpdates:updates filemanager:[[NSFileManager alloc] init] error:outError];
}
- (BOOL)writeToURL:(NSURL *)url error:(NSError *__autoreleasing *)outError
{
NSMutableArray *updates = [[NSMutableArray alloc] init];
if (parent) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"LSFileWrapper child cannot be written to new URL"
userInfo:nil];
}
[self getAll:updates withURL:url];
return [self writeUpdates:updates filemanager:[[NSFileManager alloc] init] error:outError];
}
#if TARGET_OS_OSX
- (BOOL)writeToURL:(NSURL *)url forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(nullable NSURL *)absoluteOriginalContentsURL backupDocumentURL:(nullable NSURL *)backupFileURL error:(NSError *__autoreleasing *)outError
{
switch (saveOperation) {
case NSAutosaveInPlaceOperation:
// Auto overwrite
case NSSaveOperation:
// Overwrite
if (backupFileURL) {
// Optional Backup propagation
[[NSFileManager defaultManager] copyItemAtURL:url toURL:backupFileURL error:nil];
[backupFileURL setResourceValues:@{NSURLIsHiddenKey: @YES} error:nil];
}
if (absoluteOriginalContentsURL) {
if (![self writeUpdatesToURL:absoluteOriginalContentsURL error:outError]) {
return NO;
}
if (![url isEqual:absoluteOriginalContentsURL]) {
if(![[NSFileManager defaultManager] copyItemAtURL:absoluteOriginalContentsURL toURL:url error:outError]) {
return NO;
}
}
} else {
if(![self writeToURL:url error:outError]) {
return NO;
}
}
break;
case NSAutosaveAsOperation:
// Auto new with switch
case NSSaveAsOperation:
// New with switch
if(![self writeToURL:url error:outError]) {
return NO;
}
// Switches self to new NSURL
filename = [url lastPathComponent];
writtenURL = url;
isDirectory = YES;
_reserve = 0;
fileWrappers = [[NSMutableDictionary alloc] init];
for (NSURL *childUrl in [[NSFileManager defaultManager] contentsOfDirectoryAtURL:url
includingPropertiesForKeys:nil
options:0
error:nil]) {
LSFileWrapper *fileWrapper = [[LSFileWrapper alloc] initWithURL:childUrl isDirectory:NO];
[fileWrapper setParent:self];
[fileWrappers setObject:fileWrapper forKey:[childUrl lastPathComponent]];
}
[url setResourceValues:@{NSURLHasHiddenExtensionKey: @YES} error:nil];
break;
case NSAutosaveElsewhereOperation:
// Auto totally new
case NSSaveToOperation:
// Totally new
if(![self writeToURL:url error:outError]) {
return NO;
}
[url setResourceValues:@{NSURLHasHiddenExtensionKey: @YES} error:nil];
break;
default:
break;
}
return [url setResourceValues:@{NSURLContentModificationDateKey: [NSDate date]} error:outError];
}
#endif
@end
@implementation LSFileWrapper (Internal)
- (LSFileWrapper *)walkDirectoryPath:(NSString *)path create:(BOOL)create
{
if (!isDirectory) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"LSFileWrapper file is not a directory."
userInfo:nil];
return nil;
}
if ([path hasPrefix:@"/"]) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"path must be relative"
userInfo:nil];
return nil;
}
NSArray *pathComponents = [path pathComponents];
LSFileWrapper *dirFileWrapper = self;
LSFileWrapper *parentWrapper;
for (NSString *component in pathComponents) {
parentWrapper = dirFileWrapper;
dirFileWrapper = [dirFileWrapper.fileWrappers objectForKey:component];
if (!dirFileWrapper) {
if (!create) {
return nil;
}
dirFileWrapper = [[[self class] alloc] initDirectory];
[parentWrapper setFileWrapper:dirFileWrapper filename:component replace:YES];
}
}
return dirFileWrapper;
}
- (NSString *)setFileWrapper:(LSFileWrapper *)fileWrapper filename:(NSString *)filename_ replace:(BOOL)replace
{
if (!isDirectory) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"LSFileWrapper file is not a directory."
userInfo:nil];
return nil;
}
if (fileWrapper.parent) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"LSFileWrapper can only have one parent."
userInfo:nil];
return nil;
}
if (fileWrapper == self) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"Cannot add LSFileWrapper to itself."
userInfo:nil];
return nil;
}
if (fileWrapper) {
if (!replace) {
NSString *basename = [filename_ stringByDeletingPathExtension];
NSString *extension = [filename_ pathExtension];
NSString *format;
NSUInteger num = 0;
if (extension.length > 0) {
format = [NSString stringWithFormat:@"%@ %%d.%@", basename, extension];
}
else {
format = [NSString stringWithFormat:@"%@ %%d", basename];
}
while (true) {
// Checking both cases for iOS and macOS interoperability
LSFileWrapper *existing = [fileWrappers objectForKey:filename_];
LSFileWrapper *existingCase = [fileWrappers objectForKey:[filename_ lowercaseString]];
if ((!existing || existing.deleted) && (!existingCase || existingCase.deleted)) {
break;
}
filename_ = [NSString stringWithFormat:format, ++num];
}
}
fileWrapper.parent = self;
fileWrapper.filename = filename_;
fileWrapper.deleted = NO;
[fileWrappers setObject:fileWrapper forKey:filename_];
}
else if (replace) {
LSFileWrapper *existing = [fileWrappers objectForKey:filename_];
if (existing.writtenURL) {
existing.deleted = YES;
}
else {
[fileWrappers removeObjectForKey:filename_];
}
}
updated = YES;
return filename_;
}
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
- (BOOL)writeAsset:(ALAsset *)asset_ toURL:(NSURL *)url fileManager:(NSFileManager *)fileManager error:(NSError *__autoreleasing *)outError
{
[fileManager createFileAtPath:[url path] contents:nil attributes:nil];
static const NSUInteger BufferSize = 1024*1024;
NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:url error:outError];
if (!handle) {
return NO;
}
ALAssetRepresentation *rep = [asset_ defaultRepresentation];
NSUInteger bytesSize = (NSUInteger)[rep size];
NSUInteger bytesRead = 0;
NSUInteger bytesOffset = 0;
uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
do {
bytesRead = [rep getBytes:buffer fromOffset:bytesOffset length:BufferSize error:outError];
if (!bytesRead) {
break;
}
bytesOffset += bytesRead;
@try {
[handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
} @catch (NSException *exception) {
//TODO: Should probably convert NSException to NSError
break;
}
} while (bytesOffset < bytesSize);
free(buffer);
return bytesOffset >= bytesSize;
}
- (BOOL)writeImage:(UIImage *)image_ toURL:(NSURL *)url error:(NSError *__autoreleasing *)outError
{
NSData *imageData;
NSString *extension = [url pathExtension];
if ([extension isEqualToString:@"png"]) {
imageData = UIImagePNGRepresentation(image_);
}
else if ([extension isEqualToString:@"jpg"] || [extension isEqualToString:@"jpeg"]) {
imageData = UIImageJPEGRepresentation(image_, 1);
}
return [imageData writeToURL:url options:NSDataWritingAtomic error:outError];
}
#elif TARGET_OS_OSX
- (BOOL)writeImage:(NSImage *)image_ toURL:(NSURL *)url error:(NSError *__autoreleasing *)outError
{
NSData *imageData;
NSString *extension = [url pathExtension];
[image_ lockFocus];
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, image_.size.width, image_.size.height)];
[image_ unlockFocus];
if ([extension isEqualToString:@"png"]) {
imageData = [bitmapRep representationUsingType:NSPNGFileType properties:@{}];
}
else if ([extension isEqualToString:@"jpg"] || [extension isEqualToString:@"jpeg"]) {
imageData = [bitmapRep representationUsingType:NSJPEGFileType properties:@{}];
}
return [imageData writeToURL:url options:NSDataWritingAtomic error:outError];
}
#endif
- (BOOL)getParentUpdates:(NSMutableArray *)updates withURL:(NSURL *)url
{
if (!parent) {
return YES;
}
NSString *parentPath = [url URLByDeletingLastPathComponent].path;
NSString *parentWrittenPath = parent.writtenURL.path;
if (parentWrittenPath) {
return [parentPath isEqual:parentWrittenPath];
}
NSURL *parentURL = [[NSURL alloc] initFileURLWithPath:parentPath];
if ([parent getParentUpdates:updates withURL:parentURL]) {
[updates addObject:@{@"url":parentURL, @"wrapper":parent}];
return YES;
}
return NO;
}
- (void)getUpdates:(NSMutableArray *)updates withURL:(NSURL *)url
{
if (deleted) {
[updates addObject:@{@"url": url, @"wrapper":self, @"shouldPopulateWrittenURL": @YES}];
}
else if (isDirectory) {
if (!writtenURL) {
[updates addObject:@{@"url": url, @"wrapper":self, @"shouldPopulateWrittenURL": @YES}];
}
for (LSFileWrapper *fileWrapper in [fileWrappers objectEnumerator]) {
[fileWrapper getUpdates:updates withURL:[url URLByAppendingPathComponent:fileWrapper.filename]];
}
}
else if (updated && content) {
[updates addObject:@{@"url": url, @"wrapper":self, @"shouldPopulateWrittenURL": @YES}];
}
}
- (void)getAll:(NSMutableArray *)updates withURL:(NSURL *)url {
if (!deleted) {
[updates addObject:@{@"url": url, @"wrapper":self, @"shouldPopulateWrittenURL": @NO}];
if (isDirectory) {
for (LSFileWrapper *fileWrapper in [fileWrappers objectEnumerator]) {
[fileWrapper getAll:updates withURL:[url URLByAppendingPathComponent:fileWrapper.filename]];
}
}
}
}
- (BOOL)writeUpdates:(NSArray *)updates filemanager:(NSFileManager *)fileManager error:(NSError *__autoreleasing *)outError
{
BOOL wroteAll = YES;
for (NSDictionary *updateInfo in updates) {
NSURL *fileURL = [updateInfo objectForKey:@"url"];
LSFileWrapper *fileWrapper = [updateInfo objectForKey:@"wrapper"];
// MARK: Don't change writtenURL for whole file write!
BOOL shouldPopulateWrittenURL = [(NSNumber*)[updateInfo objectForKey:@"shouldPopulateWrittenURL"] boolValue];
if (fileWrapper.content == nil && fileWrapper.writtenURL != nil) {
fileWrapper.content = [NSData dataWithContentsOfURL:fileWrapper.writtenURL];
}
NSObject *fileContent = fileWrapper.content;
BOOL success = YES;
if (fileWrapper.deleted) {
NSLog(@"delete %@", fileURL);
success = [fileManager removeItemAtURL:fileURL error:outError];
}
else if (fileWrapper.isDirectory) {
if (fileWrapper.writtenURL == nil) {
if ([fileManager fileExistsAtPath:[fileURL path]]) {
success = [fileManager removeItemAtURL:fileURL error:outError];
}
success = success && [fileManager createDirectoryAtURL:fileURL withIntermediateDirectories:NO attributes:nil error:outError];
}
}
else {
// Create the directories if they're missing
NSURL* directoryURL = [fileURL URLByDeletingLastPathComponent];
if ([directoryURL checkResourceIsReachableAndReturnError:nil] == NO) {
[[NSFileManager defaultManager] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:@{NSFileExtensionHidden: @YES} error:outError];
}
if ([fileContent isKindOfClass:[NSData class]]) {
success = [(NSData*)fileContent writeToURL:fileURL options:NSDataWritingAtomic error:outError];
}
else if ([fileContent isKindOfClass:[NSString class]]) {
success = [(NSString*)fileContent writeToURL:fileURL atomically:YES encoding:NSUTF8StringEncoding error:outError];
}
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
else if ([fileContent isKindOfClass:[UIImage class]]) {
success = [self writeImage:(UIImage *)fileContent toURL:fileURL error:outError];
}
else if ([fileContent isKindOfClass:[ALAsset class]]) {
success = [self writeAsset:(ALAsset *)fileContent toURL:fileURL fileManager:fileManager error:outError];
}
#elif TARGET_OS_OSX
else if ([fileContent isKindOfClass:[NSImage class]]) {
success = [self writeImage:(NSImage *)fileContent toURL:fileURL error:outError];
}
#endif
else {
NSData *data = [NSPropertyListSerialization dataWithPropertyList:fileContent
format:NSPropertyListBinaryFormat_v1_0
options:0
error:NULL];
success = data && [data writeToURL:fileURL atomically:YES];
}
}
if (success == NO) {
wroteAll = NO;
continue;
}
fileWrapper.filename = [fileURL lastPathComponent];
if (shouldPopulateWrittenURL) {
fileWrapper.writtenURL = fileURL;
fileWrapper.updated = NO;
if (!cacheFile) {
fileWrapper.content = nil;
}
} else {
if (!fileWrapper.updated) {
if (!cacheFile) {
fileWrapper.content = nil;
}
}
}
if (fileWrapper.deleted) {
[fileWrapper.parent.fileWrappers removeObjectForKey:fileWrapper.filename];
}
}
return wroteAll;
}
@end