Sources/OrgstarCLI/CaptureCommand.swift
112 lines · 6279 bytes
2 symbols in this file
1import Foundation
2import OrgConfig
3import OrgCore
4
5/// `orgstar capture <key> [text]`: a template of capture.toml filled and filed at once, as
6/// Shortcuts' Capture to Orgstar does.
7@MainActor
8enum CaptureCommand {
9 static let help = """
10 Usage: orgstar capture <key> [<text>] [--set <prompt>=<value>]...
11
12 Files an entry with the capture template <key> of capture.toml, without the capture window.
13 The text is %i: the argument, or standard input when there is none.
14
15 A template's %^{Prompt} questions take their answers from --set Prompt=value, or their default
16 (%^{Prompt|default}). A question with neither stops the capture, naming what to set. %^g and
17 %^G add no tags, %^t and the other dates are today, unless set (--set Tags=work:urgent,
18 --set Date=+2d). %a, %c, %x and %f are empty.
19
20 Options:
21 --set <prompt>=<value> answer a question; may be repeated
22 """
23
24 static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
25 let arguments = try Arguments(words, command: "capture", flags: [], options: ["--set"])
26 try arguments.expect(1, 2, "capture")
27 let key = arguments.positional[0]
28 var answers: [String: String] = [:]
29 for pair in arguments.options["--set"] ?? [] {
30 guard let equals = pair.firstIndex(of: "=") else { throw Failure(.usage, "capture: --set takes prompt=value, not \(pair)") }
31 answers[String(pair[..<equals])] = String(pair[pair.index(after: equals)...])
32 }
33 let (templates, _, problems) = CaptureTemplates.load(userFile: workspace.configFile("capture.toml"))
34 for problem in problems { workspace.host.error("orgstar: \(problem)\n") }
35 guard let template = templates.first(where: { $0.key == key }) else {
36 throw Failure(.notFound, "No capture template \"\(key)\". Templates: " + templates.map { "\($0.key) (\($0.name))" }.joined(separator: ", "))
37 }
38 if template.options.denote { throw Failure(.refused, "Template \"\(key)\" makes a Denote note; capture with it in orgstar.") }
39 var initial = arguments.positional.count > 1 ? arguments.positional[1] : workspace.host.input() ?? ""
40 if initial.hasSuffix("\n") { initial.removeLast() }
41
42 let running = ClockCommand.running(workspace)
43 var context = CaptureContext(
44 now: workspace.host.now, calendar: workspace.host.calendar, initial: initial, userName: NSFullUserName(),
45 clockHeading: running?.title ?? "", clockLink: running.map { "[[file:\($0.path)::*\($0.title)][\($0.title)]]" } ?? "",
46 tagsColumn: workspace.options.tagsColumn
47 )
48 context.readsTemplateFiles(from: workspace.configDirectory)
49 let questions = Capture.questions(template.template, context: context)
50 var replies: [String] = []
51 var missing: [String] = []
52 for question in questions {
53 if let answer = answers[question.prompt] {
54 replies.append(answer)
55 continue
56 }
57 switch question.kind {
58 case .text, .property:
59 if question.defaultValue.isEmpty { missing.append(question.prompt) }
60 replies.append(question.defaultValue)
61 case .tags, .date, .clipboard:
62 replies.append("")
63 }
64 }
65 if !missing.isEmpty {
66 let names = missing.map { "\"\($0)\"" }.joined(separator: ", ")
67 throw Failure(.refused, "Template \"\(key)\" asks \(names). Answer with --set, as: --set '\(missing[0])=…'")
68 }
69 guard case .success(let filled) = Capture.fill(template.template, context: context, answers: replies) else {
70 throw Failure(.failure, "Can't fill template \"\(key)\"")
71 }
72
73 var chosen = template
74 let path: String
75 switch template.target {
76 case .id(let id):
77 path = try workspace.target("id:" + id).path
78 case .clock:
79 guard let running else { throw Failure(.notFound, "Template \"\(key)\" files under the running clock, and no clock runs.") }
80 let text = try workspace.text(running.path)
81 let line = (text as NSString).range(of: "CLOCK: [\(running.start)]").location
82 guard let heading = workspace.headings(text, path: running.path).last(where: { $0.headingRange.lowerBound <= line }) else {
83 throw Failure(.notFound, "The running clock's heading wasn't found.")
84 }
85 chosen = template.retargeted(.heading(file: running.path, offset: heading.headingRange.lowerBound))
86 path = running.path
87 default:
88 path = CaptureTemplates.path(template.target.file, root: workspace.roots.first)
89 }
90 if !FileManager.default.fileExists(atPath: path) {
91 do {
92 try FileManager.default.createDirectory(at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true)
93 try Data().write(to: URL(fileURLWithPath: path))
94 } catch {
95 throw Failure(.failure, "Can't create \(path): \(error.localizedDescription)")
96 }
97 }
98 let (result, text) = try workspace.perform(CapturePlacement(text: filled.text, template: chosen), path: path, at: 0)
99 let offset = result.selection?.first?.lowerBound ?? 0
100 workspace.host.print("Captured to \(path):\(Workspace.line(of: offset, in: text))")
101 // A template's clock-in, kept running: the capture is filed at once, so without
102 // clock-keep the clock would stop as it starts.
103 let headings = workspace.headings(text, path: path)
104 if template.options.clockIn, template.options.clockKeep, let index = headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) {
105 let entry = ClockTask(path: path, title: headings[index].title, ordinal: index, id: headings[index].id)
106 try ClockCommand.clockIn(workspace) { () throws(Failure) in
107 guard let start = entry.locate(in: try workspace.text(path)) else { throw Failure(.notFound, "The captured entry wasn't found.") }
108 return Workspace.Target(path: path, offset: start, title: entry.title)
109 }
110 }
111 }
112}