Sources/OrgApp/RoamNode.swift

45 lines · 2563 bytes

 1import Foundation
 2import OrgCore
 3
 4/// A new org-roam node from a title, as org-roam 2.3's default capture template makes it: a file
 5/// `%<%Y%m%d%H%M%S>-${slug}.org` in `org-roam-directory`, starting `#+title: ${title}` under
 6/// the ID drawer.
 7public enum RoamNode {
 8    /// `org-roam-directory`: the setting, else the first folder.
 9    public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
10        let roam = OrgPreferences.roamDirectory(defaults)
11        return roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory())
12    }
13
14    /// `org-roam-node-slugify`: without the combining marks org-roam drops, everything but
15    /// letters and digits as one `_`, none at either end, lower case.
16    public static func slug(_ title: String) -> String {
17        let trimmed: Set<UInt32> = [0x300, 0x301, 0x302, 0x303, 0x304, 0x306, 0x307, 0x308, 0x309, 0x30A, 0x30B, 0x30C,
18                                    0x31B, 0x323, 0x324, 0x325, 0x327, 0x32D, 0x32E, 0x330, 0x331]
19        let decomposed = title.decomposedStringWithCanonicalMapping.unicodeScalars.filter { !trimmed.contains($0.value) }
20        let composed = String(String.UnicodeScalarView(decomposed)).precomposedStringWithCanonicalMapping
21        var out = ""
22        for character in composed {
23            if character.isLetter || character.isNumber {
24                out.append(character)
25            } else if out.last != "_" {
26                out.append("_")
27            }
28        }
29        while out.first == "_" { out.removeFirst() }
30        while out.last == "_" { out.removeLast() }
31        return out.lowercased()
32    }
33
34    /// Makes the node's file in `folder`. Fails rather than replace a file that's there.
35    public static func create(title: String, in folder: String, now: Date = Date(),
36                              id: () -> String = { UUID().uuidString.lowercased() }) throws -> (path: String, id: String) {
37        let name = Dailies.expandTime("%<%Y%m%d%H%M%S>", now) + "-" + slug(title) + ".org"
38        let path = (folder as NSString).appendingPathComponent(name)
39        let (text, nodeID) = OrgAttach.ensuringID("#+title: \(title)\n", at: 0, newID: id)
40        try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
41        guard !FileManager.default.fileExists(atPath: path) else { throw Dailies.Failure("\(name) is already there") }
42        try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
43        return (path, nodeID)
44    }
45}