Sources/OrgstarCLI/AgendaCommand.swift

19641366e5de9103a7d88bf80436ab2aebc03cf5
orgstar/Sources/OrgstarCLI/AgendaCommand.swift

222 lines · 10827 bytes

  1import Foundation
  2import OrgConfig
  3import OrgCore
  4
  5/// `orgstar agenda [view]`: the agenda or a view of views.toml, as text the way Emacs's agenda
  6/// buffer shows it, or as JSON.
  7@MainActor
  8enum AgendaCommand {
  9    static let help = """
 10    Usage: orgstar agenda [<view>] [--json]
 11
 12    Prints the agenda over the agenda files, with the span and start of Settings ▸ Agenda, or a
 13    view by name: "TODO List", "Stuck Projects", or a [[view]] of views.toml.
 14
 15    Options:
 16      --json    the views, days and entries as JSON, with each entry's file and line
 17    """
 18
 19    static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
 20        let arguments = try Arguments(words, command: "agenda", flags: ["--json"])
 21        try arguments.expect(0, 1, "agenda")
 22        let defaults = workspace.defaults
 23        let (views, problems) = AgendaViewLoader.load(userFile: workspace.configFile("views.toml"), defaults: defaults)
 24        for problem in problems { workspace.host.error("orgstar: \(problem)\n") }
 25        let name = arguments.positional.first ?? "Agenda"
 26        guard let view = views.first(where: { $0.name == name }) ?? views.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else {
 27            throw Failure(.notFound, "No agenda view named \(name). Views: " + views.map(\.name).joined(separator: ", "))
 28        }
 29        let blocks = compute(view, views: views, workspace)
 30        if arguments.flags.contains("--json") {
 31            workspace.host.output(JSONOutput.data(json(view: view.name, blocks, workspace)))
 32        } else {
 33            workspace.host.print(text(blocks, today: today(workspace), showAllDates: OrgPreferences.agendaShowAllDates(workspace.defaults)))
 34        }
 35    }
 36
 37    struct Block {
 38        let mode: AgendaMode
 39        let header: String?
 40        var first = 0
 41        var span = 0
 42        var days: [AgendaDay] = []
 43        var list: [AgendaItem] = []
 44    }
 45
 46    static func today(_ workspace: Workspace) -> Int { Days.absolute(workspace.host.now, calendar: workspace.host.calendar) }
 47
 48    /// The view's blocks, computed as the agenda window computes them.
 49    static func compute(_ view: AgendaViewDefinition, views: [AgendaViewDefinition], _ workspace: Workspace) -> [Block] {
 50        let defaults = workspace.defaults
 51        let host = workspace.host
 52        let now = host.now
 53        let calendar = host.calendar
 54        let today = today(workspace)
 55        let clock = calendar.dateComponents([.hour, .minute], from: now)
 56        let base = OrgPreferences.agendaOptions(AgendaOptions.terminal, defaults)
 57        let viewSettings = AgendaViewLoader.settings(views)
 58        var jobs: [(mode: AgendaMode, options: AgendaOptions, header: String?)] = []
 59        if case .blocks(let blocks) = view.mode {
 60            for block in blocks { jobs.append((block.mode, block.settings.apply(to: base, view: block.mode.viewKey), block.settings.header)) }
 61        } else {
 62            jobs.append((view.mode, viewSettings[view.mode]?.apply(to: base, view: view.mode.viewKey) ?? base, view.settings.header))
 63        }
 64        let sources = sources(workspace, options: base)
 65        return jobs.map { job in
 66            var block = Block(mode: job.mode, header: job.header)
 67            switch job.mode {
 68            case .agenda(let span, let start):
 69                var first = today + (start ?? OrgPreferences.agendaStartOffset(defaults))
 70                let days = span ?? OrgPreferences.agendaSpan(defaults)
 71                if days == 7 || days == 14 { first = Days.weekStart(first, on: OrgPreferences.agendaStartOnWeekday(defaults)) }
 72                block.first = first
 73                block.span = days
 74                block.days = Agenda.list(sources, start: first, days: days, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: job.options)
 75            case .todo(let keywords):
 76                block.list = Agenda.todoList(sources, keywords: keywords, options: job.options, today: today)
 77            case .match(let match, let todoOnly):
 78                block.list = Agenda.tagsMatch(sources, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: job.options)
 79            case .search(let string, let todoOnly):
 80                block.list = Agenda.textSearch(sources, string: string, todoOnly: todoOnly, options: job.options)
 81            case .stuck(let definition):
 82                block.list = Agenda.stuckProjects(sources, definition ?? job.options.stuckProjects, now: now, calendar: calendar, options: job.options)
 83            case .blocks:
 84                break
 85            }
 86            return block
 87        }
 88    }
 89
 90    /// The agenda files, parsed, without the files others archive to when
 91    /// `agenda-exclude-archives` is on.
 92    static func sources(_ workspace: Workspace, options: AgendaOptions) -> [AgendaSource] {
 93        let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
 94        var sources = workspace.agendaFiles.compactMap { path -> AgendaSource? in
 95            guard let text = try? workspace.text(path) else { return nil }
 96            return AgendaSource(path: path, text: text, defaults: workspace.settings(for: text, path: path), checksBlocking: blocking)
 97        }
 98        if OrgPreferences.agendaExcludeArchives(workspace.defaults) {
 99            let location = OrgPreferences.options(workspace.defaults).archiveLocation ?? "%s_archive::"
100            let archives = Set(sources.flatMap { $0.archiveFiles(location: location) })
101            sources.removeAll { archives.contains($0.path) }
102        }
103        return sources
104    }
105
106    // MARK: - Text
107
108    /// Days without entries are left out unless `showAllDates`; today always shows.
109    static func text(_ blocks: [Block], today: Int, showAllDates: Bool) -> String {
110        var out: [String] = []
111        for (index, block) in blocks.enumerated() {
112            if index > 0 { out.append(String(repeating: "=", count: 80)) }
113            out.append(header(block))
114            if case .agenda = block.mode {
115                for day in block.days where showAllDates || day.isToday || !day.items.isEmpty {
116                    out.append(day.header)
117                    for item in day.items { out.append(line(item, today: today)) }
118                }
119            } else {
120                out += block.list.map { line($0, today: today) }
121            }
122        }
123        return out.joined(separator: "\n")
124    }
125
126    static func line(_ item: AgendaItem, today: Int) -> String {
127        item.habit.map { Habit.insertGraph($0.graph(today: today), into: item.line) } ?? item.line
128    }
129
130    /// The block's first line, as Emacs writes it unless the view overrides it.
131    static func header(_ block: Block) -> String {
132        if let header = block.header { return header }
133        switch block.mode {
134        case .agenda:
135            let name = switch block.span {
136            case 1: "Day"
137            case 7: "Week"
138            case 14: "Fortnight"
139            case 30, 31: "Month"
140            case 365: "Year"
141            default: "\(block.span) days"
142            }
143            var header = name + "-agenda"
144            if block.span < 350 {
145                let first = week(block.first)
146                let last = week(block.first + block.span - 1)
147                header += first == last ? String(format: " (W%02d)", first) : String(format: " (W%02d-W%02d)", first, last)
148            }
149            return header + ":"
150        case .todo(let keywords): return "Global list of TODO items of type: \(keywords ?? "ALL")"
151        case .match(let match, _): return "Headlines with TAGS match: \(match)"
152        case .search(let string, _): return "Search words: \(string)"
153        case .stuck: return "List of stuck projects:"
154        case .blocks: return ""
155        }
156    }
157
158    /// The ISO week of a day as `Days` numbers it.
159    static func week(_ day: Int) -> Int {
160        let d = Days.date(day)
161        var calendar = Calendar(identifier: .iso8601)
162        calendar.timeZone = TimeZone(identifier: "UTC")!
163        let date = calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
164        return calendar.component(.weekOfYear, from: date)
165    }
166
167    // MARK: - JSON
168
169    static func json(view: String, _ blocks: [Block], _ workspace: Workspace) -> [String: Any] {
170        var texts: [String: String] = [:]
171        func entry(_ item: AgendaItem) -> [String: Any] {
172            var value: [String: Any] = [
173                "kind": item.kind.rawValue, "category": item.category, "title": item.text, "tags": item.tags, "done": item.isDone,
174                "text": line(item, today: today(workspace)),
175            ]
176            if !item.time.trimmingCharacters(in: .whitespaces).isEmpty { value["time"] = item.time.trimmingCharacters(in: .whitespaces) }
177            if !item.extra.trimmingCharacters(in: .whitespaces).isEmpty { value["extra"] = item.extra.trimmingCharacters(in: .whitespaces) }
178            if let todo = item.todo { value["todo"] = todo }
179            if let effort = item.effort { value["effort"] = effort }
180            if let path = item.path, let offset = item.headingOffset {
181                value["file"] = path
182                value["offset"] = offset
183                if texts[path] == nil { texts[path] = try? workspace.text(path) }
184                if let text = texts[path] { value["line"] = Workspace.line(of: offset, in: text) }
185            }
186            return value
187        }
188        let list = blocks.map { block -> [String: Any] in
189            var value: [String: Any] = ["header": header(block), "type": type(block.mode)]
190            if case .agenda = block.mode {
191                value["days"] = block.days.map { day -> [String: Any] in
192                    let d = Days.date(day.day)
193                    return ["date": String(format: "%04d-%02d-%02d", d.year, d.month, d.day), "today": day.isToday, "header": day.header,
194                            "entries": day.items.map(entry)]
195                }
196            } else {
197                value["entries"] = block.list.map(entry)
198            }
199            return value
200        }
201        return ["view": view, "blocks": list]
202    }
203
204    static func type(_ mode: AgendaMode) -> String {
205        switch mode {
206        case .agenda: "agenda"
207        case .todo: "todo"
208        case .match(_, let todoOnly): todoOnly ? "todo-match" : "match"
209        case .search(_, let todoOnly): todoOnly ? "todo-search" : "search"
210        case .stuck: "stuck"
211        case .blocks: "blocks"
212        }
213    }
214}
215
216enum JSONOutput {
217    static func data(_ value: Any) -> Data {
218        var data = (try? JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])) ?? Data()
219        data.append(0x0A)
220        return data
221    }
222}
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