-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathFileSystem.swift
More file actions
74 lines (64 loc) · 2.62 KB
/
FileSystem.swift
File metadata and controls
74 lines (64 loc) · 2.62 KB
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
import Foundation
/// Provides file system related utilities backed by `FileManager`.
///
/// `FileSystem` is the concrete implementation of `FileSystemProvider` used to
/// query the file system for file existence, standard directory locations
/// and directory contents.
///
/// - Note: All returned file path sets use absolute URL string representations.
final class FileSystem: FileSystemProvider {
private let fileManager: FileManager
// MARK: - Initialization
/// Creates a new `FileSystem` instance.
/// - Parameters:
/// - fileManager: The `FileManager` used for low level file operations. Defaults to `.default`.
init(
fileManager: FileManager = .default,
) {
self.fileManager = fileManager
}
// MARK: - File Queries
/// Indicates whether a file or directory exists at the specified path.
/// - Parameter path: The path whose existence is being checked.
/// - Returns: `true` if a file system item exists at the path; otherwise `false`.
func fileExists(atPath path: String) -> Bool {
fileManager.fileExists(atPath: path)
}
/// Returns the URL of the user's Library directory.
func libraryDirectory() -> URL {
fileManager.urls(for: .libraryDirectory, in: .userDomainMask).first
?? fileManager.homeDirectoryForCurrentUser.appendingPathComponent("Library", isDirectory: true)
}
/// Returns the contents of the directory at the specified URL.
/// - Parameters:
/// - url: The URL of the directory to read.
/// - keys: An array of resource keys to prefetch for each item.
/// - mask: Options for directory enumeration.
/// - Returns: An array of URLs for the items in the directory.
/// - Throws: An error if the directory cannot be read.
func contentsOfDirectory(
at url: URL,
includingPropertiesForKeys keys: [URLResourceKey]?,
options mask: FileManager.DirectoryEnumerationOptions
) throws -> [URL] {
try fileManager.contentsOfDirectory(
at: url,
includingPropertiesForKeys: keys,
options: mask
)
}
func readFile(atPath path: String) throws -> String {
try String(contentsOfFile: path)
}
func readLines(atPath path: String) async throws -> [String] {
let url = URL(fileURLWithPath: path)
var lines: [String] = []
for try await line in url.resourceBytes.lines {
lines.append(line)
}
return lines
}
func writeFile(_ contents: String, toPath path: String) throws {
try contents.write(toFile: path, atomically: true, encoding: .utf8)
}
}