Sources/OrgApp/Dailies.swift

97 lines · 5145 bytes

 1import Foundation
 2import OrgCore
 3
 4/// org-roam-dailies (org-roam 2.3): a file a day in `org-roam-dailies-directory` under
 5/// `org-roam-directory`, named and started as its default capture template does,
 6/// `%<%Y-%m-%d>.org` with `#+title: %<%Y-%m-%d>`, and an ID like any new org-roam file.
 7public struct Dailies: Sendable, Equatable {
 8    public struct Failure: Error, Equatable, CustomStringConvertible {
 9        public let description: String
10        public init(_ description: String) { self.description = description }
11    }
12
13    /// The folder the daily files are in.
14    public var directory: String
15    /// The file name, with `%<…>` for the date.
16    public var file: String
17    /// What a new file starts with.
18    public var head: String
19    /// What Capture to Daily adds, an org-capture template.
20    public var entry: String
21
22    public init(directory: String, file: String = "%<%Y-%m-%d>.org", head: String = "#+title: %<%Y-%m-%d>\n", entry: String = "* %?") {
23        self.directory = directory
24        self.file = file
25        self.head = head
26        self.entry = entry
27    }
28
29    /// The settings' dailies: `org-roam-directory`, by default the first folder, and
30    /// `org-roam-dailies-directory` in it. Nil without a folder.
31    public static func configured(roots: [String], defaults: UserDefaults = .standard) -> Dailies? {
32        let roam = OrgPreferences.roamDirectory(defaults)
33        guard let base = roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory()) else { return nil }
34        return Dailies(directory: OrgAttach.expand(OrgPreferences.dailiesDirectory(defaults), in: base),
35                       file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults), entry: OrgPreferences.dailiesEntry(defaults))
36    }
37
38    /// `format-time-string` for each `%<format>`, in the local time zone.
39    public static func expandTime(_ template: String, _ day: Date) -> String {
40        template.replacing(/%<([^>]*)>/) { strftime(String($0.1), day) }
41    }
42
43    static func strftime(_ format: String, _ date: Date) -> String {
44        var time = time_t(date.timeIntervalSince1970)
45        var parts = tm()
46        localtime_r(&time, &parts)
47        var buffer = [CChar](repeating: 0, count: 256)
48        let count = Darwin.strftime(&buffer, buffer.count, format, &parts)
49        return String(decoding: buffer[..<count].map { UInt8(bitPattern: $0) }, as: UTF8.self)
50    }
51
52    public func path(for day: Date) -> String {
53        OrgAttach.expand(Self.expandTime(file, day).trimmingCharacters(in: .whitespaces), in: directory)
54    }
55
56    /// The file's text when it's new: the head, ending in a newline, under a property drawer
57    /// with the ID, as `org-entry-put` puts it at the start.
58    public func newText(_ day: Date, id: String) -> String {
59        var text = Self.expandTime(head, day)
60        if !text.hasSuffix("\n") { text += "\n" }
61        return OrgAttach.ensuringID(text, at: 0) { id }.text
62    }
63
64    /// The daily file for `day`, made when missing. True when it's new.
65    @discardableResult
66    public func ensure(_ day: Date, id: () -> String = { UUID().uuidString.lowercased() }) throws -> (path: String, created: Bool) {
67        let path = path(for: day)
68        guard !FileManager.default.fileExists(atPath: path) else { return (path, false) }
69        try FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
70        try newText(day, id: id()).write(toFile: path, atomically: true, encoding: .utf8)
71        return (path, true)
72    }
73
74    /// `org-roam-dailies--list-files`: the org files in the folder and below, without hidden,
75    /// backup and auto-save files, sorted.
76    public func files() -> [String] {
77        let paths = (FileManager.default.enumerator(atPath: directory)?.allObjects as? [String]) ?? []
78        return paths.compactMap { relative -> String? in
79            let name = (relative as NSString).lastPathComponent
80            guard (relative as NSString).pathExtension == "org", !relative.split(separator: "/").contains(where: { $0.hasPrefix(".") }),
81                  !name.hasPrefix("#"), !name.hasSuffix("~") else { return nil }
82            return (directory as NSString).appendingPathComponent(relative)
83        }.sorted()
84    }
85
86    /// `org-roam-dailies-goto-next-note` from the daily file at `path`, `n` notes on
87    /// (back for negative `n`).
88    public func neighbor(of path: String, by n: Int) throws -> String {
89        func real(_ p: String) -> String { URL(fileURLWithPath: p).resolvingSymlinksInPath().path }
90        guard real(path).hasPrefix(real(directory) + "/") else { throw Failure("Not in a daily-note") }
91        let all = files()
92        guard let position = all.map(real).firstIndex(of: real(path)) else { throw Failure("Can't find current note file - have you saved it yet?") }
93        if n >= 0, position == all.count - 1 { throw Failure("Already at newest note") }
94        if n < 0, position == 0 { throw Failure("Already at oldest note") }
95        return all[min(max(position + n, 0), all.count - 1)]
96    }
97}