Sources/OrgstarCLI/ClockCommand.swift
148 lines · 7690 bytes
13 symbols in this file
1import Foundation
2import OrgCore
3
4/// `orgstar clock in|out|status`. The running clock is the open `CLOCK:` line in the files, as
5/// in Emacs: the tool changes only the org file, and the app, which watches its folders, takes
6/// a clock started or stopped here as the running one. The app's own record (`clock.json` in
7/// the data folder) is read, never written, so the two never write the same file.
8@MainActor
9enum ClockCommand {
10 static let help = """
11 Usage: orgstar clock in <file>::<heading>
12 orgstar clock in <file>::id:<id> | id:<id>
13 orgstar clock out
14 orgstar clock status [--json]
15
16 Starts and stops the clock as Org does: clock in writes a CLOCK line under the heading,
17 stopping the running clock first; clock out closes the running clock's line. The heading is
18 its title (with or without a leading *), #custom-id or id:ID.
19
20 The running clock is the one orgstar shows, else the most recently started open CLOCK line in
21 the agenda files. orgstar picks up a clock started or stopped here when it sees the file change.
22
23 Options:
24 --json clock status as JSON
25 """
26
27 struct Running {
28 let path: String
29 let start: String
30 let startedAt: Date
31 let title: String
32 }
33
34 static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
35 guard let verb = words.first else { throw Failure(.usage, "clock: in, out or status; see orgstar clock --help") }
36 let command = "clock " + verb
37 switch verb {
38 case "in":
39 let arguments = try Arguments(Array(words.dropFirst()), command: command, flags: [])
40 try arguments.expect(1, 1, command)
41 try clockIn(arguments.positional[0], workspace)
42 case "out":
43 try Arguments(Array(words.dropFirst()), command: command, flags: []).expect(0, 0, command)
44 try clockOut(workspace)
45 case "status":
46 let arguments = try Arguments(Array(words.dropFirst()), command: command, flags: ["--json"])
47 try arguments.expect(0, 0, command)
48 try status(json: arguments.flags.contains("--json"), workspace)
49 default:
50 throw Failure(.usage, "clock: unknown subcommand \(verb); see orgstar clock --help")
51 }
52 }
53
54 static func clockIn(_ spec: String, _ workspace: Workspace) throws(Failure) {
55 try clockIn(workspace) { () throws(Failure) in try workspace.target(spec) }
56 }
57
58 /// Clocks in at the heading `resolve` finds, asked again after the running clock stops.
59 static func clockIn(_ workspace: Workspace, target resolve: () throws(Failure) -> Workspace.Target) throws(Failure) {
60 var target = try resolve()
61 guard target.offset != nil else { throw Failure(.usage, "clock in: name a heading, as file.org::Heading") }
62 if let running = running(workspace) {
63 if running.path == target.path, try heading(of: running, workspace)?.headingRange.lowerBound == target.offset {
64 workspace.host.print("Clock continues in \"\(running.title)\"")
65 return
66 }
67 workspace.host.print(try stop(running, workspace))
68 // Clocking out may have moved the heading.
69 target = try resolve()
70 }
71 guard let offset = target.offset else { return }
72 let (_, text) = try workspace.perform(ClockIn(), path: target.path, at: offset)
73 guard let start = ClockIn.runningStart(in: text, near: offset) else { throw Failure(.failure, "The clock line wasn't found after clocking in.") }
74 workspace.host.print("Clock starts at [\(start)] in \"\(target.title ?? "")\"")
75 }
76
77 static func clockOut(_ workspace: Workspace) throws(Failure) {
78 guard let running = running(workspace) else { throw Failure(.notFound, "No active clock") }
79 workspace.host.print(try stop(running, workspace))
80 }
81
82 private static func stop(_ running: Running, _ workspace: Workspace) throws(Failure) -> String {
83 let (_, text) = try workspace.perform(ClockOut(start: running.start), path: running.path, at: 0)
84 let minutes = max(0, Int(workspace.host.now.timeIntervalSince(running.startedAt) / 60))
85 let removed = !text.contains("CLOCK: [\(running.start)]")
86 return String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60) + (removed ? " => LINE REMOVED" : "") + " in \"\(running.title)\""
87 }
88
89 static func status(json: Bool, _ workspace: Workspace) throws(Failure) {
90 let running = running(workspace)
91 if json {
92 let value: [String: Any] = running.map { running in
93 ["running": [
94 "file": running.path, "heading": running.title, "start": running.start,
95 "minutes": max(0, Int(workspace.host.now.timeIntervalSince(running.startedAt) / 60)),
96 ] as [String: Any]]
97 } ?? ["running": NSNull()]
98 workspace.host.output(JSONOutput.data(value))
99 } else if let running {
100 let minutes = max(0, Int(workspace.host.now.timeIntervalSince(running.startedAt) / 60))
101 workspace.host.print(String(format: "%d:%02d ", minutes / 60, minutes % 60) + "\(running.title) (\(running.path)) since [\(running.start)]")
102 } else {
103 workspace.host.print("No active clock")
104 }
105 if running == nil { throw Failure(.notFound, "") }
106 }
107
108 /// The clock the app shows, while its line is still open; else the most recently started
109 /// open clock in the agenda files.
110 static func running(_ workspace: Workspace) -> Running? {
111 let saved = savedRunning(workspace)
112 var paths = workspace.agendaFiles
113 if let saved, !paths.contains(saved.path) { paths.append(saved.path) }
114 var newest: Running?
115 for path in paths {
116 guard let text = try? workspace.text(path), text.contains("CLOCK: [") else { continue }
117 for clock in ClockResolution.openClocks(in: text) {
118 guard let startedAt = ClockResolution.date(of: clock.start, calendar: workspace.host.calendar) else { continue }
119 let heading = workspace.headings(text, path: path).last { $0.headingRange.lowerBound <= clock.offset }
120 let found = Running(path: path, start: clock.start, startedAt: startedAt, title: heading?.title ?? "")
121 if saved?.path == path, saved?.start == clock.start { return found }
122 if newest.map({ startedAt > $0.startedAt }) ?? true { newest = found }
123 }
124 }
125 return newest
126 }
127
128 private static func heading(of running: Running, _ workspace: Workspace) throws(Failure) -> HeadingInfo? {
129 let text = try workspace.text(running.path)
130 let offset = (text as NSString).range(of: "CLOCK: [\(running.start)]").location
131 guard offset != NSNotFound else { return nil }
132 return workspace.headings(text, path: running.path).last { $0.headingRange.lowerBound <= offset }
133 }
134
135 /// The running clock in the app's `clock.json`.
136 private static func savedRunning(_ workspace: Workspace) -> (path: String, start: String)? {
137 struct Clock: Decodable {
138 let path: String
139 let start: String
140 }
141 struct Saved: Decodable {
142 let running: Clock?
143 }
144 guard let data = try? Data(contentsOf: workspace.dataDirectory.appendingPathComponent("clock.json")) else { return nil }
145 let clock = (try? JSONDecoder().decode(Saved.self, from: data))?.running ?? (try? JSONDecoder().decode(Clock.self, from: data))
146 return clock.map { ($0.path, $0.start) }
147 }
148}