Sources/OrgApp/UserCommandWorkspace.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgApp/UserCommandWorkspace.swift

227 lines · 12915 bytes

12 symbols in this file
  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import OrgIndex
  5
  6/// The calls a user command with `workspace = true` makes beyond its buffer: `org.search`,
  7/// `org.outlineOf`, `org.agenda` and `org.capture`. Reads never return text that is encrypted
  8/// on disk: `.gpg` files are refused or left out, buffers holding decrypted entries are read
  9/// from disk, and a search match in an encrypted entry has no snippet.
 10@MainActor
 11public struct UserCommandWorkspace {
 12    public let workspace: WorkspaceModel
 13    public let clock: ClockModel
 14    public var templates: () -> [CaptureTemplate] = { CaptureTemplates.load().templates }
 15    /// `%n` in capture templates.
 16    public var userName = ""
 17    public var now: () -> Date = Date.init
 18    public var calendar = Calendar.current
 19
 20    /// The calls, by name, that need `workspace = true`.
 21    public static let calls: Set<String> = ["search", "outlineOf", "agenda", "capture"]
 22    /// The most `org.search` returns.
 23    public static let searchLimit = 50
 24    /// The most `org.agenda` returns, as many as the x-callback-url `agenda` action may.
 25    public static let agendaLimit = XCallbackRunner.maximumLimit
 26    /// The longest span `org.agenda` covers.
 27    public static let maximumDays = 366
 28
 29    public init(workspace: WorkspaceModel, clock: ClockModel) {
 30        self.workspace = workspace
 31        self.clock = clock
 32    }
 33
 34    public struct Failure: Error, Equatable {
 35        public let message: String
 36        init(_ message: String) { self.message = message }
 37    }
 38
 39    /// The answer to `name`, one of `calls`, for a command running in `path`'s buffer.
 40    func answer(_ name: String, _ value: Any, session: DocumentSession, path: String) async throws(Failure) -> Any {
 41        switch name {
 42        case "search": return try await search(value, session: session)
 43        case "outlineOf": return try await outline(value, session: session)
 44        case "agenda": return try await agenda(value, session: session)
 45        case "capture": return try capture(value, session: session, path: path)
 46        default: throw Failure("No call \(name).")
 47        }
 48    }
 49
 50    // MARK: - Search
 51
 52    /// `{file, title, outline, start, heading, snippet}` for each match, best first: `outline`
 53    /// is the titles of the headings above it, `heading` false for a match in the text before
 54    /// a file's first heading (then `title` is the file's), `snippet` the text around the match
 55    /// or null.
 56    func search(_ value: Any, session: DocumentSession) async throws(Failure) -> Any {
 57        guard let query = value as? String else { throw Failure("org.search needs a query string.") }
 58        // Unsaved buffers are searched as they are, except those holding decrypted entries,
 59        // which are searched as they are on disk.
 60        let shown = session.openTexts
 61        let overlay = workspace.overlay(session.openDocuments.filter { shown[$0.path] != nil })
 62        let index = workspace.index
 63        let roots = workspace.rootPaths
 64        let limit = Self.searchLimit
 65        let found: [Match]
 66        do {
 67            found = try await Task.detached {
 68                try index.search(query, overlay: overlay, limit: limit).compactMap { location -> Match? in
 69                    guard !CryptVault.isEncryptedFile(location.path) else { return nil }
 70                    let body = try? index.text(of: location, overlay: overlay)
 71                    let encrypted = body?.contains("-----BEGIN PGP MESSAGE-----") == true
 72                    return Match(file: UserCommandFile.relativePath(location.path, roots: roots), title: location.title,
 73                                 outline: Array(location.outlinePath.dropLast()), start: location.start,
 74                                 heading: location.ordinal != HeadingLocation.fileOrdinal,
 75                                 snippet: encrypted ? nil : location.snippet?.text)
 76                }
 77            }.value
 78        } catch {
 79            throw Failure("Can't read the index: \(error.localizedDescription)")
 80        }
 81        return found.map { match -> [String: Any] in
 82            ["file": match.file, "title": match.title, "outline": match.outline, "start": match.start, "heading": match.heading,
 83             "snippet": match.snippet ?? NSNull()]
 84        }
 85    }
 86
 87    struct Match: Sendable {
 88        let file: String
 89        let title: String
 90        let outline: [String]
 91        let start: Int
 92        let heading: Bool
 93        let snippet: String?
 94    }
 95
 96    // MARK: - Outline of another file
 97
 98    /// The headings of an org file in the folders, as `org.outline()` gives them: a path
 99    /// relative to a folder or absolute inside one, after symlinks are resolved.
100    func outline(_ value: Any, session: DocumentSession) async throws(Failure) -> Any {
101        guard let given = value as? String, !given.isEmpty else { throw Failure("org.outlineOf needs a path.") }
102        guard let path = Self.resolve(given, roots: workspace.rootPaths) else { throw Failure("No file \(given) in orgstar's folders.") }
103        guard !CryptVault.isEncryptedFile(path) else { throw Failure("\(given) is encrypted, so user commands can't read it.") }
104        guard path.hasSuffix(".org") || path.hasSuffix(".org_archive") else { throw Failure("\(given) isn't an org file.") }
105        let context: EditContext
106        if session.refusesUserCommand(path) == nil, let document = session.document(of: path) {
107            context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [0..<0])
108        } else {
109            // Not open, or holding decrypted entries: what's on disk.
110            let defaults = session.defaults
111            guard let read = await Task.detached(operation: { () -> EditContext? in
112                guard let data = FileManager.default.contents(atPath: path) else { return nil }
113                let text = SourceText(bytes: [UInt8](data)).text
114                return EditContext(revision: 0, text: text, tree: OrgParser.parse(text, defaults: defaults), selection: [0..<0])
115            }).value else { throw Failure("Can't read \(given).") }
116            context = read
117        }
118        return UserCommandAPI.answer("outline", NSNull(), context: context, file: nil) ?? []
119    }
120
121    /// `given` relative to the first folder that has it, or absolute (or `~/…`) inside one,
122    /// when it is a file whose real path, symlinks resolved, is inside that folder's.
123    nonisolated static func resolve(_ given: String, roots: [String]) -> String? {
124        func real(_ path: String) -> String? {
125            realpath(path, nil).map { defer { free($0) }; return String(cString: $0) }
126        }
127        let candidates = given.hasPrefix("/") || given.hasPrefix("~")
128            ? [(OrgPaths.expandingTilde(given) as NSString).standardizingPath]
129            : roots.map { ((($0 as NSString).appendingPathComponent(given)) as NSString).standardizingPath }
130        for candidate in candidates {
131            guard let file = real(candidate) else { continue }
132            var directory: ObjCBool = false
133            guard FileManager.default.fileExists(atPath: file, isDirectory: &directory), !directory.boolValue else { continue }
134            let inside = roots.contains { root in
135                guard let root = real(root) else { return false }
136                return file.hasPrefix(root.hasSuffix("/") ? root : root + "/")
137            }
138            if inside { return candidate }
139        }
140        return nil
141    }
142
143    // MARK: - Agenda
144
145    /// The agenda's entries from `from` to `to` (`YYYY-MM-DD`, both included; today and `from`
146    /// when not given), in the shape of the x-callback-url `agenda` action's.
147    func agenda(_ value: Any, session: DocumentSession) async throws(Failure) -> Any {
148        let options = value as? [String: Any] ?? [:]
149        let today = Days.absolute(now(), calendar: calendar)
150        func day(_ key: String) throws(Failure) -> Int? {
151            guard let raw = options[key], !(raw is NSNull) else { return nil }
152            guard let text = raw as? String, let day = Self.day(text) else { throw Failure("org.agenda: \(key) must be a date as YYYY-MM-DD.") }
153            return day
154        }
155        let from = try day("from") ?? today
156        let to = try day("to") ?? from
157        guard to >= from else { throw Failure("org.agenda: to is before from.") }
158        guard to - from < Self.maximumDays else { throw Failure("org.agenda: a span of at most \(Self.maximumDays) days.") }
159        let model = AgendaModel(workspace: workspace)
160        XCallbackRunner.configure(model)
161        model.mode = .agenda(span: to - from + 1, startOffset: nil)
162        model.start = from
163        model.startOnWeekday = nil
164        await model.refresh(open: session.openTexts, now: now(), calendar: calendar)
165        let roots = workspace.rootPaths
166        let entries = XCallbackRunner.entries(model, calendar: calendar) { UserCommandFile.relativePath($0, roots: roots) }
167            .filter { $0.file.map { !CryptVault.isEncryptedFile($0) } ?? true }
168        let encoder = JSONEncoder()
169        guard let data = try? encoder.encode(Array(entries.prefix(Self.agendaLimit))),
170              let json = try? JSONSerialization.jsonObject(with: data) else { return [Any]() }
171        return json
172    }
173
174    /// The day `YYYY-MM-DD` names, as `Days` numbers it.
175    nonisolated static func day(_ text: String) -> Int? {
176        let parts = text.split(separator: "-", omittingEmptySubsequences: false)
177        guard parts.count == 3, parts[0].count == 4, parts[1].count == 2, parts[2].count == 2,
178              let year = Int(parts[0]), let month = Int(parts[1]), let day = Int(parts[2]),
179              (1...12).contains(month), (1...31).contains(day) else { return nil }
180        let absolute = Days.absolute(year: year, month: month, day: day)
181        let back = Days.date(absolute)
182        return back.month == month && back.day == day ? absolute : nil
183    }
184
185    // MARK: - Capture
186
187    /// Files `text` with the template keyed `template`, without the capture window, as the
188    /// x-callback-url `capture` action does: every prompt of the template must have an answer
189    /// in `fields`, by its prompt text, or nothing is filed. `{template, file}` with the file
190    /// relative to its folder.
191    func capture(_ value: Any, session: DocumentSession, path: String) throws(Failure) -> Any {
192        let options = value as? [String: Any] ?? [:]
193        guard let key = options["template"] as? String, !key.isEmpty else { throw Failure("org.capture needs a template key.") }
194        guard let text = options["text"] as? String else { throw Failure("org.capture needs the text to capture.") }
195        var fields: [String: String] = [:]
196        if let raw = options["fields"], !(raw is NSNull) {
197            guard let given = raw as? [String: Any] else { throw Failure("org.capture: fields must be an object of strings.") }
198            for (name, answer) in given {
199                guard let answer = answer as? String else { throw Failure("org.capture: field \(name) must be a string.") }
200                fields[name] = answer
201            }
202        }
203        let templates = templates()
204        guard let template = templates.first(where: { $0.key == key }) else { throw Failure("No capture template \"\(key)\".") }
205        if template.options.denote || template.asksTreeDate {
206            throw Failure("Template \"\(key)\" makes a Denote note or asks for a date tree's day, which needs the capture window.")
207        }
208        let missing = XCallbackRunner.unanswered(template, text: text, properties: [:], given: Set(fields.keys))
209        guard missing.isEmpty else {
210            throw Failure("Template \"\(key)\" asks for \(missing.joined(separator: ", ")); give \(missing.count == 1 ? "it" : "them") in fields.")
211        }
212        let target: String
213        switch template.resolved(workspace: workspace, session: session, clock: clock) {
214        case .failure(let error): throw Failure(error.message)
215        case .success(let resolved): target = resolved.file ?? DocumentSession.resolve(resolved.template.target.file, root: workspace.rootPaths.first)
216        }
217        // Its own buffer changes only through the edits the command returns, as one undo step.
218        let real = { (path: String) in URL(fileURLWithPath: path).resolvingSymlinksInPath().path }
219        guard real(target) != real(path) else { throw Failure("org.capture can't file to the file the command runs in; return edits instead.") }
220        switch session.capture(text, templateKey: key, templates: [template], workspace: workspace, clock: clock,
221                               clipboard: "", userName: userName, answers: fields) {
222        case .failure(let error): throw Failure(error.message)
223        case .success(let placed):
224            return ["template": key, "file": UserCommandFile.relativePath(placed.path, roots: workspace.rootPaths)]
225        }
226    }
227}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form