Commit 9f33aea70f

9f33aea70f08a8299cb34d6e14579eff87c321ad

parent: ef89d935d4

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 12:25 UTC

Leave configuration files that can't be read and report failed writes

UserFile reads a file to change it and treats only a missing file as empty.
The iOS settings, ConfigSync, the Emacs import, saved agenda views and the
clock report's Save report read and write failures instead of dropping them,
and the import summary counts only what was written.

Closes #192

Layout: unified · split

Sources/OrgApp/AgendaViews.swift +3 −3
@@ -251,11 +251,11 @@ public enum AgendaViewLoader {
251 guard let table = table(name: name, mode: mode) else { 251 guard let table = table(name: name, mode: mode) else {
252 throw SaveFailure(description: String(localized: "This view can't be saved from here; write it in views.toml.")) 252 throw SaveFailure(description: String(localized: "This view can't be saved from here; write it in views.toml."))
253 } 253 }
254 var text = (try? String(contentsOf: userFile, encoding: .utf8)) ?? ""
255 if !text.isEmpty { text += text.hasSuffix("\n") ? "\n" : "\n\n" }
256 do { 254 do {
257 try FileManager.default.createDirectory(at: userFile.deletingLastPathComponent(), withIntermediateDirectories: true) 255 try FileManager.default.createDirectory(at: userFile.deletingLastPathComponent(), withIntermediateDirectories: true)
258 try (text + table).write(to: userFile, atomically: true, encoding: .utf8) 256 try UserFile.update(userFile) { text in
257 text + (text.isEmpty ? "" : text.hasSuffix("\n") ? "\n" : "\n\n") + table
258 }
259 } catch { 259 } catch {
260 throw SaveFailure(description: error.localizedDescription) 260 throw SaveFailure(description: error.localizedDescription)
261 } 261 }
Sources/OrgApp/ConfigSync.swift +41 −10
@@ -24,6 +24,9 @@ public final class ConfigSync {
24 private let defaults: UserDefaults 24 private let defaults: UserDefaults
25 @ObservationIgnored private var text: String? 25 @ObservationIgnored private var text: String?
26 @ObservationIgnored private var configProblems: [String] = [] 26 @ObservationIgnored private var configProblems: [String] = []
27 @ObservationIgnored private var themeProblems: [String] = []
28 /// Why the file couldn't be read or written, the last time a setting was to go into it.
29 @ObservationIgnored private var fileProblem: String?
27 @ObservationIgnored private var applying = false 30 @ObservationIgnored private var applying = false
28 @ObservationIgnored private var watcher: FSEventsWatcher? 31 @ObservationIgnored private var watcher: FSEventsWatcher?
29 @ObservationIgnored private var observer: NSObjectProtocol? 32 @ObservationIgnored private var observer: NSObjectProtocol?
@@ -53,15 +56,11 @@ public final class ConfigSync {
53 if let text { 56 if let text {
54 let migrated = UserConfig.usesLegacyNames(text) ? UserConfig.migratingLegacyNames(text) : text 57 let migrated = UserConfig.usesLegacyNames(text) ? UserConfig.migratingLegacyNames(text) : text
55 let completed = UserConfig.addingMissingSections(migrated, from: defaults) 58 let completed = UserConfig.addingMissingSections(migrated, from: defaults)
56 if completed != text { 59 if completed != text, write(completed) { self.text = completed }
57 try? completed.write(to: target, atomically: true, encoding: .utf8)
58 self.text = completed
59 }
60 } 60 }
61 } else { 61 } else {
62 let template = UserConfig.template(from: defaults) 62 let template = UserConfig.template(from: defaults)
63 try? template.write(to: target, atomically: true, encoding: .utf8) 63 if write(template) { text = template }
64 text = template
65 } 64 }
66 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in 65 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
67 MainActor.assumeIsolated { self?.writeBack() } 66 MainActor.assumeIsolated { self?.writeBack() }
@@ -105,6 +104,8 @@ public final class ConfigSync {
105 observer = nil 104 observer = nil
106 text = nil 105 text = nil
107 configProblems = [] 106 configProblems = []
107 themeProblems = []
108 fileProblem = nil
108 self.url = url 109 self.url = url
109 start(watch: watches) 110 start(watch: watches)
110 readTheme() 111 readTheme()
@@ -142,13 +143,40 @@ public final class ConfigSync {
142 in: url.deletingLastPathComponent() 143 in: url.deletingLastPathComponent()
143 ) else { return } 144 ) else { return }
144 if read.theme != theme { theme = read.theme } 145 if read.theme != theme { theme = read.theme }
145 problems = configProblems + read.problems 146 themeProblems = read.problems
147 updateProblems()
148 }
149
150 private func updateProblems() {
151 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems
152 if all != problems { problems = all }
153 }
154
155 /// Writes the file; false, with the reason among `problems`, when that fails.
156 private func write(_ new: String) -> Bool {
157 do {
158 try new.write(to: target, atomically: true, encoding: .utf8)
159 fileProblem = nil
160 } catch {
161 fileProblem = "\(url.lastPathComponent) wasn't written: \(error.localizedDescription)"
162 }
163 updateProblems()
164 return fileProblem == nil
146 } 165 }
147 166
148 /// Writes settings that differ from the file into it. 167 /// Writes settings that differ from the file into it.
149 func writeBack() { 168 func writeBack() {
150 // The file as it is now, so that tables written into it since, as by Emacs import, stay. 169 // The file as it is now, so that tables written into it since, as by Emacs import, stay.
151 guard !applying, var current = (try? String(contentsOf: url, encoding: .utf8)) ?? text else { return } 170 guard !applying else { return }
171 let onDisk: String?
172 do {
173 onDisk = try UserFile.text(at: url)
174 } catch {
175 fileProblem = "\(url.lastPathComponent) wasn't changed: \(error.localizedDescription)"
176 updateProblems()
177 return
178 }
179 guard var current = onDisk ?? text else { return }
152 let values = UserConfig.values(in: current) 180 let values = UserConfig.values(in: current)
153 let original = current 181 let original = current
154 for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil { 182 for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
@@ -164,9 +192,12 @@ public final class ConfigSync {
164 for template in UserConfig.denoteTemplates(defaults) where values[UserConfig.path(UserConfig.denoteTemplateTable, template.key)] != .string(template.text) { 192 for template in UserConfig.denoteTemplates(defaults) where values[UserConfig.path(UserConfig.denoteTemplateTable, template.key)] != .string(template.text) {
165 current = UserConfig.setting(current, section: UserConfig.denoteTemplateTable, key: template.key, to: .string(template.text)) 193 current = UserConfig.setting(current, section: UserConfig.denoteTemplateTable, key: template.key, to: .string(template.text))
166 } 194 }
167 guard current != original else { return } 195 guard current != original else {
196 fileProblem = nil
197 return updateProblems()
198 }
199 guard write(current) else { return }
168 text = current 200 text = current
169 try? current.write(to: target, atomically: true, encoding: .utf8)
170 // A theme picked in Settings; the watcher's reload sees the text unchanged and skips it. 201 // A theme picked in Settings; the watcher's reload sees the text unchanged and skips it.
171 readTheme() 202 readTheme()
172 } 203 }
Sources/OrgApp/EmacsImport.swift +33 −11
@@ -1134,7 +1134,8 @@ extension EmacsImport {
1134 /// Applies `items`: settings to `defaults` (and so config.toml), folders to the workspace, 1134 /// Applies `items`: settings to `defaults` (and so config.toml), folders to the workspace,
1135 /// capture templates and key bindings appended to capture.toml and keymap.toml in 1135 /// capture templates and key bindings appended to capture.toml and keymap.toml in
1136 /// `directory`, leaving out templates whose key is there already and bindings that are 1136 /// `directory`, leaving out templates whose key is there already and bindings that are
1137 /// there already. Returns a summary. 1137 /// there already. A file that is there but can't be read is left as it is. Returns a summary,
1138 /// which counts only what was written.
1138 @MainActor 1139 @MainActor
1139 /// With `writeConfig`, settings and structure templates are written into `config.toml` too, 1140 /// With `writeConfig`, settings and structure templates are written into `config.toml` too,
1140 /// for where nothing syncs user defaults into it (iOS). With `chosenFolders`, folders chosen in 1141 /// for where nothing syncs user defaults into it (iOS). With `chosenFolders`, folders chosen in
@@ -1193,8 +1194,28 @@ extension EmacsImport {
1193 } 1194 }
1194 } 1195 }
1195 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) 1196 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
1197 // Files that are there but can't be read; nothing is written to them.
1198 var unreadable: Set<URL> = []
1199 func read(_ file: URL) -> String {
1200 do {
1201 return try UserFile.text(at: file) ?? ""
1202 } catch {
1203 if unreadable.insert(file).inserted { problems.append("\(file.lastPathComponent) wasn't changed: \(error.localizedDescription)") }
1204 return ""
1205 }
1206 }
1207 func write(_ text: String, to file: URL) -> Bool {
1208 guard !unreadable.contains(file) else { return false }
1209 do {
1210 try text.write(to: file, atomically: true, encoding: .utf8)
1211 return true
1212 } catch {
1213 problems.append("\(file.lastPathComponent) wasn't written: \(error.localizedDescription)")
1214 return false
1215 }
1216 }
1196 let captureFile = directory.appendingPathComponent("capture.toml") 1217 let captureFile = directory.appendingPathComponent("capture.toml")
1197 var capture = (try? String(contentsOf: captureFile, encoding: .utf8)) ?? "" 1218 var capture = read(captureFile)
1198 let existingKeys = Set((try? TOML.parse(capture))?.compactMap { $0.values["key"]?.string } ?? []) 1219 let existingKeys = Set((try? TOML.parse(capture))?.compactMap { $0.values["key"]?.string } ?? [])
1199 var addedCapture = "" 1220 var addedCapture = ""
1200 for item in items { 1221 for item in items {
@@ -1204,10 +1225,10 @@ extension EmacsImport {
1204 } 1225 }
1205 if !addedCapture.isEmpty { 1226 if !addedCapture.isEmpty {
1206 capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture 1227 capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture
1207 try? capture.write(to: captureFile, atomically: true, encoding: .utf8) 1228 if !write(capture, to: captureFile) { templates = 0 }
1208 } 1229 }
1209 let viewsFile = directory.appendingPathComponent("views.toml") 1230 let viewsFile = directory.appendingPathComponent("views.toml")
1210 var viewsText = (try? String(contentsOf: viewsFile, encoding: .utf8)) ?? "" 1231 var viewsText = read(viewsFile)
1211 var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? []) 1232 var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? [])
1212 var addedViews = "" 1233 var addedViews = ""
1213 for item in items { 1234 for item in items {
@@ -1217,10 +1238,10 @@ extension EmacsImport {
1217 } 1238 }
1218 if !addedViews.isEmpty { 1239 if !addedViews.isEmpty {
1219 viewsText += (viewsText.isEmpty ? "# Agenda views. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedViews 1240 viewsText += (viewsText.isEmpty ? "# Agenda views. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedViews
1220 try? viewsText.write(to: viewsFile, atomically: true, encoding: .utf8) 1241 if !write(viewsText, to: viewsFile) { views = 0 }
1221 } 1242 }
1222 let configFile = directory.appendingPathComponent("config.toml") 1243 let configFile = directory.appendingPathComponent("config.toml")
1223 var config = (try? String(contentsOf: configFile, encoding: .utf8)) ?? "" 1244 var config = read(configFile)
1224 var projectNames = Set((try? TOML.parse(config))?.filter { $0.name == "publish" }.compactMap { $0.values["name"]?.string } ?? []) 1245 var projectNames = Set((try? TOML.parse(config))?.filter { $0.name == "publish" }.compactMap { $0.values["name"]?.string } ?? [])
1225 var addedProjects = "" 1246 var addedProjects = ""
1226 for item in items { 1247 for item in items {
@@ -1230,10 +1251,10 @@ extension EmacsImport {
1230 } 1251 }
1231 if !addedProjects.isEmpty { 1252 if !addedProjects.isEmpty {
1232 config += (config.isEmpty || config.hasSuffix("\n") ? "" : "\n") + "\n# Publishing projects. Imported from Emacs.\n" + addedProjects 1253 config += (config.isEmpty || config.hasSuffix("\n") ? "" : "\n") + "\n# Publishing projects. Imported from Emacs.\n" + addedProjects
1233 try? config.write(to: configFile, atomically: true, encoding: .utf8) 1254 if !write(config, to: configFile) { projects = 0 }
1234 } 1255 }
1235 let keymapFile = directory.appendingPathComponent("keymap.toml") 1256 let keymapFile = directory.appendingPathComponent("keymap.toml")
1236 var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? "" 1257 var keymap = read(keymapFile)
1237 func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") } 1258 func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") }
1238 var existingBindings = Set((try? TOML.parse(keymap))?.filter { $0.name == "bind" && $0.values["when"] == nil } 1259 var existingBindings = Set((try? TOML.parse(keymap))?.filter { $0.name == "bind" && $0.values["when"] == nil }
1239 .map { binding($0.values["keys"]?.string, $0.values["command"]?.string, $0.values["mode"]?.string) } ?? []) 1260 .map { binding($0.values["keys"]?.string, $0.values["command"]?.string, $0.values["mode"]?.string) } ?? [])
@@ -1247,7 +1268,7 @@ extension EmacsImport {
1247 } 1268 }
1248 if !addedKeys.isEmpty { 1269 if !addedKeys.isEmpty {
1249 keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys 1270 keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys
1250 try? keymap.write(to: keymapFile, atomically: true, encoding: .utf8) 1271 if !write(keymap, to: keymapFile) { bindings = 0 }
1251 } 1272 }
1252 // Into user defaults, from where ConfigSync writes them into config.toml. 1273 // Into user defaults, from where ConfigSync writes them into config.toml.
1253 var rows = UserConfig.structureTemplates(defaults) 1274 var rows = UserConfig.structureTemplates(defaults)
@@ -1267,7 +1288,7 @@ extension EmacsImport {
1267 } 1288 }
1268 if noteTemplates > 0 { UserConfig.setDenoteTemplates(notes, in: defaults) } 1289 if noteTemplates > 0 { UserConfig.setDenoteTemplates(notes, in: defaults) }
1269 if writeConfig, settings + blocks + noteTemplates > 0 { 1290 if writeConfig, settings + blocks + noteTemplates > 0 {
1270 var text = (try? String(contentsOf: configFile, encoding: .utf8)) ?? "" 1291 var text = read(configFile)
1271 for setting in stored { 1292 for setting in stored {
1272 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults)) 1293 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults))
1273 } 1294 }
@@ -1279,7 +1300,8 @@ extension EmacsImport {
1279 guard case .denoteTemplate(let key, let template) = item.change else { continue } 1300 guard case .denoteTemplate(let key, let template) = item.change else { continue }
1280 text = UserConfig.setting(text, section: UserConfig.denoteTemplateTable, key: key, to: .string(template)) 1301 text = UserConfig.setting(text, section: UserConfig.denoteTemplateTable, key: key, to: .string(template))
1281 } 1302 }
1282 try? text.write(to: configFile, atomically: true, encoding: .utf8) 1303 // Here config.toml holds the settings, so one that isn't in it wasn't imported.
1304 if !write(text, to: configFile) { (settings, blocks, noteTemplates) = (0, 0, 0) }
1283 } 1305 }
1284 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" } 1306 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
1285 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"), 1307 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
Sources/OrgApp/UserFile.swift added +30
@@ -0,0 +1,30 @@
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}
Sources/Orgstar/ClockViews.swift +5 −1
@@ -259,6 +259,10 @@ struct ClockReportView: View {
259 let panel = NSSavePanel() 259 let panel = NSSavePanel()
260 panel.nameFieldStringValue = "time-report.org" 260 panel.nameFieldStringValue = "time-report.org"
261 guard panel.runModal() == .OK, let url = panel.url else { return } 261 guard panel.runModal() == .OK, let url = panel.url else { return }
262 try? report.write(to: url, atomically: true, encoding: .utf8) 262 do {
263 try report.write(to: url, atomically: true, encoding: .utf8)
264 } catch {
265 NSAlert(error: error).runModal()
266 }
263 } 267 }
264} 268}
Sources/OrgstarMobile/MobileModel.swift +33 −18
@@ -108,16 +108,17 @@ final class MobileModel {
108 108
109 /// Chooses the configuration folder, or with nil stops using one; its settings apply now. 109 /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
110 func setConfigFolder(_ url: URL?) { 110 func setConfigFolder(_ url: URL?) {
111 var problem: String?
111 if let url { 112 if let url {
112 ConfigFolder.set(url) 113 ConfigFolder.set(url)
113 Self.createConfig(in: url) 114 problem = Self.createConfig(in: url)
114 } else { 115 } else {
115 ConfigFolder.clear() 116 ConfigFolder.clear()
116 // What the folder set no longer applies. 117 // What the folder set no longer applies.
117 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) } 118 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
118 } 119 }
119 configFolder = url 120 configFolder = url
120 reloadConfig() 121 _ = reloadConfig(after: problem)
121 watchConfig() 122 watchConfig()
122 } 123 }
123 124
@@ -168,27 +169,38 @@ final class MobileModel {
168 configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) } 169 configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
169 } 170 }
170 171
171 /// Writes the folder's `config.toml` and applies it. 172 /// Writes the folder's `config.toml` and applies it. False, with the reason first in
172 func saveConfig(_ text: String) { 173 /// `configProblems`, when the file can't be written or what it holds can't be read.
173 guard let configFolder else { return } 174 @discardableResult
174 var error: NSError? 175 func saveConfig(_ text: String) -> Bool {
175 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: configFolder.appendingPathComponent("config.toml"), options: [], error: &error) { url in 176 guard let configFolder else { return false }
176 try? text.write(to: url, atomically: true, encoding: .utf8) 177 return reloadConfig(after: Self.updateConfig(in: configFolder) { _ in text })
178 }
179
180 /// Changes the folder's `config.toml`; returns the problem when it can't be read or written.
181 private static func updateConfig(in folder: URL, _ change: (String) -> String) -> String? {
182 do {
183 try UserFile.update(folder.appendingPathComponent("config.toml"), coordinated: true, change)
184 return nil
185 } catch {
186 return "config.toml wasn't changed: \(error.localizedDescription)"
177 } 187 }
188 }
189
190 /// Applies the folder's settings, with the `problem` of the write before it first.
191 private func reloadConfig(after problem: String?) -> Bool {
178 reloadConfig() 192 reloadConfig()
193 if let problem { configProblems.insert(problem, at: 0) }
194 return problem == nil
179 } 195 }
180 196
181 /// Changes a setting from the app: in the folder's config.toml when there is a folder, as 197 /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
182 /// the Mac's Settings write it, else in this device's settings. 198 /// the Mac's Settings write it, else in this device's settings.
183 func set(_ defaultsKey: String, to value: TOML.Value) { 199 func set(_ defaultsKey: String, to value: TOML.Value) {
184 guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return } 200 guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
201 var problem: String?
185 if let configFolder { 202 if let configFolder {
186 let file = configFolder.appendingPathComponent("config.toml") 203 problem = Self.updateConfig(in: configFolder) { UserConfig.setting($0, section: setting.section, key: setting.key, to: value) }
187 var error: NSError?
188 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
189 let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
190 try? UserConfig.setting(text, section: setting.section, key: setting.key, to: value).write(to: url, atomically: true, encoding: .utf8)
191 }
192 } else { 204 } else {
193 switch value { 205 switch value {
194 case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey) 206 case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
@@ -196,7 +208,7 @@ final class MobileModel {
196 case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey) 208 case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
197 } 209 }
198 } 210 }
199 reloadConfig() 211 _ = reloadConfig(after: problem)
200 } 212 }
201 213
202 /// The capture templates, for the share extension to offer. 214 /// The capture templates, for the share extension to offer.
@@ -218,14 +230,17 @@ final class MobileModel {
218 230
219 /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's 231 /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
220 /// colors. 232 /// colors.
221 /// Writes `config.toml` with every setting at its default when the folder has none. 233 /// Writes `config.toml` with every setting at its default when the folder has none; returns
222 private static func createConfig(in folder: URL) { 234 /// the problem when it can't be written.
235 private static func createConfig(in folder: URL) -> String? {
223 let file = folder.appendingPathComponent("config.toml") 236 let file = folder.appendingPathComponent("config.toml")
224 var error: NSError? 237 var error: NSError?
238 var failure: Error?
225 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in 239 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
226 guard !FileManager.default.fileExists(atPath: url.path) else { return } 240 guard !FileManager.default.fileExists(atPath: url.path) else { return }
227 try? UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8) 241 do { try UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8) } catch { failure = error }
228 } 242 }
243 return (error ?? failure).map { "config.toml wasn't created: \($0.localizedDescription)" }
229 } 244 }
230 245
231 private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) { 246 private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
Sources/OrgstarMobile/SettingsScreen.swift +1 −2
@@ -362,8 +362,7 @@ struct ConfigFileEditor: View {
362 362
363 private func save() { 363 private func save() {
364 guard text != saved else { return } 364 guard text != saved else { return }
365 model.saveConfig(text) 365 if model.saveConfig(text) { saved = text }
366 saved = text
367 } 366 }
368} 367}
369 368
Tests/OrgAppTests/UserFileTests.swift added +153
@@ -0,0 +1,153 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgApp
5
6/// Bytes that aren't UTF-8: a file that is there and can't be read as text.
7private let notText = Data([0xFF, 0xFE, 0xFD])
8
9private func item(_ change: EmacsImport.Change) -> EmacsImport.Item {
10 EmacsImport.Item(id: 0, name: "", summary: "", source: "config.el:1", change: change)
11}
12
13private func defaults() -> UserDefaults {
14 let name = "orgstar-userfile-\(UUID().uuidString)"
15 let defaults = UserDefaults(suiteName: name)!
16 defaults.removePersistentDomain(forName: name)
17 return defaults
18}
19
20/// Takes or gives back the folder's write permission, so that writes into it fail.
21private func setWritable(_ writable: Bool, _ folder: URL) {
22 try? FileManager.default.setAttributes([.posixPermissions: writable ? 0o755 : 0o555], ofItemAtPath: folder.path)
23}
24
25struct UserFileTests {
26 @Test func onlyAMissingFileIsEmpty() throws {
27 let folder = try Folder()
28 let file = folder.url.appendingPathComponent("config.toml")
29 #expect(try UserFile.text(at: file) == nil)
30 try "a = 1\n".write(to: file, atomically: true, encoding: .utf8)
31 #expect(try UserFile.text(at: file) == "a = 1\n")
32 try notText.write(to: file)
33 #expect(throws: (any Error).self) { try UserFile.text(at: file) }
34 try FileManager.default.removeItem(at: file)
35 try FileManager.default.createDirectory(at: file, withIntermediateDirectories: true)
36 #expect(throws: (any Error).self) { try UserFile.text(at: file) }
37 }
38
39 @Test(arguments: [false, true]) func updateLeavesAFileItCannotRead(coordinated: Bool) throws {
40 let folder = try Folder()
41 let file = folder.url.appendingPathComponent("config.toml")
42 try UserFile.update(file, coordinated: coordinated) { $0 + "a = 1\n" }
43 try UserFile.update(file, coordinated: coordinated) { $0 + "b = 2\n" }
44 #expect(try String(contentsOf: file, encoding: .utf8) == "a = 1\nb = 2\n")
45 try notText.write(to: file)
46 #expect(throws: (any Error).self) { try UserFile.update(file, coordinated: coordinated) { $0 + "c = 3\n" } }
47 #expect(try Data(contentsOf: file) == notText)
48 }
49
50 @Test(arguments: [false, true]) func updateReportsAFailedWrite(coordinated: Bool) throws {
51 let folder = try Folder()
52 let file = folder.url.appendingPathComponent("config.toml")
53 setWritable(false, folder.url)
54 defer { setWritable(true, folder.url) }
55 #expect(throws: (any Error).self) { try UserFile.update(file, coordinated: coordinated) { $0 + "a = 1\n" } }
56 #expect(!FileManager.default.fileExists(atPath: file.path))
57 }
58
59 @MainActor
60 @Test func savingAViewLeavesAFileItCannotRead() throws {
61 let folder = try Folder()
62 let file = folder.url.appendingPathComponent("views.toml")
63 try notText.write(to: file)
64 #expect(throws: AgendaViewLoader.SaveFailure.self) { try AgendaViewLoader.save(name: "Work", mode: .match("+work", todoOnly: false), userFile: file) }
65 #expect(try Data(contentsOf: file) == notText)
66 }
67}
68
69@MainActor
70struct EmacsImportFileTests {
71 private let items = [
72 item(.capture(key: "x", toml: "[[template]]\nkey = \"x\"\nfile = \"x.org\"\ntemplate = \"* %?\"\n")),
73 item(.view(name: "Work", toml: "[[view]]\nname = \"Work\"\ntype = \"match\"\nmatch = \"+work\"\n")),
74 item(.binding(keys: "C-c z", command: "app.agenda", mode: nil)),
75 item(.setting(key: "fill-column", value: .integer(64))),
76 ]
77
78 @Test func leavesFilesItCannotReadAndDoesNotCountThem() async throws {
79 let folder = try Folder()
80 let names = ["capture.toml", "views.toml", "keymap.toml", "config.toml"]
81 for name in names { try notText.write(to: folder.url.appendingPathComponent(name)) }
82 let summary = await EmacsImport.apply(items, defaults: defaults(), workspace: nil, directory: folder.url, writeConfig: true)
83 for name in names {
84 #expect(try Data(contentsOf: folder.url.appendingPathComponent(name)) == notText)
85 #expect(summary.components(separatedBy: "\(name) wasn't changed: ").count == 2, "\(summary)")
86 }
87 #expect(summary.hasPrefix("Nothing new to import. "), "\(summary)")
88 }
89
90 @Test func oneUnreadableFileDoesNotStopTheOthers() async throws {
91 let folder = try Folder()
92 try notText.write(to: folder.url.appendingPathComponent("capture.toml"))
93 let summary = await EmacsImport.apply(items, defaults: defaults(), workspace: nil, directory: folder.url)
94 #expect(summary.hasPrefix("Imported 1 setting, 1 key binding, 1 agenda view. capture.toml wasn't changed: "), "\(summary)")
95 #expect(try Data(contentsOf: folder.url.appendingPathComponent("capture.toml")) == notText)
96 #expect(try String(contentsOf: folder.url.appendingPathComponent("views.toml"), encoding: .utf8).contains("name = \"Work\""))
97 }
98
99 @Test func reportsFailedWritesAndDoesNotCountThem() async throws {
100 let folder = try Folder()
101 setWritable(false, folder.url)
102 defer { setWritable(true, folder.url) }
103 let summary = await EmacsImport.apply(items, defaults: defaults(), workspace: nil, directory: folder.url, writeConfig: true)
104 #expect(summary.hasPrefix("Nothing new to import. "), "\(summary)")
105 for name in ["capture.toml", "views.toml", "keymap.toml", "config.toml"] {
106 #expect(summary.contains("\(name) wasn't written: "), "\(summary)")
107 }
108 }
109}
110
111@MainActor
112struct ConfigSyncFileTests {
113 @Test func leavesAFileItCannotReadAndReportsIt() throws {
114 let folder = try Folder()
115 let url = folder.url.appendingPathComponent("config.toml")
116 try notText.write(to: url)
117 let store = defaults()
118 let sync = ConfigSync(url: url, defaults: store)
119 sync.start(watch: false)
120 store.set(64, forKey: "fillColumn")
121 sync.writeBack()
122 #expect(try Data(contentsOf: url) == notText)
123 #expect(sync.problems.first?.hasPrefix("config.toml wasn't changed: ") == true, "\(sync.problems)")
124 }
125
126 @Test func reportsAFailedWriteUntilOneWorks() throws {
127 let folder = try Folder()
128 let url = folder.url.appendingPathComponent("config.toml")
129 let store = defaults()
130 let sync = ConfigSync(url: url, defaults: store)
131 sync.start(watch: false)
132 let written = try String(contentsOf: url, encoding: .utf8)
133 setWritable(false, folder.url)
134 defer { setWritable(true, folder.url) }
135 store.set(64, forKey: "fillColumn")
136 sync.writeBack()
137 #expect(try String(contentsOf: url, encoding: .utf8) == written)
138 #expect(sync.problems.first?.hasPrefix("config.toml wasn't written: ") == true, "\(sync.problems)")
139 setWritable(true, folder.url)
140 sync.writeBack()
141 #expect(try String(contentsOf: url, encoding: .utf8).contains("fill-column = 64"))
142 #expect(!sync.problems.contains { $0.contains("wasn't written") })
143 }
144
145 @Test func reportsAFileItCannotCreate() throws {
146 let folder = try Folder()
147 let sync = ConfigSync(url: folder.url.appendingPathComponent("config.toml"), defaults: defaults())
148 setWritable(false, folder.url)
149 defer { setWritable(true, folder.url) }
150 sync.start(watch: false)
151 #expect(sync.problems.first?.hasPrefix("config.toml wasn't written: ") == true, "\(sync.problems)")
152 }
153}
docs/manual/guide/13-configuration.org +1 −1
@@ -23,7 +23,7 @@ The folder holds these files:
23| =views.toml= | Saved agenda views | No | 23| =views.toml= | Saved agenda views | No |
24| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch | 24| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch |
25 25
26=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. 26=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way.
27 27
28When you add the folder to a dotfiles repository, keep =default-theme.toml= out of it or ignore its changes: orgstar rewrites it whenever its contents differ from the built-in theme. 28When you add the folder to a dotfiles repository, keep =default-theme.toml= out of it or ignore its changes: orgstar rewrites it whenever its contents differ from the built-in theme.
29 29