forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileManager.swift
2673 lines (2299 loc) · 126 KB
/
FileManager.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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(Android) // struct stat.st_mode is UInt32
internal func &(left: UInt32, right: mode_t) -> mode_t {
return mode_t(left) & right
}
#endif
import CoreFoundation
#if os(Windows)
internal func joinPath(prefix: String, suffix: String) -> String {
var pszPath: PWSTR?
_ = prefix.withCString(encodedAs: UTF16.self) { prefix in
_ = suffix.withCString(encodedAs: UTF16.self) { suffix in
PathAllocCombine(prefix, suffix, ULONG(PATHCCH_ALLOW_LONG_PATHS.rawValue), &pszPath)
}
}
let path: String = String(decodingCString: pszPath!, as: UTF16.self)
LocalFree(pszPath)
return path
}
#endif
open class FileManager : NSObject {
/* Returns the default singleton instance.
*/
private static let _default = FileManager()
open class var `default`: FileManager {
get {
return _default
}
}
/// Returns an array of URLs that identify the mounted volumes available on the device.
open func mountedVolumeURLs(includingResourceValuesForKeys propertyKeys: [URLResourceKey]?, options: VolumeEnumerationOptions = []) -> [URL]? {
var urls: [URL] = []
#if os(Linux)
guard let procMounts = try? String(contentsOfFile: "/proc/mounts", encoding: .utf8) else {
return nil
}
urls = []
for line in procMounts.components(separatedBy: "\n") {
let mountPoint = line.components(separatedBy: " ")
if mountPoint.count > 2 {
urls.append(URL(fileURLWithPath: mountPoint[1], isDirectory: true))
}
}
#elseif os(Windows)
var wszVolumeName: UnsafeMutableBufferPointer<WCHAR> = UnsafeMutableBufferPointer<WCHAR>.allocate(capacity: Int(MAX_PATH))
defer { wszVolumeName.deallocate() }
var hVolumes: HANDLE = FindFirstVolumeW(wszVolumeName.baseAddress, DWORD(wszVolumeName.count))
guard hVolumes != INVALID_HANDLE_VALUE else { return nil }
defer { FindVolumeClose(hVolumes) }
repeat {
var dwCChReturnLength: DWORD = 0
GetVolumePathNamesForVolumeNameW(wszVolumeName.baseAddress, nil, 0, &dwCChReturnLength)
var wszPathNames: UnsafeMutableBufferPointer<WCHAR> = UnsafeMutableBufferPointer<WCHAR>.allocate(capacity: Int(dwCChReturnLength + 1))
defer { wszPathNames.deallocate() }
if GetVolumePathNamesForVolumeNameW(wszVolumeName.baseAddress, wszPathNames.baseAddress, DWORD(wszPathNames.count), &dwCChReturnLength) == FALSE {
// TODO(compnerd) handle error
continue
}
var pPath: DWORD = 0
repeat {
let path: String = String(decodingCString: wszPathNames.baseAddress! + Int(pPath), as: UTF16.self)
if path.length == 0 {
break
}
urls.append(URL(fileURLWithPath: path, isDirectory: true))
pPath += DWORD(path.length + 1)
} while pPath < dwCChReturnLength
} while FindNextVolumeW(hVolumes, wszVolumeName.baseAddress, DWORD(wszVolumeName.count)) != FALSE
#elseif canImport(Darwin)
func mountPoints(_ statBufs: UnsafePointer<statfs>, _ fsCount: Int) -> [URL] {
var urls: [URL] = []
for fsIndex in 0..<fsCount {
var fs = statBufs.advanced(by: fsIndex).pointee
if options.contains(.skipHiddenVolumes) && fs.f_flags & UInt32(MNT_DONTBROWSE) != 0 {
continue
}
let mountPoint = withUnsafePointer(to: &fs.f_mntonname.0) { (ptr: UnsafePointer<Int8>) -> String in
return string(withFileSystemRepresentation: ptr, length: strlen(ptr))
}
urls.append(URL(fileURLWithPath: mountPoint, isDirectory: true))
}
return urls
}
if #available(OSX 10.13, *) {
var statBufPtr: UnsafeMutablePointer<statfs>?
let fsCount = getmntinfo_r_np(&statBufPtr, MNT_WAIT)
guard let statBuf = statBufPtr, fsCount > 0 else {
return nil
}
urls = mountPoints(statBuf, Int(fsCount))
free(statBufPtr)
} else {
var fsCount = getfsstat(nil, 0, MNT_WAIT)
guard fsCount > 0 else {
return nil
}
let statBuf = UnsafeMutablePointer<statfs>.allocate(capacity: Int(fsCount))
defer { statBuf.deallocate() }
fsCount = getfsstat(statBuf, fsCount * Int32(MemoryLayout<statfs>.stride), MNT_WAIT)
guard fsCount > 0 else {
return nil
}
urls = mountPoints(statBuf, Int(fsCount))
}
#else
#error("Requires a platform-specific implementation")
#endif
return urls
}
/* Returns an NSArray of NSURLs identifying the the directory entries.
If the directory contains no entries, this method will return the empty array. When an array is specified for the 'keys' parameter, the specified property values will be pre-fetched and cached with each enumerated URL.
This method always does a shallow enumeration of the specified directory (i.e. it always acts as if NSDirectoryEnumerationSkipsSubdirectoryDescendants has been specified). If you need to perform a deep enumeration, use -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:].
If you wish to only receive the URLs and no other attributes, then pass '0' for 'options' and an empty NSArray ('[NSArray array]') for 'keys'. If you wish to have the property caches of the vended URLs pre-populated with a default set of attributes, then pass '0' for 'options' and 'nil' for 'keys'.
*/
open func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: DirectoryEnumerationOptions = []) throws -> [URL] {
var error : Error? = nil
let e = self.enumerator(at: url, includingPropertiesForKeys: keys, options: mask.union(.skipsSubdirectoryDescendants)) { (url, err) -> Bool in
error = err
return false
}
var result = [URL]()
if let e = e {
for url in e {
result.append(url as! URL)
}
if let error = error {
throw error
}
}
return result
}
private enum _SearchPathDomain {
case system
case local
case network
case user
static let correspondingValues: [UInt: _SearchPathDomain] = [
SearchPathDomainMask.systemDomainMask.rawValue: .system,
SearchPathDomainMask.localDomainMask.rawValue: .local,
SearchPathDomainMask.networkDomainMask.rawValue: .network,
SearchPathDomainMask.userDomainMask.rawValue: .user,
]
static let searchOrder: [SearchPathDomainMask] = [
.systemDomainMask,
.localDomainMask,
.networkDomainMask,
.userDomainMask,
]
init?(_ domainMask: SearchPathDomainMask) {
if let value = _SearchPathDomain.correspondingValues[domainMask.rawValue] {
self = value
} else {
return nil
}
}
static func allInSearchOrder(from domainMask: SearchPathDomainMask) -> [_SearchPathDomain] {
var domains: [_SearchPathDomain] = []
for bit in _SearchPathDomain.searchOrder {
if domainMask.contains(bit) {
domains.append(_SearchPathDomain.correspondingValues[bit.rawValue]!)
}
}
return domains
}
}
private func darwinPathURLs(for domain: _SearchPathDomain, system: String?, local: String?, network: String?, userHomeSubpath: String?) -> [URL] {
switch domain {
case .system:
guard let path = system else { return [] }
return [ URL(fileURLWithPath: path, isDirectory: true) ]
case .local:
guard let path = local else { return [] }
return [ URL(fileURLWithPath: path, isDirectory: true) ]
case .network:
guard let path = network else { return [] }
return [ URL(fileURLWithPath: path, isDirectory: true) ]
case .user:
guard let path = userHomeSubpath else { return [] }
return [ URL(fileURLWithPath: path, isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
}
}
private func darwinPathURLs(for domain: _SearchPathDomain, all: String, useLocalDirectoryForSystem: Bool = false) -> [URL] {
switch domain {
case .system:
return [ URL(fileURLWithPath: useLocalDirectoryForSystem ? "/\(all)" : "/System/\(all)", isDirectory: true) ]
case .local:
return [ URL(fileURLWithPath: "/\(all)", isDirectory: true) ]
case .network:
return [ URL(fileURLWithPath: "/Network/\(all)", isDirectory: true) ]
case .user:
return [ URL(fileURLWithPath: all, isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
}
}
/* -URLsForDirectory:inDomains: is analogous to NSSearchPathForDirectoriesInDomains(), but returns an array of NSURL instances for use with URL-taking APIs. This API is suitable when you need to search for a file or files which may live in one of a variety of locations in the domains specified.
*/
open func urls(for directory: SearchPathDirectory, in domainMask: SearchPathDomainMask) -> [URL] {
let domains = _SearchPathDomain.allInSearchOrder(from: domainMask)
var urls: [URL] = []
#if os(Windows)
for domain in domains {
urls.append(contentsOf: windowsURLs(for: directory, in: domain))
}
#else
// We are going to return appropriate paths on Darwin, but [] on platforms that do not have comparable locations.
// For example, on FHS/XDG systems, applications are not installed in a single path.
let useDarwinPaths: Bool
if let envVar = ProcessInfo.processInfo.environment["_NSFileManagerUseXDGPathsForDirectoryDomains"] {
useDarwinPaths = !NSString(string: envVar).boolValue
} else {
#if canImport(Darwin)
useDarwinPaths = true
#else
useDarwinPaths = false
#endif
}
for domain in domains {
if useDarwinPaths {
urls.append(contentsOf: darwinURLs(for: directory, in: domain))
} else {
urls.append(contentsOf: xdgURLs(for: directory, in: domain))
}
}
#endif
return urls
}
#if os(Windows)
private class func url(for id: KNOWNFOLDERID) -> URL {
var pszPath: PWSTR?
let hResult: HRESULT = withUnsafePointer(to: id) { id in
SHGetKnownFolderPath(id, DWORD(KF_FLAG_DEFAULT.rawValue), nil, &pszPath)
}
precondition(hResult >= 0, "SHGetKnownFolderpath failed \(GetLastError())")
let url: URL = URL(fileURLWithPath: String(decodingCString: pszPath!, as: UTF16.self), isDirectory: true)
CoTaskMemFree(pszPath)
return url
}
private func windowsURLs(for directory: SearchPathDirectory, in domain: _SearchPathDomain) -> [URL] {
switch directory {
case .autosavedInformationDirectory:
// FIXME(compnerd) where should this go?
return []
case .desktopDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Desktop)]
case .documentDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Documents)]
case .cachesDirectory:
guard domain == .user else { return [] }
return [URL(fileURLWithPath: NSTemporaryDirectory())]
case .applicationSupportDirectory:
switch domain {
case .local:
return [FileManager.url(for: FOLDERID_ProgramData)]
case .user:
return [FileManager.url(for: FOLDERID_LocalAppData)]
default:
return []
}
case .downloadsDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Downloads)]
case .userDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_UserProfiles)]
case .moviesDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Videos)]
case .musicDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Music)]
case .picturesDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_PicturesLibrary)]
case .sharedPublicDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Public)]
case .trashDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_RecycleBinFolder)]
// None of these are supported outside of Darwin:
case .applicationDirectory,
.demoApplicationDirectory,
.developerApplicationDirectory,
.adminApplicationDirectory,
.libraryDirectory,
.developerDirectory,
.documentationDirectory,
.coreServiceDirectory,
.inputMethodsDirectory,
.preferencePanesDirectory,
.applicationScriptsDirectory,
.allApplicationsDirectory,
.allLibrariesDirectory,
.printerDescriptionDirectory,
.itemReplacementDirectory:
return []
}
}
#endif
private lazy var xdgHomeDirectory: String = {
let key = "HOME="
if let contents = try? String(contentsOfFile: "/etc/default/useradd", encoding: .utf8) {
for line in contents.components(separatedBy: "\n") {
if line.hasPrefix(key) {
let index = line.index(line.startIndex, offsetBy: key.count)
let str = String(line[index...]) as NSString
let homeDir = str.trimmingCharacters(in: CharacterSet.whitespaces)
if homeDir.count > 0 {
return homeDir
}
}
}
}
return "/home"
}()
private func xdgURLs(for directory: SearchPathDirectory, in domain: _SearchPathDomain) -> [URL] {
// FHS/XDG-compliant OSes:
switch directory {
case .autosavedInformationDirectory:
let runtimePath = __SwiftValue.fetch(nonOptional: _CFXDGCreateDataHomePath()) as! String
return [ URL(fileURLWithPath: "Autosave Information", isDirectory: true, relativeTo: URL(fileURLWithPath: runtimePath, isDirectory: true)) ]
case .desktopDirectory:
guard domain == .user else { return [] }
return [ _XDGUserDirectory.desktop.url ]
case .documentDirectory:
guard domain == .user else { return [] }
return [ _XDGUserDirectory.documents.url ]
case .cachesDirectory:
guard domain == .user else { return [] }
let path = __SwiftValue.fetch(nonOptional: _CFXDGCreateCacheDirectoryPath()) as! String
return [ URL(fileURLWithPath: path, isDirectory: true) ]
case .applicationSupportDirectory:
guard domain == .user else { return [] }
let path = __SwiftValue.fetch(nonOptional: _CFXDGCreateDataHomePath()) as! String
return [ URL(fileURLWithPath: path, isDirectory: true) ]
case .downloadsDirectory:
guard domain == .user else { return [] }
return [ _XDGUserDirectory.download.url ]
case .userDirectory:
guard domain == .local else { return [] }
return [ URL(fileURLWithPath: xdgHomeDirectory, isDirectory: true) ]
case .moviesDirectory:
return [ _XDGUserDirectory.videos.url ]
case .musicDirectory:
guard domain == .user else { return [] }
return [ _XDGUserDirectory.music.url ]
case .picturesDirectory:
guard domain == .user else { return [] }
return [ _XDGUserDirectory.pictures.url ]
case .sharedPublicDirectory:
guard domain == .user else { return [] }
return [ _XDGUserDirectory.publicShare.url ]
case .trashDirectory:
let userTrashURL = URL(fileURLWithPath: ".Trash", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true))
if domain == .user || domain == .local {
return [ userTrashURL ]
} else {
return []
}
// None of these are supported outside of Darwin:
case .applicationDirectory:
fallthrough
case .demoApplicationDirectory:
fallthrough
case .developerApplicationDirectory:
fallthrough
case .adminApplicationDirectory:
fallthrough
case .libraryDirectory:
fallthrough
case .developerDirectory:
fallthrough
case .documentationDirectory:
fallthrough
case .coreServiceDirectory:
fallthrough
case .inputMethodsDirectory:
fallthrough
case .preferencePanesDirectory:
fallthrough
case .applicationScriptsDirectory:
fallthrough
case .allApplicationsDirectory:
fallthrough
case .allLibrariesDirectory:
fallthrough
case .printerDescriptionDirectory:
fallthrough
case .itemReplacementDirectory:
return []
}
}
private func darwinURLs(for directory: SearchPathDirectory, in domain: _SearchPathDomain) -> [URL] {
switch directory {
case .applicationDirectory:
return darwinPathURLs(for: domain, all: "Applications", useLocalDirectoryForSystem: true)
case .demoApplicationDirectory:
return darwinPathURLs(for: domain, all: "Demos", useLocalDirectoryForSystem: true)
case .developerApplicationDirectory:
return darwinPathURLs(for: domain, all: "Developer/Applications", useLocalDirectoryForSystem: true)
case .adminApplicationDirectory:
return darwinPathURLs(for: domain, all: "Applications/Utilities", useLocalDirectoryForSystem: true)
case .libraryDirectory:
return darwinPathURLs(for: domain, all: "Library")
case .developerDirectory:
return darwinPathURLs(for: domain, all: "Developer", useLocalDirectoryForSystem: true)
case .documentationDirectory:
return darwinPathURLs(for: domain, all: "Library/Documentation")
case .coreServiceDirectory:
return darwinPathURLs(for: domain, system: "/System/Library/CoreServices", local: nil, network: nil, userHomeSubpath: nil)
case .autosavedInformationDirectory:
return darwinPathURLs(for: domain, system: nil, local: nil, network: nil, userHomeSubpath: "Library/Autosave Information")
case .inputMethodsDirectory:
return darwinPathURLs(for: domain, all: "Library/Input Methods")
case .preferencePanesDirectory:
return darwinPathURLs(for: domain, system: "/System/Library/PreferencePanes", local: "/Library/PreferencePanes", network: nil, userHomeSubpath: "Library/PreferencePanes")
case .applicationScriptsDirectory:
// Only the ObjC Foundation can know where this is.
return []
case .allApplicationsDirectory:
var directories: [URL] = []
directories.append(contentsOf: darwinPathURLs(for: domain, all: "Applications", useLocalDirectoryForSystem: true))
directories.append(contentsOf: darwinPathURLs(for: domain, all: "Demos", useLocalDirectoryForSystem: true))
directories.append(contentsOf: darwinPathURLs(for: domain, all: "Developer/Applications", useLocalDirectoryForSystem: true))
directories.append(contentsOf: darwinPathURLs(for: domain, all: "Applications/Utilities", useLocalDirectoryForSystem: true))
return directories
case .allLibrariesDirectory:
var directories: [URL] = []
directories.append(contentsOf: darwinPathURLs(for: domain, all: "Library"))
directories.append(contentsOf: darwinPathURLs(for: domain, all: "Developer"))
return directories
case .printerDescriptionDirectory:
guard domain == .system else { return [] }
return [ URL(fileURLWithPath: "/System/Library/Printers/PPD", isDirectory: true) ]
case .desktopDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Desktop", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .documentDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Documents", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .cachesDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Library/Caches", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .applicationSupportDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Library/Application Support", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .downloadsDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Downloads", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .userDirectory:
return darwinPathURLs(for: domain, system: nil, local: "/Users", network: "/Network/Users", userHomeSubpath: nil)
case .moviesDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Movies", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .musicDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Music", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .picturesDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Pictures", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .sharedPublicDirectory:
guard domain == .user else { return [] }
return [ URL(fileURLWithPath: "Public", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ]
case .trashDirectory:
let userTrashURL = URL(fileURLWithPath: ".Trash", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true))
if domain == .user || domain == .local {
return [ userTrashURL ]
} else {
return []
}
case .itemReplacementDirectory:
// This directory is only returned by url(for:in:appropriateFor:create:)
return []
}
}
private enum URLForDirectoryError: Error {
case directoryUnknown
}
/* -URLForDirectory:inDomain:appropriateForURL:create:error: is a URL-based replacement for FSFindFolder(). It allows for the specification and (optional) creation of a specific directory for a particular purpose (e.g. the replacement of a particular item on disk, or a particular Library directory.
You may pass only one of the values from the NSSearchPathDomainMask enumeration, and you may not pass NSAllDomainsMask.
*/
open func url(for directory: SearchPathDirectory, in domain: SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool) throws -> URL {
let urls = self.urls(for: directory, in: domain)
guard let url = urls.first else {
// On Apple OSes, this case returns nil without filling in the error parameter; Swift then synthesizes an error rather than trap.
// We simulate that behavior by throwing a private error.
throw URLForDirectoryError.directoryUnknown
}
if shouldCreate {
var attributes: [FileAttributeKey : Any] = [:]
switch _SearchPathDomain(domain) {
case .some(.user):
attributes[.posixPermissions] = 0700
case .some(.system):
attributes[.posixPermissions] = 0755
attributes[.ownerAccountID] = 0 // root
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
attributes[.ownerAccountID] = 80 // on Darwin, the admin group's fixed ID.
#endif
default:
break
}
try createDirectory(at: url, withIntermediateDirectories: true, attributes: attributes)
}
return url
}
/* Sets 'outRelationship' to NSURLRelationshipContains if the directory at 'directoryURL' directly or indirectly contains the item at 'otherURL', meaning 'directoryURL' is found while enumerating parent URLs starting from 'otherURL'. Sets 'outRelationship' to NSURLRelationshipSame if 'directoryURL' and 'otherURL' locate the same item, meaning they have the same NSURLFileResourceIdentifierKey value. If 'directoryURL' is not a directory, or does not contain 'otherURL' and they do not locate the same file, then sets 'outRelationship' to NSURLRelationshipOther. If an error occurs, returns NO and sets 'error'.
*/
open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, ofDirectoryAt directoryURL: URL, toItemAt otherURL: URL) throws {
NSUnimplemented()
}
/* Similar to -[NSFileManager getRelationship:ofDirectoryAtURL:toItemAtURL:error:], except that the directory is instead defined by an NSSearchPathDirectory and NSSearchPathDomainMask. Pass 0 for domainMask to instruct the method to automatically choose the domain appropriate for 'url'. For example, to discover if a file is contained by a Trash directory, call [fileManager getRelationship:&result ofDirectory:NSTrashDirectory inDomain:0 toItemAtURL:url error:&error].
*/
open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, of directory: SearchPathDirectory, in domainMask: SearchPathDomainMask, toItemAt url: URL) throws {
NSUnimplemented()
}
/* createDirectoryAtURL:withIntermediateDirectories:attributes:error: creates a directory at the specified URL. If you pass 'NO' for withIntermediateDirectories, the directory must not exist at the time this call is made. Passing 'YES' for withIntermediateDirectories will create any necessary intermediate directories. This method returns YES if all directories specified in 'url' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.
*/
open func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
try self.createDirectory(atPath: url.path, withIntermediateDirectories: createIntermediates, attributes: attributes)
}
/* createSymbolicLinkAtURL:withDestinationURL:error: returns YES if the symbolic link that point at 'destURL' was able to be created at the location specified by 'url'. 'destURL' is always resolved against its base URL, if it has one. If 'destURL' has no base URL and it's 'relativePath' is indeed a relative path, then a relative symlink will be created. If this method returns NO, the link was unable to be created and an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
*/
open func createSymbolicLink(at url: URL, withDestinationURL destURL: URL) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
guard destURL.scheme == nil || destURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : destURL])
}
try self.createSymbolicLink(atPath: url.path, withDestinationPath: destURL.path)
}
/* Instances of FileManager may now have delegates. Each instance has one delegate, and the delegate is not retained. In versions of Mac OS X prior to 10.5, the behavior of calling [[NSFileManager alloc] init] was undefined. In Mac OS X 10.5 "Leopard" and later, calling [[NSFileManager alloc] init] returns a new instance of an FileManager.
*/
open weak var delegate: FileManagerDelegate?
/* setAttributes:ofItemAtPath:error: returns YES when the attributes specified in the 'attributes' dictionary are set successfully on the item specified by 'path'. If this method returns NO, a presentable NSError will be provided by-reference in the 'error' parameter. If no error is required, you may pass 'nil' for the error.
This method replaces changeFileAttributes:atPath:.
*/
open func setAttributes(_ attributes: [FileAttributeKey : Any], ofItemAtPath path: String) throws {
try _fileSystemRepresentation(withPath: path, { fsRep in
for attribute in attributes.keys {
if attribute == .posixPermissions {
guard let number = attributes[attribute] as? NSNumber else {
fatalError("Can't set file permissions to \(attributes[attribute] as Any?)")
}
#if os(macOS) || os(iOS)
let modeT = number.uint16Value
#elseif os(Linux) || os(Android) || os(Windows)
let modeT = number.uint32Value
#endif
guard chmod(fsRep, mode_t(modeT)) == 0 else {
throw _NSErrorWithErrno(errno, reading: false, path: path)
}
} else {
fatalError("Attribute type not implemented: \(attribute)")
}
}
})
}
/* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this call is made. Passing 'YES' for 'createIntermediates' will create any necessary intermediate directories. This method returns YES if all directories specified in 'path' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.
This method replaces createDirectoryAtPath:attributes:
*/
open func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws {
#if os(Windows)
if createIntermediates {
var isDir: ObjCBool = false
if fileExists(atPath: path, isDirectory: &isDir) {
guard isDir.boolValue else { throw _NSErrorWithErrno(EEXIST, reading: false, path: path) }
return
}
let parent = path._nsObject.deletingLastPathComponent
if !parent.isEmpty && !fileExists(atPath: parent, isDirectory: &isDir) {
try createDirectory(atPath: parent, withIntermediateDirectories: true, attributes: attributes)
}
}
var saAttributes: SECURITY_ATTRIBUTES =
SECURITY_ATTRIBUTES(nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
lpSecurityDescriptor: nil,
bInheritHandle: FALSE)
let psaAttributes: UnsafeMutablePointer<SECURITY_ATTRIBUTES> =
UnsafeMutablePointer<SECURITY_ATTRIBUTES>(&saAttributes)
try path.withCString(encodedAs: UTF16.self) {
if CreateDirectoryW($0, psaAttributes) == FALSE {
// FIXME(compnerd) pass along path
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
}
}
if let attr = attributes {
try self.setAttributes(attr, ofItemAtPath: path)
}
#else
try _fileSystemRepresentation(withPath: path, { pathFsRep in
if createIntermediates {
var isDir: ObjCBool = false
if !fileExists(atPath: path, isDirectory: &isDir) {
let parent = path._nsObject.deletingLastPathComponent
if !parent.isEmpty && !fileExists(atPath: parent, isDirectory: &isDir) {
try createDirectory(atPath: parent, withIntermediateDirectories: true, attributes: attributes)
}
if mkdir(pathFsRep, S_IRWXU | S_IRWXG | S_IRWXO) != 0 {
throw _NSErrorWithErrno(errno, reading: false, path: path)
} else if let attr = attributes {
try self.setAttributes(attr, ofItemAtPath: path)
}
} else if isDir.boolValue {
return
} else {
throw _NSErrorWithErrno(EEXIST, reading: false, path: path)
}
} else {
if mkdir(pathFsRep, S_IRWXU | S_IRWXG | S_IRWXO) != 0 {
throw _NSErrorWithErrno(errno, reading: false, path: path)
} else if let attr = attributes {
try self.setAttributes(attr, ofItemAtPath: path)
}
}
})
#endif
}
private func _contentsOfDir(atPath path: String, _ closure: (String, Int32) throws -> () ) throws {
#if os(Windows)
try path.withCString(encodedAs: UTF16.self) {
var ffd: WIN32_FIND_DATAW = WIN32_FIND_DATAW()
let hDirectory: HANDLE = FindFirstFileW($0, &ffd)
if hDirectory == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
}
defer { FindClose(hDirectory) }
repeat {
let path: String = withUnsafePointer(to: &ffd.cFileName) {
$0.withMemoryRebound(to: UInt16.self, capacity: MemoryLayout.size(ofValue: $0) / MemoryLayout<WCHAR>.size) {
String(decodingCString: $0, as: UTF16.self)
}
}
try closure(path, Int32(ffd.dwFileAttributes))
} while FindNextFileW(hDirectory, &ffd) != FALSE
}
#else
try _fileSystemRepresentation(withPath: path) { fsRep in
guard let dir = opendir(fsRep) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue,
userInfo: [NSFilePathErrorKey: path, "NSUserStringVariant": NSArray(object: "Folder")])
}
defer { closedir(dir) }
var entry = dirent()
var result: UnsafeMutablePointer<dirent>? = nil
while readdir_r(dir, &entry, &result) == 0 {
guard result != nil else {
return
}
let length = Int(_direntNameLength(&entry))
let entryName = withUnsafePointer(to: &entry.d_name) { (ptr) -> String in
let namePtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)
return string(withFileSystemRepresentation: namePtr, length: length)
}
if entryName != "." && entryName != ".." {
let entryType = Int32(entry.d_type)
try closure(entryName, entryType)
}
}
}
#endif
}
/**
Performs a shallow search of the specified directory and returns the paths of any contained items.
This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”) but it does return other hidden files (files that begin with a period character).
The order of the files in the returned array is undefined.
- Parameter path: The path to the directory whose contents you want to enumerate.
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
- Returns: An array of String each of which identifies a file, directory, or symbolic link contained in `path`. The order of the files returned is undefined.
*/
open func contentsOfDirectory(atPath path: String) throws -> [String] {
var contents: [String] = []
try _contentsOfDir(atPath: path, { (entryName, entryType) throws in
contents.append(entryName)
})
return contents
}
/**
Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories.
This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion.
Because this method recurses the directory’s contents, you might not want to use it in performance-critical code. Instead, consider using the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or enumeratorAtPath: method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to abort the enumeration or perform other tasks at the same time.
- Parameter path: The path of the directory to list.
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
- Returns: An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file.
*/
open func subpathsOfDirectory(atPath path: String) throws -> [String] {
var contents: [String] = []
try _contentsOfDir(atPath: path, { (entryName, entryType) throws in
contents.append(entryName)
#if os(Windows)
if entryType & FILE_ATTRIBUTE_DIRECTORY == FILE_ATTRIBUTE_DIRECTORY {
let subPath: String = joinPath(prefix: path, suffix: entryName)
let entries = try subpathsOfDirectory(atPath: subPath)
contents.append(contentsOf: entries.map { joinPath(prefix: entryName, suffix: $0) })
}
#else
if entryType == DT_DIR {
let subPath: String = path + "/" + entryName
let entries = try subpathsOfDirectory(atPath: subPath)
contents.append(contentsOf: entries.map({file in "\(entryName)/\(file)"}))
}
#endif
})
return contents
}
#if os(Windows)
private func windowsFileAttributes(atPath path: String) throws -> WIN32_FILE_ATTRIBUTE_DATA {
var faAttributes: WIN32_FILE_ATTRIBUTE_DATA = WIN32_FILE_ATTRIBUTE_DATA()
return try path.withCString(encodedAs: UTF16.self) {
if GetFileAttributesExW($0, GetFileExInfoStandard, &faAttributes) == FALSE {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
}
return faAttributes
}
}
#endif
/* attributesOfItemAtPath:error: returns an NSDictionary of key/value pairs containing the attributes of the item (file, directory, symlink, etc.) at the path in question. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces fileAttributesAtPath:traverseLink:.
*/
open func attributesOfItem(atPath path: String) throws -> [FileAttributeKey : Any] {
var result: [FileAttributeKey:Any] = [:]
#if os(Linux)
let (s, creationDate) = try _statxFile(atPath: path)
result[.creationDate] = creationDate
#else
let s = try _lstatFile(atPath: path)
#endif
result[.size] = NSNumber(value: UInt64(s.st_size))
#if os(macOS) || os(iOS)
let ti = (TimeInterval(s.st_mtimespec.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtimespec.tv_nsec))
#elseif os(Android)
let ti = (TimeInterval(s.st_mtime) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtime_nsec))
#elseif os(Windows)
let ti = (TimeInterval(s.st_mtime) - kCFAbsoluteTimeIntervalSince1970)
#else
let ti = (TimeInterval(s.st_mtim.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtim.tv_nsec))
#endif
result[.modificationDate] = Date(timeIntervalSinceReferenceDate: ti)
result[.posixPermissions] = NSNumber(value: _filePermissionsMask(mode: UInt32(s.st_mode)))
result[.referenceCount] = NSNumber(value: UInt64(s.st_nlink))
result[.systemNumber] = NSNumber(value: UInt64(s.st_dev))
result[.systemFileNumber] = NSNumber(value: UInt64(s.st_ino))
#if os(Windows)
result[.deviceIdentifier] = NSNumber(value: UInt64(s.st_rdev))
let type = FileAttributeType(attributes: try windowsFileAttributes(atPath: path))
#else
if let pwd = getpwuid(s.st_uid), pwd.pointee.pw_name != nil {
let name = String(cString: pwd.pointee.pw_name)
result[.ownerAccountName] = name
}
if let grd = getgrgid(s.st_gid), grd.pointee.gr_name != nil {
let name = String(cString: grd.pointee.gr_name)
result[.groupOwnerAccountName] = name
}
let type = FileAttributeType(statMode: s.st_mode)
#endif
result[.type] = type
if type == .typeBlockSpecial || type == .typeCharacterSpecial {
result[.deviceIdentifier] = NSNumber(value: UInt64(s.st_rdev))
}
#if os(macOS) || os(iOS)
if (s.st_flags & UInt32(UF_IMMUTABLE | SF_IMMUTABLE)) != 0 {
result[.immutable] = NSNumber(value: true)
}
if (s.st_flags & UInt32(UF_APPEND | SF_APPEND)) != 0 {
result[.appendOnly] = NSNumber(value: true)
}
#endif
result[.ownerAccountID] = NSNumber(value: UInt64(s.st_uid))
result[.groupOwnerAccountID] = NSNumber(value: UInt64(s.st_gid))
return result
}
/* attributesOfFileSystemForPath:error: returns an NSDictionary of key/value pairs containing the attributes of the filesystem containing the provided path. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces fileSystemAttributesAtPath:.
*/
#if os(Android)
@available(*, unavailable, message: "Unsuppported on this platform")
open func attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] {
NSUnsupported()
}
#else
open func attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] {
var result: [FileAttributeKey:Any] = [:]
#if os(Windows)
try path.withCString(encodedAs: UTF16.self) {
let dwLength: DWORD = GetFullPathNameW($0, 0, nil, nil)
let szVolumePath: UnsafeMutableBufferPointer<WCHAR> = UnsafeMutableBufferPointer<WCHAR>.allocate(capacity: Int(dwLength + 1))
defer { szVolumePath.deallocate() }
guard GetVolumePathNameW($0, szVolumePath.baseAddress, dwLength) != FALSE else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
}
var liTotal: ULARGE_INTEGER = ULARGE_INTEGER()
var liFree: ULARGE_INTEGER = ULARGE_INTEGER()
guard GetDiskFreeSpaceExW(szVolumePath.baseAddress, nil, &liTotal, &liFree) != FALSE else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
}
result[.systemSize] = NSNumber(value: liTotal.QuadPart)
result[.systemFreeSize] = NSNumber(value: liFree.QuadPart)
// FIXME(compnerd): what about .systemNodes, .systemFreeNodes?
}
#else
try _fileSystemRepresentation(withPath: path) { fsRep in
// statvfs(2) doesn't support 64bit inode on Darwin (apfs), fallback to statfs(2)
#if os(macOS) || os(iOS)
var s = statfs()
guard statfs(fsRep, &s) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: path)
}
#else
var s = statvfs()
guard statvfs(fsRep, &s) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: path)
}
#endif
#if os(macOS) || os(iOS)
let blockSize = UInt64(s.f_bsize)
result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid.val.0))
#else
let blockSize = UInt64(s.f_frsize)
result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid))
#endif
result[.systemSize] = NSNumber(value: blockSize * UInt64(s.f_blocks))
result[.systemFreeSize] = NSNumber(value: blockSize * UInt64(s.f_bavail))
result[.systemNodes] = NSNumber(value: UInt64(s.f_files))
result[.systemFreeNodes] = NSNumber(value: UInt64(s.f_ffree))
}
#endif
return result
}
#endif