Sources/OrgstarCLI/Workspace.swift
247 lines · 12028 bytes
15 symbols in this file
1import Foundation
2import OrgConfig
3import OrgCore
4import OrgDocument
5import OrgIndex
6import OrgWorkspace
7
8/// Settings held in memory: config.toml is applied to them as the app applies it to its user
9/// defaults, and no defaults domain is written.
10final class MemoryDefaults: UserDefaults, @unchecked Sendable {
11 private var values: [String: Any] = [:]
12
13 convenience init() {
14 self.init(suiteName: nil)!
15 }
16
17 override func object(forKey defaultName: String) -> Any? { values[defaultName] }
18 override func set(_ value: Any?, forKey defaultName: String) { values[defaultName] = value }
19 override func removeObject(forKey defaultName: String) { values[defaultName] = nil }
20}
21
22/// The app's configuration and folders as the tool finds them: the configuration folder, the
23/// data folder (the folder list, the running clock, recovery versions), the settings of
24/// config.toml, and the files of the folders.
25@MainActor
26final class Workspace {
27 let host: Host
28 let configDirectory: URL
29 let dataDirectory: URL
30 let defaults = MemoryDefaults()
31 let settings: OrgSettings
32 let options: EditingOptions
33 /// The folders, by path, sorted as the app sorts them.
34 let roots: [String]
35 private var scanned: [(path: String, relative: String, kind: FileKind)]?
36
37 init(host: Host) {
38 self.host = host
39 let environment = host.environment
40 configDirectory = UserConfig.defaultDirectory(environment: environment, home: NSHomeDirectory(), sandboxed: false)
41 dataDirectory = environment["ORGSTAR_DATA_DIR"].map { URL(fileURLWithPath: $0) }
42 ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
43 var roots: Set<String> = []
44 if let data = try? Data(contentsOf: dataDirectory.appendingPathComponent("roots.json")),
45 let saved = try? JSONDecoder().decode([WorkspaceRoot].self, from: data) {
46 for root in saved {
47 if let url = try? root.resolve(sandboxed: false).url { roots.insert(url.standardizedFileURL.path) }
48 }
49 }
50 if let root = environment["ORGSTAR_ROOT"] { roots.insert(host.absolute(root)) }
51 self.roots = roots.sorted()
52 if let text = try? String(contentsOf: Self.configFile("config.toml", in: configDirectory, environment: environment), encoding: .utf8) {
53 for problem in UserConfig.apply(text, to: defaults) { host.error("orgstar: \(problem)\n") }
54 }
55 settings = OrgPreferences.orgSettings(defaults)
56 options = OrgPreferences.options(defaults)
57 }
58
59 /// A file of the configuration folder; without a folder from the environment, one that
60 /// exists only where earlier versions kept it is read from there, as the app does.
61 func configFile(_ name: String) -> URL {
62 Self.configFile(name, in: configDirectory, environment: host.environment)
63 }
64
65 private static func configFile(_ name: String, in directory: URL, environment: [String: String]) -> URL {
66 let url = directory.appendingPathComponent(name)
67 guard environment["ORGSTAR_CONFIG_DIR"] == nil, environment["ORGSTAR_DATA_DIR"] == nil else { return url }
68 let legacy = UserConfig.legacyDirectory.appendingPathComponent(name)
69 let manager = FileManager.default
70 if !manager.fileExists(atPath: url.path), manager.fileExists(atPath: legacy.path) { return legacy }
71 return url
72 }
73
74 // MARK: - Files
75
76 /// The folders' files, as the app lists them with Settings ▸ General's hidden-file and
77 /// ignored-folder settings.
78 var files: [(path: String, relative: String, kind: FileKind)] {
79 if let scanned { return scanned }
80 let rules = ScanRules(
81 hiddenFiles: OrgPreferences.bool("showHiddenFiles", defaults),
82 ignoredFolders: Set(OrgPreferences.string("ignoredFolders", defaults).split(separator: " ").map(String.init))
83 )
84 var found: [(path: String, relative: String, kind: FileKind)] = []
85 for root in roots {
86 guard let discovery = try? WorkspaceScanner.scan(URL(fileURLWithPath: root), rules: rules) else { continue }
87 let base = URL(fileURLWithPath: root).resolvingSymlinksInPath().path + "/"
88 for file in discovery.files {
89 let path = file.url.path
90 let resolved = file.url.resolvingSymlinksInPath().path
91 let relative = resolved.hasPrefix(base) ? String(resolved.dropFirst(base.count)) : file.url.lastPathComponent
92 found.append((path, relative, file.kind))
93 }
94 }
95 scanned = found
96 return found
97 }
98
99 /// `(org-agenda-files)`: `org-agenda-files` resolved, or when it is empty the org files at
100 /// the top of each folder, or below it with `agenda-include-subfolders`.
101 var agendaFiles: [String] {
102 let list = OrgPreferences.agendaFiles(defaults)
103 if !list.isEmpty { return AgendaFiles.resolve(list, base: roots.first) }
104 let subfolders = OrgPreferences.agendaSubfolders(defaults)
105 return files
106 .filter { $0.kind == .org && !($0.path as NSString).lastPathComponent.hasPrefix(".") && (subfolders || !$0.relative.contains("/")) }
107 .map(\.path)
108 .sorted()
109 }
110
111 /// The text of the file at `path`.
112 func text(_ path: String) throws(Failure) -> String {
113 guard let data = FileManager.default.contents(atPath: path) else {
114 let name = (path as NSString).lastPathComponent
115 if FileManager.default.fileExists(atPath: path) { throw Failure(.failure, "Can't read \(name)") }
116 throw Failure(.notFound, "No such file: \(path)")
117 }
118 return SourceText(bytes: [UInt8](data)).text
119 }
120
121 /// The settings for `text`, the file at `path`, with its setup files.
122 func settings(for text: String, path: String) -> OrgSettings {
123 settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
124 }
125
126 // MARK: - Changing files
127
128 /// Runs `command` at `offset` in the file at `path` and writes the file as the app saves a
129 /// file that isn't open: through a temporary file, merged with a change made meanwhile,
130 /// the versions it replaces kept in the recovery folder as the app keeps them. The
131 /// command's result and the text after it.
132 @discardableResult
133 func perform(_ command: any OrgCommand, path: String, at offset: Int) throws(Failure) -> (result: EditResult, text: String) {
134 let url = URL(fileURLWithPath: path)
135 let name = url.lastPathComponent
136 guard !path.hasSuffix(".gpg") else { throw Failure(.refused, "\(name) is encrypted; change it in orgstar.") }
137 let fileSystem = CoordinatedFileSystem(writesInPlaceWhenDenied: false)
138 let bytes: [UInt8]
139 do {
140 guard let read = try fileSystem.read(url) else { throw Failure(.notFound, "No such file: \(path)") }
141 bytes = read
142 } catch let failure as Failure {
143 throw failure
144 } catch {
145 throw Failure(.failure, "Can't read \(name): \(error.localizedDescription)")
146 }
147 var state = DocumentState(bytes: bytes, defaults: settings(for: SourceText(bytes: bytes).text, path: path))
148 guard state.isEditable else { throw Failure(.refused, "\(name) isn't UTF-8, so it can't be changed.") }
149 let step: CommandStep
150 do {
151 step = try state.run(command, selection: [offset..<offset], now: host.now, calendar: host.calendar, options: options)
152 } catch {
153 throw Failure(.failure, "Can't change \(name): \(error)")
154 }
155 switch step {
156 case .commit(let result):
157 if state.isDirty { try save(&state, to: url) }
158 return (result, state.text)
159 case .failed(let message):
160 throw Failure(.failure, message)
161 case .prompt(let prompt):
162 throw Failure(.refused, "\(name): this needs an answer to \"\(prompt.message)\"; do it in orgstar.")
163 case .external:
164 throw Failure(.refused, "\(name): this needs a program orgstar runs; do it in orgstar.")
165 }
166 }
167
168 private func save(_ state: inout DocumentState, to url: URL) throws(Failure) {
169 let name = url.lastPathComponent
170 let saver = Saver(fileSystem: CoordinatedFileSystem(writesInPlaceWhenDenied: false),
171 recovery: FileRecoveryStore(directory: dataDirectory.appendingPathComponent("Recovery")))
172 do {
173 switch try saver.save(&state, to: url) {
174 case .saved, .mergedAndSaved:
175 break
176 case .conflict:
177 throw Failure(.failure, "\(name) changed on disk; nothing was changed.")
178 case .overwroteExternalChange, .changedAfterWrite:
179 host.error("orgstar: \(name) changed while it was written; the other version is kept in History.\n")
180 }
181 } catch let failure as Failure {
182 throw failure
183 } catch {
184 throw Failure(.failure, "Can't write \(name): \(error.localizedDescription)")
185 }
186 }
187
188 // MARK: - Headings
189
190 /// A heading or a whole file named on the command line.
191 struct Target {
192 let path: String
193 /// The heading's start; nil for the whole file.
194 let offset: Int?
195 let title: String?
196 }
197
198 /// `file`, `file::Heading`, `file::*Heading`, `file::#custom-id`, `file::id:ID` or `id:ID`.
199 func target(_ spec: String) throws(Failure) -> Target {
200 if spec.hasPrefix("id:"), !spec.contains("::") {
201 let id = String(spec.dropFirst(3))
202 for path in Array(Set(files.filter { $0.kind == .org }.map(\.path) + agendaFiles)).sorted() {
203 guard let text = try? text(path), text.contains(id),
204 let heading = headings(text, path: path).first(where: { $0.id == id }) else { continue }
205 return Target(path: path, offset: heading.headingRange.lowerBound, title: heading.title)
206 }
207 throw Failure(.notFound, "No heading with ID \(id)")
208 }
209 let parts = spec.components(separatedBy: "::")
210 let path = host.absolute(parts[0])
211 let text = try text(path)
212 guard parts.count > 1 else { return Target(path: path, offset: nil, title: nil) }
213 let search = parts.dropFirst().joined(separator: "::")
214 let all = headings(text, path: path)
215 let found: HeadingInfo?
216 if search.hasPrefix("id:") {
217 found = all.first { $0.id == String(search.dropFirst(3)) }
218 } else if search.hasPrefix("#") {
219 let custom = String(search.dropFirst())
220 found = all.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == custom } }
221 } else {
222 let title = search.hasPrefix("*") ? String(search.dropFirst()) : search
223 found = all.first { $0.title == title } ?? all.first { $0.title.caseInsensitiveCompare(title) == .orderedSame }
224 }
225 guard let found else { throw Failure(.notFound, "No heading \(search) in \((path as NSString).lastPathComponent)") }
226 return Target(path: path, offset: found.headingRange.lowerBound, title: found.title)
227 }
228
229 func headings(_ text: String, path: String) -> [HeadingInfo] {
230 DocumentModel(tree: OrgParser.parse(text, defaults: settings(for: text, path: path))).headings
231 }
232
233 /// The 1-based line of `offset`, a UTF-16 offset in `text`.
234 static func line(of offset: Int, in text: String) -> Int {
235 let ns = text as NSString
236 var line = 1
237 var index = 0
238 let end = min(offset, ns.length)
239 while index < end {
240 let found = ns.range(of: "\n", options: [], range: NSRange(location: index, length: end - index))
241 guard found.location != NSNotFound else { break }
242 line += 1
243 index = found.location + 1
244 }
245 return line
246 }
247}