Branchwell

Textley / app · textley.ai / Sources / TextleyCore / TextFile.swift

Raw 6.4 KB on e5f2c9784a4411c0066da2556c6e5a5a36d1e961
1import Foundation
2
3public enum TextFileError: LocalizedError {
4 case unsupportedEncoding, mixedLineEndings, diskChanged, openDestination
5
6 public var errorDescription: String? {
7 switch self {
8 case .unsupportedEncoding:
9 return "This file isn’t supported plain text. Text Editor opens UTF-8 and UTF-16 with a byte-order mark."
10 case .mixedLineEndings:
11 return "This file uses mixed or unsupported line endings. Text Editor left the original file untouched."
12 case .diskChanged:
13 return "Another app changed or removed this file since Text Editor opened or saved it."
14 case .openDestination:
15 return "That file is already open in Textley. Choose another destination."
16 }
17 }
18}
19
20public enum TextEncoding: String, CaseIterable, Identifiable {
21 case utf8 = "UTF-8"
22 case utf8BOM = "UTF-8 with BOM"
23 case utf16LE = "UTF-16 LE"
24 case utf16BE = "UTF-16 BE"
25
26 public var id: Self { self }
27
28 var bom: [UInt8] {
29 switch self {
30 case .utf8: return []
31 case .utf8BOM: return [0xef, 0xbb, 0xbf]
32 case .utf16LE: return [0xff, 0xfe]
33 case .utf16BE: return [0xfe, 0xff]
34 }
35 }
36
37 var stringEncoding: String.Encoding {
38 switch self {
39 case .utf8, .utf8BOM: return .utf8
40 case .utf16LE: return .utf16LittleEndian
41 case .utf16BE: return .utf16BigEndian
42 }
43 }
44}
45
46public enum LineEnding: String, CaseIterable, Identifiable {
47 case lf = "LF"
48 case crlf = "CRLF"
49
50 public var id: Self { self }
51 var separator: String { self == .lf ? "\n" : "\r\n" }
52}
53
54public struct TextFileFormat: Equatable {
55 public var encoding: TextEncoding
56 public var lineEnding: LineEnding
57
58 public init(encoding: TextEncoding = .utf8, lineEnding: LineEnding = .lf) {
59 self.encoding = encoding
60 self.lineEnding = lineEnding
61 }
62
63 public func encode(_ text: String) throws -> Data {
64 let normalized = Self.normalizeLineEndings(text)
65 let output = lineEnding == .lf ? normalized : normalized.replacingOccurrences(of: "\n", with: "\r\n")
66 guard let bytes = output.data(using: encoding.stringEncoding) else { throw TextFileError.unsupportedEncoding }
67 var data = Data(encoding.bom)
68 data.append(bytes)
69 return data
70 }
71
72 public static func decode(_ data: Data) throws -> (text: String, format: TextFileFormat) {
73 let encoding = TextEncoding.allCases.first { !$0.bom.isEmpty && data.starts(with: $0.bom) } ?? .utf8
74 let payload = data.dropFirst(encoding.bom.count)
75 guard let text = String(data: payload, encoding: encoding.stringEncoding) else {
76 throw TextFileError.unsupportedEncoding
77 }
78 var previousCR = false
79 var sawLF = false
80 var sawCRLF = false
81 for byte in text.utf8 {
82 if byte < 0x20 && byte != 9 && byte != 10 && byte != 12 && byte != 13 && byte != 27 {
83 throw TextFileError.unsupportedEncoding
84 }
85 if previousCR && byte != 10 { throw TextFileError.mixedLineEndings }
86 if byte == 10 {
87 if previousCR { sawCRLF = true } else { sawLF = true }
88 if sawLF && sawCRLF { throw TextFileError.mixedLineEndings }
89 }
90 previousCR = byte == 13
91 }
92 if previousCR { throw TextFileError.mixedLineEndings }
93 return (sawCRLF ? normalizeLineEndings(text) : text, TextFileFormat(encoding: encoding, lineEnding: sawCRLF ? .crlf : .lf))
94 }
95
96 public static func normalizeLineEndings(_ text: String) -> String {
97 guard text.utf8.contains(13) else { return text }
98 return text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
99 }
100}
101
102public enum TextFileAccess {
103 public static func read(_ url: URL) throws -> Data {
104 var coordinationError: NSError?
105 var result: Result<Data, Error>?
106 NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &coordinationError) { coordinatedURL in
107 result = Result { try Data(contentsOf: coordinatedURL) }
108 }
109 if let coordinationError { throw coordinationError }
110 guard let result else { throw CocoaError(.fileReadUnknown) }
111 return try result.get()
112 }
113
114 public static func write(_ data: Data, to url: URL, replacing expected: Data? = nil, force: Bool = false,
115 exclusive: Bool = false) throws {
116 var coordinationError: NSError?
117 var result: Result<Void, Error>?
118 NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { coordinatedURL in
119 result = Result {
120 if let expected, !force {
121 let current: Data
122 do {
123 current = try Data(contentsOf: coordinatedURL)
124 } catch let error as CocoaError where error.code == .fileReadNoSuchFile {
125 throw TextFileError.diskChanged
126 }
127 guard current == expected else { throw TextFileError.diskChanged }
128 }
129 let manager = FileManager.default
130 if exclusive {
131 try data.write(to: coordinatedURL, options: .withoutOverwriting)
132 } else if manager.fileExists(atPath: coordinatedURL.path) {
133 let staging = try manager.url(for: .itemReplacementDirectory, in: .userDomainMask,
134 appropriateFor: coordinatedURL, create: true)
135 let replacement = staging.appendingPathComponent(coordinatedURL.lastPathComponent)
136 do {
137 try data.write(to: replacement, options: .withoutOverwriting)
138 } catch {
139 try? manager.removeItem(at: staging)
140 throw error
141 }
142 // Keep the staging directory on replacement failure in case it holds the original.
143 _ = try manager.replaceItemAt(coordinatedURL, withItemAt: replacement)
144 try? manager.removeItem(at: staging)
145 } else {
146 try data.write(to: coordinatedURL, options: .atomic)
147 }
148 }
149 }
150 if let coordinationError { throw coordinationError }
151 guard let result else { throw CocoaError(.fileWriteUnknown) }
152 try result.get()
153 }
154}