Sources/OrgApp/UserFile.swift

30 lines · 1405 bytes

4 symbols in this file
 1import Foundation
 2
 3/// Reading a configuration file in order to change it: only a file that isn't there counts as
 4/// empty, so that one that can't be read is never written over.
 5public enum UserFile {
 6    /// The file's text, or nil when there is no such file. Any other failure is thrown.
 7    public static func text(at url: URL) throws -> String? {
 8        do {
 9            return try String(contentsOf: url, encoding: .utf8)
10        } catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile {
11            return nil
12        }
13    }
14
15    /// Writes what `change` makes of the file's text, "" when there is no such file. Throws,
16    /// leaving the file alone, when it can't be read. With `coordinated`, in coordination with
17    /// the app that syncs the file.
18    public static func update(_ url: URL, coordinated: Bool = false, _ change: (String) -> String) throws {
19        func write(_ url: URL) throws {
20            try change(text(at: url) ?? "").write(to: url, atomically: true, encoding: .utf8)
21        }
22        guard coordinated else { return try write(url) }
23        var coordination: NSError?
24        var failure: Error?
25        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: url, options: [], error: &coordination) { url in
26            do { try write(url) } catch { failure = error }
27        }
28        if let error = coordination ?? failure { throw error }
29    }
30}