forked from jerrykrinock/CategoriesObjC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSFileManager+SomeMore.m
524 lines (449 loc) · 12.9 KB
/
NSFileManager+SomeMore.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
#import "NSFileManager+SomeMore.h"
#import "NSError+SSYAdds.h"
#import "NSError+LowLevel.h"
#import <fcntl.h>
NSString* const SSYMoreFileManagerErrorDomain = @"SSYMoreFileManagerErrorDomain" ;
@implementation NSFileManager (SomeMore)
- (BOOL)removeIfExistsItemAtPath:(NSString*)path
error_p:(NSError**)error_p {
if (!path) {
return YES ;
}
if ([self fileExistsAtPath:path]) {
return [self removeItemAtPath:path
error:error_p] ;
}
return YES ;
}
- (BOOL)getFromUrl:(NSURL*)url
fsRef_p:(FSRef*)fsRef_p
error_p:(NSError**)error_p {
OSStatus err = paramErr ;
NSString* path = nil ;
if (url) {
path = [url path] ;
}
if (path) {
err = FSPathMakeRef(
(UInt8*)[path fileSystemRepresentation],
fsRef_p,
NULL) ;
}
if (error_p) {
if (err == noErr) {
*error_p = nil ;
}
else {
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
@"Could not get FSRef", NSLocalizedDescriptionKey,
[url description], @"url",
[NSError errorWithMacErrorCode:err], NSUnderlyingErrorKey,
nil] ;
*error_p = [NSError errorWithDomain:SSYMoreFileManagerErrorDomain
code:617001
userInfo:info] ;
}
}
return (err == noErr) ;
}
- (BOOL)swapUrl:(NSURL*)url1
withUrl:(NSURL*)url2
error_p:(NSError**)error_p {
FSRef fsRef1, fsRef2 ;
BOOL ok ;
ok = [self getFromUrl:url1
fsRef_p:&fsRef1
error_p:error_p] ;
if (!ok) {
goto end ;
}
ok = [self getFromUrl:url2
fsRef_p:&fsRef2
error_p:error_p] ;
if (!ok) {
goto end ;
}
OSErr err = FSExchangeObjects (
&fsRef1,
&fsRef2
) ;
ok = (err == noErr) ;
if (error_p) {
if (err == noErr) {
*error_p = nil ;
}
else {
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
@"Could not exchange FSRefs", NSLocalizedDescriptionKey,
[url1 description], @"url1",
[url2 description], @"url2",
[NSError errorWithMacErrorCode:err], NSUnderlyingErrorKey,
nil] ;
*error_p = [NSError errorWithDomain:SSYMoreFileManagerErrorDomain
code:617002
userInfo:info] ;
}
}
end:
return ok ;
}
- (NSDate*)modificationDateForPath:(NSString*)path {
#if (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5)
NSDictionary* fileAttributes = [self fileAttributesAtPath:path
traverseLink:YES] ;
#else
NSDictionary* fileAttributes = [self attributesOfItemAtPath:path
error:NULL] ;
#endif
return [fileAttributes objectForKey:NSFileModificationDate] ;
}
- (BOOL)createDirectoryIfNoneExistsAtPath:(NSString*)path
error_p:(NSError**)error_p {
NSError* error = nil ;
NSFileManager* fileManager = [NSFileManager defaultManager] ;
BOOL isDirectory ;
BOOL exists = [fileManager fileExistsAtPath:path
isDirectory:&isDirectory] ;
BOOL ok = YES ;
if (!isDirectory) {
ok = [fileManager removeItemAtPath:path
error:&error] ;
if (!ok) {
error = [SSYMakeError(35261, @"Could not remove file") errorByAddingUnderlyingError:error] ;
[error errorByAddingUserInfoObject:path
forKey:@"path"] ;
}
}
if (!exists) {
ok = [fileManager createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:&error] ;
}
if (error && error_p) {
*error_p = error ;
}
return ok ;
}
- (BOOL)fileIsPermanentAtPath:(NSString*)path {
// The ^correct^ way to find if a path is in a temporary folder should
// be to pass its FSRef along with kTemporaryFolderType to
// FSDetermineIfRefIsEnclosedByFolder(). I have done this farther down,
// but it "just doesn't work" to find paths which are in the
// temporary directory that Cocoa uses, something like:
// /private/var/folders/PR/PRtZlutkFa82jPnfdYcUUk+++TI/-Tmp-/
// So, to work around that I first get the current ^Cocoa^ temporary
// directory and see if the given path is in there, with or without the
// "/private" symbolic link
NSString* cocoaTempDir = NSTemporaryDirectory() ;
if ([path hasPrefix:cocoaTempDir]) {
return NO ;
}
cocoaTempDir = [@"/private" stringByAppendingPathComponent:cocoaTempDir] ;
if ([path hasPrefix:cocoaTempDir]) {
return NO ;
}
FSRef fsRef;
OSStatus err = paramErr ;
if (path) {
err = FSPathMakeRef(
(UInt8*)[path fileSystemRepresentation],
&fsRef,
NULL) ;
}
if (err == noErr) {
Boolean result ;
// Note: FSDetermineIfRefIsEnclosedByFolder will return a -35 nsvErr
// (no such volume) if the fsRef given in the third argument is not
// in the specified folder. Probably that is because it is iterating
// through all possible volumes that match the specification given in the
// first parameter, 0, which means "all volumes", and the last one it tried
// was something that didn't exist, maybe an OS9/Classic volume.
// Seems like a bug to me. But anyhow, we ignore it.
FSDetermineIfRefIsEnclosedByFolder (
0,
kTrashFolderType,
&fsRef,
&result
) ;
if (result == true) {
return NO ;
}
FSDetermineIfRefIsEnclosedByFolder (
0,
kTemporaryFolderType,
&fsRef,
&result
) ;
if (result == true) {
return NO ;
}
FSDetermineIfRefIsEnclosedByFolder (
0,
kWhereToEmptyTrashFolderType,
&fsRef,
&result
) ;
if (result == true) {
return NO ;
}
FSDetermineIfRefIsEnclosedByFolder (
0,
kTemporaryItemsInCacheDataFolderType,
&fsRef,
&result
) ;
if (result == true) {
return NO ;
}
FSDetermineIfRefIsEnclosedByFolder (
0,
kChewableItemsFolderType,
&fsRef,
&result
) ;
if (result == true) {
return NO ;
}
}
else {
return NO ;
}
return YES ;
}
- (BOOL)fsGetCatalogInfo_p:(FSCatalogInfo*)catInfo_p
whichInfo:(FSCatalogInfoBitmap)whichInfo
fsRef:(FSRef)pathRef
error_p:(NSError**)error_p {
OSErr osErr;
osErr = FSGetCatalogInfo(
&pathRef,
whichInfo,
catInfo_p,
NULL,
NULL,
NULL
) ;
if (osErr != noErr) {
if (error_p) {
NSError* error_ = [NSError errorWithMacErrorCode:osErr] ;
*error_p = SSYMakeError(65840, @"FSGetCatalogInfo failed") ;
*error_p = [*error_p errorByAddingUnderlyingError:error_] ;
}
return NO ;
}
return YES ;
}
- (BOOL)fsSetCatalogInfo:(FSCatalogInfo)catInfo
whichInfo:(FSCatalogInfoBitmap)whichInfo
fsRef:(FSRef)pathRef
error_p:(NSError**)error_p {
OSErr osErr;
osErr = FSSetCatalogInfo(
&pathRef,
whichInfo,
&catInfo
) ;
if (osErr != noErr) {
if (error_p) {
NSError* error_ = [NSError errorWithMacErrorCode:osErr] ;
*error_p = SSYMakeError(65840, @"FSSetCatalogInfo failed") ;
*error_p = [*error_p errorByAddingUnderlyingError:error_] ;
}
return NO ;
}
return YES ;
}
- (BOOL)fsGetCatalogInfo_p:(FSCatalogInfo*)catInfo_p
whichInfo:(FSCatalogInfoBitmap)whichInfo
path:(NSString*)path
error_p:(NSError**)error_p {
FSRef pathRef;
// Warning: FSPathMakeRef may hang for a minute or so if mounted server is interrupted
FSPathMakeRef(
(UInt8*)[path fileSystemRepresentation],
&pathRef,
NULL
) ;
NSError* error = nil ;
BOOL ok = [self fsGetCatalogInfo_p:catInfo_p
whichInfo:whichInfo
fsRef:pathRef
error_p:&error] ;
if (!ok) {
if (error_p) {
*error_p = error ;
*error_p = [*error_p errorByAddingUserInfoObject:path
forKey:@"path"] ;
return NO ;
}
}
return YES ;
}
- (NSInteger)fileIsLockedAtPath:(NSString*)path
error_p:(NSError**)error_p {
NSError* error ;
FSCatalogInfo catInfo ;
BOOL ok = [self fsGetCatalogInfo_p:&catInfo
whichInfo:kFSCatInfoNodeFlags
path:path
error_p:&error] ;
if (!ok) {
if (error_p) {
*error_p = SSYMakeError(65847, @"Could not determine if file is locked") ;
*error_p = [*error_p errorByAddingUnderlyingError:error] ;
}
return NSMixedState ;
}
UInt16 nodeFlags = catInfo.nodeFlags ;
return ((nodeFlags & kFSNodeLockedMask) > 0 ) ? NSOnState : NSOffState ;
}
- (BOOL)setDoLock:(BOOL)doLock
fileAtPath:(NSString*)path
error_p:(NSError**)error_p {
FSRef pathRef;
// Warning: FSPathMakeRef may hang for a minute or so if mounted server is interrupted
FSPathMakeRef(
(UInt8*)[path fileSystemRepresentation],
&pathRef,
NULL
) ;
NSError* error = nil ;
NSError* error_ = nil ;
FSCatalogInfo catInfo ;
BOOL ok ;
ok= [self fsGetCatalogInfo_p:&catInfo
whichInfo:kFSCatInfoNodeFlags
fsRef:pathRef
error_p:&error_] ;
if (!ok) {
error = SSYMakeError(65842, @"Could not get catInfo needed to un/lock file") ;
goto end ;
}
// Alter the 'node locked' bit of the flags
UInt16 nodeFlags = catInfo.nodeFlags ;
nodeFlags = doLock ? (nodeFlags | kFSNodeLockedMask) : (nodeFlags & ~kFSNodeLockedMask) ;
catInfo.nodeFlags = nodeFlags ;
ok = [self fsSetCatalogInfo:catInfo
whichInfo:kFSCatInfoNodeFlags
fsRef:pathRef
error_p:&error_] ;
if (!ok) {
error = SSYMakeError(65848, @"Could not set un/lock file") ;
goto end ;
}
end:
if (!ok) {
if (error_p) {
*error_p = [error errorByAddingUnderlyingError:error_] ;
*error_p = [*error_p errorByAddingUserInfoObject:(doLock ? @"lock" : @"unlock")
forKey:@"attempted operation"] ;
*error_p = [*error_p errorByAddingUserInfoObject:path
forKey:@"path"] ;
}
}
return ok ;
}
- (NSString*)pathToSpecialFolderType:(OSType)folderType {
FSRef foundRef ;
OSErr err = FSFindFolder (
kUserDomain,
folderType,
false,
&foundRef ) ;
char fullPath[1024];
if (err == noErr) {
OSStatus osStatus = FSRefMakePath (&foundRef, (UInt8*)fullPath, sizeof(fullPath)) ;
if (osStatus != noErr) {
err = 1 ;
}
}
NSString* path = nil ;
if (err == noErr) {
path = [NSString stringWithCString:fullPath
encoding:NSUTF8StringEncoding] ;
}
return path ;
}
- (BOOL)fcntlIsLockedAtPath:(NSString*)path {
/* I haven't studied all the details of this. It's patterned after
JavaScript code found in the source code by Jonathan Griffin
for the (Firefox) ProfileManager project:
http://jagriffin.wordpress.com/2011/01/11/profilemanager-1-0_beta1/
source code: http://hg.mozilla.org/automation/profilemanager/
in the file chrome/content/utils.js:177
function isFcntlLocked(file).
Here is Jonathan's description:
Determines if a profile lockfile is locked with fcntl. This is done by
attempting to lock the file; if we can, it isn't locked by something else.
*/
BOOL isLocked = NO ;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path] ;
if (exists) {
const char* pathC = [path UTF8String] ;
int fd = open(
pathC,
FREAD | O_CREAT | O_TRUNC,
S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) ;
struct flock daFlock ;
daFlock.l_start = 0 ;
daFlock.l_len = 0 ;
daFlock.l_type = F_WRLCK ;
daFlock.l_whence = SEEK_SET ;
// Jonathan says: Attempt to get lock status; if this
// returns -1 it means fcntl isn't supported on this file
int getlock = fcntl(fd, F_GETLK, &daFlock) ;
if (getlock != -1) {
// Attempt to lock the file
int setlock = fcntl(fd, F_SETLK, &daFlock) ;
if (setlock == -1) {
// Attempt to lock the file failed
if (errno == EAGAIN || errno == EACCES) {
isLocked = YES ;
}
}
}
close(fd) ;
}
return isLocked ;
}
- (BOOL)removeThoughtfullyPath:(NSString*)path
error_p:(NSError**)error_p {
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
return YES ;
}
NSError* error ;
BOOL ok = [[NSFileManager defaultManager] removeItemAtPath:path
error:&error] ;
if (!ok && error_p) {
*error_p = SSYMakeError(922018, @"Could not delete item") ;
*error_p = [*error_p errorByAddingUserInfoObject:path
forKey:@"Path"] ;
*error_p = [*error_p errorByAddingUnderlyingError:error] ;
NSString* suggestion = [NSString stringWithFormat:
@"Activate Finder and try to remove this item yourself:\n\n%@\n\n",
path] ;
*error_p = [*error_p errorByAddingLocalizedRecoverySuggestion:suggestion] ;
}
return ok ;
}
- (BOOL)trashPath:(NSString*)path
error_p:(NSError**)error_p {
NSString* source = [NSString stringWithFormat:
/**/@"tell application \"Finder\"\n"
/**/ @"delete POSIX file \"%@\"\n"
/**/@"end tell\n",
path] ;
NSAppleScript* script = [[NSAppleScript alloc] initWithSource:source];
NSDictionary* errorDic = nil ;
[script executeAndReturnError:&errorDic] ;
[script release] ;
BOOL ok = YES ;
NSError* error = [NSError errorWithAppleScriptErrorDictionary:errorDic] ;
if (error_p && error) {
*error_p = [error errorByAddingUserInfoObject:path
forKey:@"Path Attempted to Trash"] ;
}
return ok ;
}
@end