-
Notifications
You must be signed in to change notification settings - Fork 5
/
NSFileManager+Utils.m
executable file
·471 lines (411 loc) · 14.3 KB
/
NSFileManager+Utils.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
//
// NSFileManager+Utils.m
// PermanentEraser
//
// Created by Chad Armstrong on 12/2/10.
// Copyright 2010 Edenwaith. All rights reserved.
//
#import "NSFileManager+Utils.h"
#import "NSProcessInfo+PECocoaBackports.h"
@implementation NSFileManager (Utils)
// =========================================================================
// (BOOL) createDirectoryAtPathWithIntermediateDirectories: (NSString *) path attributes: (NSDictionary *) attributes
// -------------------------------------------------------------------------
// Recursively create a folder (and it's parent folders, if necessary)
// A category replacement for createDirectoryAtPath:withIntermediateDirectories:attributes:error:,
// since that was introduced in Mac OS 10.5, and the current version of PE
// still supports Mac OS 10.3.9.
// -------------------------------------------------------------------------
// Created: 2 December 2010
// Version: 4 December 2010 11:20
// =========================================================================
- (BOOL) createDirectoryAtPathWithIntermediateDirectories: (NSString *) path attributes: (NSDictionary *) attributes
{
BOOL isDir;
NSString *parentDirectory = [path stringByDeletingLastPathComponent];
if (![self fileExistsAtPath: parentDirectory isDirectory:&isDir] && isDir)
{
// call ourself with the directory above...
[self createDirectoryAtPathWithIntermediateDirectories: parentDirectory attributes: attributes];
}
// Parent directories have been created by now, if needed...
if ([self fileExistsAtPath: path] == NO)
{
[self createDirectoryAtPath: path attributes: attributes];
}
return YES;
}
// =========================================================================
// (BOOL) isFileSymbolicLink: (NSString *)path
// -------------------------------------------------------------------------
// Check to see if a file is a symbolic/soft link, so the link
// can be deleted with rm instead of srm, so the original file is not
// accidentally erased.
// -------------------------------------------------------------------------
// Version: 19. November 2004 21:28
// Created: 19. November 2004 21:28
// =========================================================================
- (BOOL) isFileSymbolicLink: (NSString *) path
{
NSDictionary *fattrs = [self fileAttributesAtPath: path traverseLink:NO];
if ( [[fattrs objectForKey:NSFileType] isEqual: @"NSFileTypeSymbolicLink"])
{
return (YES);
}
else
{
return (NO);
}
}
// =========================================================================
// (BOOL) containsResourceFork: (NSString *)path
// -------------------------------------------------------------------------
// Check to see if a file contains a resource fork.
// Should gather several of these file-related checks and put them into
// a separate extension class.
// -------------------------------------------------------------------------
// Created: 2 January 2007 19:49
// Version: 8 April 2007
// =========================================================================
// TODO: Should move some of these methods to the NSFileManager+Utils category class
- (BOOL) containsResourceFork: (NSString *)path
{
FSRef fsRef;
FSCatalogInfo fsInfo;
BOOL isDir;
// If path is a directory, automatically return NO
if ( [self fileExistsAtPath: path isDirectory:&isDir] && isDir )
{
return (NO);
}
else if (FSPathMakeRef((unsigned char *) [path fileSystemRepresentation], &fsRef, NULL) == noErr)
{
// Another way to check for a resource fork is by using getxattr
// ssize_t resourceForkSize = getxattr([pathToFile fileSystemRepresentation], "com.apple.ResourceFork", NULL, 0, 0, 0);
if(FSGetCatalogInfo(&fsRef, kFSCatInfoRsrcSizes, &fsInfo, NULL, NULL, NULL) == noErr)
{
if (fsInfo.rsrcLogicalSize > 0)
{
return (YES);
}
else
{
return (NO);
}
}
}
return (NO);
}
// =========================================================================
// (FSRef) convertStringToFSRef: (NSString *) path
// -------------------------------------------------------------------------
// Convert NSString to FSRef
// -------------------------------------------------------------------------
// Created: 10 December 2009 22:37
// Version: 9 June 2010 21:23
// =========================================================================
- (FSRef) convertStringToFSRef: (NSString *) path
{
// This converts an NSString path to a FSRef correctly.
// The Dell Inspiron backup was sized properly at 20662092257, whereas the old method
// returned the value 25893905653. If a file name had a semi-colon in it, the entire
// parent directory would be given as the file's size.
FSRef output;
NSURL *fileURL = [NSURL fileURLWithPath: path];
if (!CFURLGetFSRef( (CFURLRef)fileURL, &output ))
{
NSLog( @"Failed to create FSRef." );
}
return output;
}
// =========================================================================
// (unsigned long long) fileSize: (NSString *) path
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Created: 10 December 2009 22:45
// Version: 21 May 2010 22:39
// =========================================================================
- (unsigned long long) fileSize: (NSString *) path
{
unsigned long long pathFileSize = 0;
if ([self isFileSymbolicLink: path] == YES)
{
NSDictionary *fattrs = [self fileAttributesAtPath: path traverseLink: NO];
if (fattrs != nil)
{
NSNumber *numFileSize;
numFileSize = [fattrs objectForKey: NSFileSize];
pathFileSize = [numFileSize unsignedLongLongValue];
}
}
else
{
FSRef ref = [self convertStringToFSRef: path];
pathFileSize = [self fastFolderSizeAtFSRef: &ref];
}
return (pathFileSize);
}
// =========================================================================
// (unsigned long long) fastFolderSizeAtFSRef:(FSRef*)theFileRef
// -------------------------------------------------------------------------
// =========================================================================
- (unsigned long long) fastFolderSizeAtFSRef:(FSRef*)theFileRef
{
FSIterator thisDirEnum = NULL;
unsigned long long totalSize = 0;
// Iterate the directory contents, recursing as necessary
if (FSOpenIterator(theFileRef, kFSIterateFlat, &thisDirEnum) == noErr)
{
// 40 is a better number, prevents the memory crash from too many recursive calls
const ItemCount kMaxEntriesPerFetch = 40;
ItemCount actualFetched;
FSRef fetchedRefs[kMaxEntriesPerFetch];
FSCatalogInfo fetchedInfos[kMaxEntriesPerFetch];
OSErr fsErr = FSGetCatalogInfoBulk(thisDirEnum, kMaxEntriesPerFetch, &actualFetched,
NULL, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes | kFSCatInfoNodeFlags, fetchedInfos,
fetchedRefs, NULL, NULL);
while ((fsErr == noErr) || (fsErr == errFSNoMoreItems))
{
ItemCount thisIndex;
for (thisIndex = 0; thisIndex < actualFetched; thisIndex++)
{
// Recurse if it's a folder
if (fetchedInfos[thisIndex].nodeFlags & kFSNodeIsDirectoryMask)
{
totalSize += [self fastFolderSizeAtFSRef:&fetchedRefs[thisIndex]];
}
else
{
// add the size for this item
totalSize += fetchedInfos[thisIndex].dataLogicalSize + fetchedInfos[thisIndex].rsrcLogicalSize;
}
}
if (fsErr == errFSNoMoreItems)
{
break;
}
else
{
// get more items
fsErr = FSGetCatalogInfoBulk(thisDirEnum, kMaxEntriesPerFetch, &actualFetched,
NULL, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes | kFSCatInfoNodeFlags, fetchedInfos,
fetchedRefs, NULL, NULL);
}
}
FSCloseIterator(thisDirEnum);
}
else
{
FSCatalogInfo fsInfo;
if (FSGetCatalogInfo(theFileRef, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes, &fsInfo, NULL, NULL, NULL) == noErr)
{
if (fsInfo.rsrcLogicalSize > 0)
{
totalSize += (fsInfo.dataLogicalSize + fsInfo.rsrcLogicalSize);
}
else
{
totalSize += (fsInfo.dataLogicalSize);
}
}
}
return totalSize;
}
- (unsigned long long) fastFolderSizeAtFSRefOld:(FSRef*)theFileRef
{
FSIterator thisDirEnum = NULL;
unsigned long long totalSize = 0;
// Iterate the directory contents, recursing as necessary
if (FSOpenIterator(theFileRef, kFSIterateFlat, &thisDirEnum) == noErr)
{
// 40 is a better number, prevents the memory crash from too many recursive calls
const ItemCount kMaxEntriesPerFetch = 40; // 256;
ItemCount actualFetched;
FSRef fetchedRefs[kMaxEntriesPerFetch];
FSCatalogInfo fetchedInfos[kMaxEntriesPerFetch];
OSErr fsErr = FSGetCatalogInfoBulk(thisDirEnum, kMaxEntriesPerFetch, &actualFetched,
NULL, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes | kFSCatInfoNodeFlags, fetchedInfos,
fetchedRefs, NULL, NULL);
while ((fsErr == noErr) || (fsErr == errFSNoMoreItems))
{
ItemCount thisIndex;
for (thisIndex = 0; thisIndex < actualFetched; thisIndex++)
{
// Recurse if it's a folder
if (fetchedInfos[thisIndex].nodeFlags & kFSNodeIsDirectoryMask)
{
totalSize += [self fastFolderSizeAtFSRef:&fetchedRefs[thisIndex]];
}
else
{
// add the size for this item
totalSize += fetchedInfos[thisIndex].dataLogicalSize + fetchedInfos[thisIndex].rsrcLogicalSize;
}
}
if (fsErr == errFSNoMoreItems)
{
break;
}
else
{
// get more items
fsErr = FSGetCatalogInfoBulk(thisDirEnum, kMaxEntriesPerFetch, &actualFetched,
NULL, kFSCatInfoDataSizes | kFSCatInfoNodeFlags, fetchedInfos,
fetchedRefs, NULL, NULL);
}
}
FSCloseIterator(thisDirEnum);
}
else
{
FSCatalogInfo fsInfo;
if(FSGetCatalogInfo(theFileRef, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes, &fsInfo, NULL, NULL, NULL) == noErr)
{
if (fsInfo.rsrcLogicalSize > 0)
{
totalSize += (fsInfo.dataLogicalSize + fsInfo.rsrcLogicalSize);
}
else
{
totalSize += (fsInfo.dataLogicalSize);
}
}
}
return totalSize;
}
// =========================================================================
// (NSString *) formatFileSize: (double) fileSize
// -------------------------------------------------------------------------
// Should (double) file)_size be changed to unsigned long long?
// -------------------------------------------------------------------------
// Created: 8 August 2007 22:09
// Version: 16 February 2015 15:02
// =========================================================================
- (NSString *) formatFileSize: (double) fileSize
{
NSString *fileSizeLabel;
double baseSize = 1024.0; // For Mac OS 10.6+, set this to 1000.0
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 6, 0}] == YES)
{
baseSize = 1000.0;
}
if ( (fileSize / baseSize) < 1.0)
{
if (fileSize == 1.0)
{
fileSizeLabel = @" byte";
}
else
{
fileSizeLabel = @" bytes";
}
}
else if ((fileSize / pow(baseSize, 2)) < 1.0)
{
fileSize = fileSize / baseSize;
fileSizeLabel = @" KB";
}
else if ((fileSize / pow(baseSize, 3)) < 1.0)
{
fileSize = fileSize / pow(baseSize, 2);
fileSizeLabel = @" MB";
}
else
{
fileSize = fileSize / pow(baseSize, 3);
fileSizeLabel = @" GB";
}
return ([NSString stringWithFormat: @"%.2f%@", fileSize, fileSizeLabel]);
}
// =========================================================================
// (BOOL) isSolidState: (UInt8 const *) cpath
// -------------------------------------------------------------------------
// Check to see if a given file is located on a Solid State Drive (SSD)
// -------------------------------------------------------------------------
// Added 18 March 2012 18:06
// =========================================================================
- (BOOL) isSolidState: (UInt8 const *) cpath
{
FSRef volRef;
CFMutableDictionaryRef classesToMatch = nil;
if (noErr == FSPathMakeRef( cpath, &volRef, NULL))
{
FSCatalogInfo volCatInfo;
if (noErr == FSGetCatalogInfo(&volRef, kFSCatInfoVolume, &volCatInfo, NULL, NULL, NULL))
{
CFStringRef idStr = NULL;
if (noErr == FSCopyDiskIDForVolume(volCatInfo.volume, &idStr))
{
NSString *str = (NSString*)idStr;
//NSLog(@"Checking bsd disk %@",str);
// create matching dictionary
classesToMatch = IOBSDNameMatching(kIOMasterPortDefault,0,[str UTF8String]);
if (idStr) CFRelease(idStr);
}
}
}
if (classesToMatch == NULL) {
NSLog(@"Could not find io classes of disk");
return NO;
}
// get iterator of matching services
io_iterator_t entryIterator;
if (KERN_SUCCESS != IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, &entryIterator))
{
NSLog(@"Can't iterate services");
return NO;
}
BOOL isSolidState = NO;
// iterate over all found medias
io_object_t serviceEntry, parentMedia;
while (serviceEntry = IOIteratorNext(entryIterator))
{
int maxlevels = 8;
do
{
kern_return_t kernResult = IORegistryEntryGetParentEntry(serviceEntry, kIOServicePlane, &parentMedia);
IOObjectRelease(serviceEntry);
if (KERN_SUCCESS != kernResult) {
serviceEntry = 0;
NSLog(@"Error while getting parent service entry");
break;
}
serviceEntry = parentMedia;
if (!parentMedia) break; // finished iterator
CFTypeRef res = IORegistryEntryCreateCFProperty(serviceEntry, CFSTR(kIOPropertyDeviceCharacteristicsKey), kCFAllocatorDefault, 0);
if (res)
{
NSString *type = [(NSDictionary*)res objectForKey:(id)CFSTR(kIOPropertyMediumTypeKey)];
//NSLog(@"Found disk %@",res);
isSolidState = [@"Solid State" isEqualToString:type]; type = nil;
CFRelease(res);
if (isSolidState) break;
}
}
while(maxlevels--);
if (serviceEntry) IOObjectRelease(serviceEntry);
}
IOObjectRelease(entryIterator);
return isSolidState;
}
// =========================================================================
// (NSString *) isDirectoryEmpty: (NSString *) path
// -------------------------------------------------------------------------
//
// -------------------------------------------------------------------------
// Created: 27 November 2009 23:35
// Version: 6 April 2018 20:49
// =========================================================================
- (BOOL) isDirectoryEmpty: (NSString *) path
{
NSArray *dirContents = [self subpathsAtPath: path];
if (dirContents != nil && [dirContents count] == 0)
{
return YES;
}
else
{
return NO;
}
}
@end