Keep queued shared captures and unreadable configuration files !454

merged merged by cmc on 2026-11-22 12:26 UTC · krz/orgstar:issue-191-data-loss into main

13 files changed, +365 −61

Layout: unified · split

Sources/OrgApp/AgendaViews.swift +3 −3
@@ -251,11 +251,11 @@ public enum AgendaViewLoader {
251251 guard let table = table(name: name, mode: mode) else {
252252 throw SaveFailure(description: String(localized: "This view can't be saved from here; write it in views.toml."))
253253 }
254 var text = (try? String(contentsOf: userFile, encoding: .utf8)) ?? ""
255 if !text.isEmpty { text += text.hasSuffix("\n") ? "\n" : "\n\n" }
256254 do {
257255 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 }
259259 } catch {
260260 throw SaveFailure(description: error.localizedDescription)
261261 }
Sources/OrgApp/CaptureInbox.swift +14 −4
@@ -36,16 +36,26 @@ public struct CaptureInbox: Sendable {
3636 try Data(link.utf8).write(to: folder.appendingPathComponent(name), options: .atomic)
3737 }
3838
39 /// The waiting links, oldest first, each removed as it's taken.
40 public func take() -> [String] {
39 /// A waiting link and the file that holds it.
40 public struct Link: Sendable, Hashable {
41 public let file: URL
42 public let text: String
43 }
44
45 /// The waiting links, oldest first. Each stays until `remove`; a file that can't be read
46 /// is left out and kept.
47 public func links() -> [Link] {
4148 let names = ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).filter { $0.hasSuffix(".link") }.sorted()
4249 return names.compactMap { name in
4350 let file = folder.appendingPathComponent(name)
44 defer { try? FileManager.default.removeItem(at: file) }
45 return (try? Data(contentsOf: file)).flatMap { String(data: $0, encoding: .utf8) }
51 return (try? Data(contentsOf: file)).flatMap { String(data: $0, encoding: .utf8) }.map { Link(file: file, text: $0) }
4652 }
4753 }
4854
55 public func remove(_ link: Link) {
56 try? FileManager.default.removeItem(at: link.file)
57 }
58
4959 public func setTemplates(_ templates: [Template]) throws {
5060 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
5161 try JSONEncoder().encode(templates).write(to: templatesFile, options: .atomic)
Sources/OrgApp/ConfigSync.swift +41 −10
@@ -24,6 +24,9 @@ public final class ConfigSync {
2424 private let defaults: UserDefaults
2525 @ObservationIgnored private var text: String?
2626 @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?
2730 @ObservationIgnored private var applying = false
2831 @ObservationIgnored private var watcher: FSEventsWatcher?
2932 @ObservationIgnored private var observer: NSObjectProtocol?
@@ -53,15 +56,11 @@ public final class ConfigSync {
5356 if let text {
5457 let migrated = UserConfig.usesLegacyNames(text) ? UserConfig.migratingLegacyNames(text) : text
5558 let completed = UserConfig.addingMissingSections(migrated, from: defaults)
56 if completed != text {
57 try? completed.write(to: target, atomically: true, encoding: .utf8)
58 self.text = completed
59 }
59 if completed != text, write(completed) { self.text = completed }
6060 }
6161 } else {
6262 let template = UserConfig.template(from: defaults)
63 try? template.write(to: target, atomically: true, encoding: .utf8)
64 text = template
63 if write(template) { text = template }
6564 }
6665 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
6766 MainActor.assumeIsolated { self?.writeBack() }
@@ -105,6 +104,8 @@ public final class ConfigSync {
105104 observer = nil
106105 text = nil
107106 configProblems = []
107 themeProblems = []
108 fileProblem = nil
108109 self.url = url
109110 start(watch: watches)
110111 readTheme()
@@ -142,13 +143,40 @@ public final class ConfigSync {
142143 in: url.deletingLastPathComponent()
143144 ) else { return }
144145 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
146165 }
147166
148167 /// Writes settings that differ from the file into it.
149168 func writeBack() {
150169 // 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 }
152180 let values = UserConfig.values(in: current)
153181 let original = current
154182 for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
@@ -164,9 +192,12 @@ public final class ConfigSync {
164192 for template in UserConfig.denoteTemplates(defaults) where values[UserConfig.path(UserConfig.denoteTemplateTable, template.key)] != .string(template.text) {
165193 current = UserConfig.setting(current, section: UserConfig.denoteTemplateTable, key: template.key, to: .string(template.text))
166194 }
167 guard current != original else { return }
195 guard current != original else {
196 fileProblem = nil
197 return updateProblems()
198 }
199 guard write(current) else { return }
168200 text = current
169 try? current.write(to: target, atomically: true, encoding: .utf8)
170201 // A theme picked in Settings; the watcher's reload sees the text unchanged and skips it.
171202 readTheme()
172203 }
Sources/OrgApp/EmacsImport.swift +33 −11
@@ -1134,7 +1134,8 @@ extension EmacsImport {
11341134 /// Applies `items`: settings to `defaults` (and so config.toml), folders to the workspace,
11351135 /// capture templates and key bindings appended to capture.toml and keymap.toml in
11361136 /// `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.
11381139 @MainActor
11391140 /// With `writeConfig`, settings and structure templates are written into `config.toml` too,
11401141 /// for where nothing syncs user defaults into it (iOS). With `chosenFolders`, folders chosen in
@@ -1193,8 +1194,28 @@ extension EmacsImport {
11931194 }
11941195 }
11951196 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 }
11961217 let captureFile = directory.appendingPathComponent("capture.toml")
1197 var capture = (try? String(contentsOf: captureFile, encoding: .utf8)) ?? ""
1218 var capture = read(captureFile)
11981219 let existingKeys = Set((try? TOML.parse(capture))?.compactMap { $0.values["key"]?.string } ?? [])
11991220 var addedCapture = ""
12001221 for item in items {
@@ -1204,10 +1225,10 @@ extension EmacsImport {
12041225 }
12051226 if !addedCapture.isEmpty {
12061227 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 }
12081229 }
12091230 let viewsFile = directory.appendingPathComponent("views.toml")
1210 var viewsText = (try? String(contentsOf: viewsFile, encoding: .utf8)) ?? ""
1231 var viewsText = read(viewsFile)
12111232 var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? [])
12121233 var addedViews = ""
12131234 for item in items {
@@ -1217,10 +1238,10 @@ extension EmacsImport {
12171238 }
12181239 if !addedViews.isEmpty {
12191240 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 }
12211242 }
12221243 let configFile = directory.appendingPathComponent("config.toml")
1223 var config = (try? String(contentsOf: configFile, encoding: .utf8)) ?? ""
1244 var config = read(configFile)
12241245 var projectNames = Set((try? TOML.parse(config))?.filter { $0.name == "publish" }.compactMap { $0.values["name"]?.string } ?? [])
12251246 var addedProjects = ""
12261247 for item in items {
@@ -1230,10 +1251,10 @@ extension EmacsImport {
12301251 }
12311252 if !addedProjects.isEmpty {
12321253 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 }
12341255 }
12351256 let keymapFile = directory.appendingPathComponent("keymap.toml")
1236 var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? ""
1257 var keymap = read(keymapFile)
12371258 func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") }
12381259 var existingBindings = Set((try? TOML.parse(keymap))?.filter { $0.name == "bind" && $0.values["when"] == nil }
12391260 .map { binding($0.values["keys"]?.string, $0.values["command"]?.string, $0.values["mode"]?.string) } ?? [])
@@ -1247,7 +1268,7 @@ extension EmacsImport {
12471268 }
12481269 if !addedKeys.isEmpty {
12491270 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 }
12511272 }
12521273 // Into user defaults, from where ConfigSync writes them into config.toml.
12531274 var rows = UserConfig.structureTemplates(defaults)
@@ -1267,7 +1288,7 @@ extension EmacsImport {
12671288 }
12681289 if noteTemplates > 0 { UserConfig.setDenoteTemplates(notes, in: defaults) }
12691290 if writeConfig, settings + blocks + noteTemplates > 0 {
1270 var text = (try? String(contentsOf: configFile, encoding: .utf8)) ?? ""
1291 var text = read(configFile)
12711292 for setting in stored {
12721293 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults))
12731294 }
@@ -1279,7 +1300,8 @@ extension EmacsImport {
12791300 guard case .denoteTemplate(let key, let template) = item.change else { continue }
12801301 text = UserConfig.setting(text, section: UserConfig.denoteTemplateTable, key: key, to: .string(template))
12811302 }
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) }
12831305 }
12841306 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
12851307 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 {
259259 let panel = NSSavePanel()
260260 panel.nameFieldStringValue = "time-report.org"
261261 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 }
263267 }
264268}
Sources/OrgstarMobile/MobileModel.swift +33 −18
@@ -108,16 +108,17 @@ final class MobileModel {
108108
109109 /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
110110 func setConfigFolder(_ url: URL?) {
111 var problem: String?
111112 if let url {
112113 ConfigFolder.set(url)
113 Self.createConfig(in: url)
114 problem = Self.createConfig(in: url)
114115 } else {
115116 ConfigFolder.clear()
116117 // What the folder set no longer applies.
117118 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
118119 }
119120 configFolder = url
120 reloadConfig()
121 _ = reloadConfig(after: problem)
121122 watchConfig()
122123 }
123124
@@ -168,27 +169,38 @@ final class MobileModel {
168169 configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
169170 }
170171
171 /// Writes the folder's `config.toml` and applies it.
172 func saveConfig(_ text: String) {
173 guard let configFolder else { return }
174 var error: NSError?
175 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: configFolder.appendingPathComponent("config.toml"), options: [], error: &error) { url in
176 try? text.write(to: url, atomically: true, encoding: .utf8)
172 /// Writes the folder's `config.toml` and applies it. False, with the reason first in
173 /// `configProblems`, when the file can't be written or what it holds can't be read.
174 @discardableResult
175 func saveConfig(_ text: String) -> Bool {
176 guard let configFolder else { return false }
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)"
177187 }
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 {
178192 reloadConfig()
193 if let problem { configProblems.insert(problem, at: 0) }
194 return problem == nil
179195 }
180196
181197 /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
182198 /// the Mac's Settings write it, else in this device's settings.
183199 func set(_ defaultsKey: String, to value: TOML.Value) {
184200 guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
201 var problem: String?
185202 if let configFolder {
186 let file = configFolder.appendingPathComponent("config.toml")
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 }
203 problem = Self.updateConfig(in: configFolder) { UserConfig.setting($0, section: setting.section, key: setting.key, to: value) }
192204 } else {
193205 switch value {
194206 case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
@@ -196,7 +208,7 @@ final class MobileModel {
196208 case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
197209 }
198210 }
199 reloadConfig()
211 _ = reloadConfig(after: problem)
200212 }
201213
202214 /// The capture templates, for the share extension to offer.
@@ -218,14 +230,17 @@ final class MobileModel {
218230
219231 /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
220232 /// colors.
221 /// Writes `config.toml` with every setting at its default when the folder has none.
222 private static func createConfig(in folder: URL) {
233 /// Writes `config.toml` with every setting at its default when the folder has none; returns
234 /// the problem when it can't be written.
235 private static func createConfig(in folder: URL) -> String? {
223236 let file = folder.appendingPathComponent("config.toml")
224237 var error: NSError?
238 var failure: Error?
225239 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
226240 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 }
228242 }
243 return (error ?? failure).map { "config.toml wasn't created: \($0.localizedDescription)" }
229244 }
230245
231246 private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
Sources/OrgstarMobile/OrgstarMobileApp.swift +27 −6
@@ -120,8 +120,9 @@ struct RootView: View {
120120 let workspace: WorkspaceModel
121121 let agenda: AgendaModel
122122 @State private var capture: CaptureRequest?
123 /// Captures from the share extension after the one showing.
124 @State private var waiting: [CaptureRequest] = []
123 /// The share extension's link whose capture sheet is showing, with its request's id. The link
124 /// stays in the inbox until the sheet is dismissed.
125 @State private var shared: (link: CaptureInbox.Link, request: UUID)?
125126 /// Files from the share extension, waiting for the entry to attach them to.
126127 @State private var sharedFiles: SharedFiles?
127128 @State private var tab = AppTab.agenda
@@ -290,7 +291,11 @@ struct RootView: View {
290291 capture = request
291292 }
292293
293 .sheet(item: $capture, onDismiss: showWaiting) { request in
294 // Another capture took the sheet from a shared one, which stays in the inbox for later.
295 .onChange(of: capture?.id) { _, id in
296 if let id, id != shared?.request { shared = nil }
297 }
298 .sheet(item: $capture, onDismiss: captureDismissed) { request in
294299 CaptureScreen(workspace: workspace, session: session, request: request)
295300 }
296301 .sheet(item: $sharedFiles) { shared in
@@ -371,13 +376,29 @@ struct RootView: View {
371376
372377 /// What the share extension left, one capture sheet at a time.
373378 private func takeShared() {
374 waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
375 if capture == nil { showWaiting() }
379 showWaiting()
376380 if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
377381 }
378382
383 /// The inbox's oldest capture, unless a capture sheet is showing or being dismissed.
379384 private func showWaiting() {
380 if !waiting.isEmpty { capture = waiting.removeFirst() }
385 guard capture == nil, shared == nil, let inbox = model.inbox else { return }
386 for link in inbox.links() {
387 guard let request = CaptureRequest(link: link.text) else {
388 inbox.remove(link)
389 continue
390 }
391 shared = (link, request.id)
392 capture = request
393 return
394 }
395 }
396
397 /// The shared capture was saved or discarded, so its link goes; then the next one shows.
398 private func captureDismissed() {
399 if let shared { model.inbox?.remove(shared.link) }
400 shared = nil
401 showWaiting()
381402 }
382403
383404 /// A widget's or the Live Activity's link.
Sources/OrgstarMobile/SettingsScreen.swift +1 −2
@@ -362,8 +362,7 @@ struct ConfigFileEditor: View {
362362
363363 private func save() {
364364 guard text != saved else { return }
365 model.saveConfig(text)
366 saved = text
365 if model.saveConfig(text) { saved = text }
367366 }
368367}
369368
Tests/OrgAppTests/CaptureInboxTests.swift +23 −4
@@ -5,14 +5,33 @@ import Testing
55@testable import OrgApp
66
77struct CaptureInboxTests {
8 @Test func takesLinksOldestFirstOnce() throws {
8 @Test func keepsLinksOldestFirstUntilRemoved() throws {
99 let folder = try Folder()
1010 let inbox = CaptureInbox(folder: folder.url.appendingPathComponent("Captures"))
11 #expect(inbox.take() == [])
11 #expect(inbox.links() == [])
1212 try inbox.add("org-protocol://capture?body=one")
1313 try inbox.add("org-protocol://capture?body=two")
14 #expect(inbox.take() == ["org-protocol://capture?body=one", "org-protocol://capture?body=two"])
15 #expect(inbox.take() == [])
14 let links = inbox.links()
15 #expect(links.map(\.text) == ["org-protocol://capture?body=one", "org-protocol://capture?body=two"])
16 // Another instance, as after the app was ended with both queued.
17 #expect(CaptureInbox(folder: inbox.folder).links() == links)
18 inbox.remove(links[0])
19 #expect(inbox.links().map(\.text) == ["org-protocol://capture?body=two"])
20 inbox.remove(links[1])
21 #expect(inbox.links() == [])
22 }
23
24 @Test func keepsALinkItCannotRead() throws {
25 let folder = try Folder()
26 let inbox = CaptureInbox(folder: folder.url.appendingPathComponent("Captures"))
27 try inbox.add("org-protocol://capture?body=one")
28 let notText = inbox.folder.appendingPathComponent("0-not-text.link")
29 try Data([0xFF, 0xFE, 0xFD]).write(to: notText)
30 let directory = inbox.folder.appendingPathComponent("1-directory.link")
31 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
32 #expect(inbox.links().map(\.text) == ["org-protocol://capture?body=one"])
33 #expect(FileManager.default.fileExists(atPath: notText.path))
34 #expect(FileManager.default.fileExists(atPath: directory.path))
1635 }
1736
1837 @Test func keepsTheTemplateList() throws {
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/08-capture.org +1 −1
@@ -353,7 +353,7 @@ In another app, share a web page or text and choose orgstar. The share form has:
353353- for a link, its title (editable) and address;
354354- a Text field, filled with shared text.
355355
356Capture saves the item in the app group's capture inbox. The next time you open orgstar, it opens the capture sheet with the item as an org-protocol capture: the link becomes =%a= and =%:link=, the title =%:description=, and the text =%i=. Several waiting items open one after another, oldest first. If the extension says orgstar's shared folder isn't available, the app group is missing from the build and nothing can be saved.
356Capture saves the item in the app group's capture inbox. The next time you open orgstar, it opens the capture sheet with the item as an org-protocol capture: the link becomes =%a= and =%:link=, the title =%:description=, and the text =%i=. Several waiting items open one after another, oldest first. An item stays in the inbox until its sheet is saved or cancelled, so items still waiting when orgstar is ended open the next time. If the extension says orgstar's shared folder isn't available, the app group is missing from the build and nothing can be saved.
357357
358358The share form lists no templates until orgstar has run once with your configuration folder; the capture sheet then starts on the first template.
359359
docs/manual/guide/13-configuration.org +1 −1
@@ -23,7 +23,7 @@ The folder holds these files:
2323| =views.toml= | Saved agenda views | No |
2424| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch |
2525
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.
2727
2828When 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.
2929