Tests/OrgAppTests/DenoteOracleTests.swift

a15753a827b5ab7a0ccf3a0873890771c2979ee7
orgstar/Tests/OrgAppTests/DenoteOracleTests.swift

405 lines · 29351 bytes

  1import Foundation
  2import Testing
  3@testable import OrgApp
  4@testable import OrgCore
  5
  6/// Denote and denote-journal themselves, run in Emacs, when they're installed: the load-path
  7/// directories in `ORGSTAR_DENOTE` (colon-separated), else a Doom or package.el install.
  8struct DenoteOracleTests {
  9    /// The load-path directories of denote and denote-journal, and of denote-org and
 10    /// denote-sequence when they're there too.
 11    static let loadPath: [String]? = {
 12        if let paths = ProcessInfo.processInfo.environment["ORGSTAR_DENOTE"] { return paths.split(separator: ":").map(String.init) }
 13        let fm = FileManager.default, home = NSHomeDirectory()
 14        let roots = ["\(home)/.config/emacs/.local/straight", "\(home)/.emacs.d/.local/straight"].flatMap { root in
 15            ((try? fm.contentsOfDirectory(atPath: root)) ?? []).filter { $0.hasPrefix("build-") }.sorted().reversed().map { "\(root)/\($0)" }
 16        } + ["\(home)/.emacs.d/elpa", "\(home)/.config/emacs/elpa"]
 17        for root in roots {
 18            let names = (try? fm.contentsOfDirectory(atPath: root)) ?? []
 19            let dirs = ["denote", "denote-journal", "denote-org", "denote-sequence"].compactMap { package in
 20                names.filter { $0 == package || ($0.hasPrefix(package + "-") && $0.dropFirst(package.count + 1).first?.isNumber == true) }
 21                    .sorted().last.map { "\(root)/\($0)" }
 22            }
 23            if dirs.count >= 2, dirs[0].hasSuffix("/denote") || dirs[0].contains("/denote-") { return dirs }
 24        }
 25        return nil
 26    }()
 27
 28    static func has(_ package: String) -> Bool { enabled && loadPath!.contains { ($0 as NSString).lastPathComponent == package || ($0 as NSString).lastPathComponent.hasPrefix(package + "-") && ($0 as NSString).lastPathComponent.dropFirst(package.count + 1).first?.isNumber == true } }
 29
 30    static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
 31
 32    /// Runs `body` with Denote loaded, `denote-directory` at `folder` and nothing backed up.
 33    static func denote(_ folder: URL, _ body: String) throws {
 34        let paths = loadPath!.map(\.debugDescription).joined(separator: " ")
 35        _ = try DailiesTests.emacs("""
 36            (progn (setq load-path (append (list \(paths)) load-path) make-backup-files nil auto-save-default nil create-lockfiles nil
 37                         coding-system-for-read 'utf-8 coding-system-for-write 'utf-8)
 38              (require 'denote) (require 'denote-journal)
 39              (setq denote-directory \((folder.path + "/").debugDescription) denote-rename-confirmations nil)
 40              \(body))
 41            """)
 42    }
 43
 44    static func folder() throws -> URL {
 45        let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
 46        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
 47        return url
 48    }
 49
 50    static func lines(_ url: URL) throws -> [String] {
 51        try String(contentsOf: url, encoding: .utf8).split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
 52    }
 53
 54    @Test(.enabled(if: enabled)) func slugsMatchDenote() throws {
 55        let titles = ["Hello, World: a_test -- Note!", "  Café au lait  ", "C++ & Rust!", "Привет мир", "x=y/z", "a  -  b", "It's [done]", "日本語のノート", "a <b> c\\d"]
 56        let words = ["Emacs", "org-mode", "two words", "a_b", "Café", "x=1"]
 57        let dir = try Self.folder()
 58        defer { try? FileManager.default.removeItem(at: dir) }
 59        let input = dir.appendingPathComponent("in.txt"), output = dir.appendingPathComponent("out.txt")
 60        try (titles + words).joined(separator: "\n").write(to: input, atomically: true, encoding: .utf8)
 61        try Self.denote(dir, """
 62            (let ((lines (split-string (with-temp-buffer (insert-file-contents \(input.path.debugDescription)) (buffer-string)) "\\n")))
 63              (with-temp-file \(output.path.debugDescription)
 64                (dotimes (i (length lines))
 65                  (insert (denote-sluggify (if (< i \(titles.count)) 'title 'keyword) (nth i lines)) "\\n"))))
 66            """)
 67        let theirs = try Self.lines(output)
 68        #expect(Array(theirs.prefix(titles.count)) == titles.map(Denote.slug))
 69        #expect(Array(theirs.dropFirst(titles.count).prefix(words.count)) == words.map(Denote.keyword))
 70    }
 71
 72    /// A note, a journal entry and a rename, as files Denote and orgstar each make.
 73    @Test(.enabled(if: enabled)) func filesMatchDenote() throws {
 74        let theirs = try Self.folder(), ours = try Self.folder()
 75        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
 76        let front = "#+title:      New Title\n#+signature:  Two Words\n#+filetags:   :zeta:alpha:\n#+identifier: 20261011T080000\n\nBody\n"
 77        let old = "20261011T080000==1a--old__x.org"
 78        for dir in [theirs, ours] { try front.write(to: dir.appendingPathComponent(old), atomically: true, encoding: .utf8) }
 79        try Self.denote(theirs, """
 80            (progn
 81              (denote "Field Notes" (denote-keywords-sort (list "work" "ideas")) 'org nil "2026-10-11 12:00:05")
 82              (save-buffer)
 83              (let ((denote-journal-directory nil)) (denote-journal-new-entry "2026-10-11 12:00:00") (save-buffer))
 84              (denote-rename-file-using-front-matter \(theirs.appendingPathComponent(old).path.debugDescription))
 85              (save-some-buffers t))
 86            """)
 87        _ = try DenoteNote.create(title: "Field Notes", keywords: ["work", "ideas"], in: ours.path, now: DailiesTests.day.addingTimeInterval(5))
 88        _ = try Dailies(directory: ours.path, journal: Dailies.Journal()).ensure(DailiesTests.day)
 89        let renamed = Denote.renamed(ours.appendingPathComponent(old).path, text: front)!
 90        try renamed.text.write(to: ours.appendingPathComponent(old), atomically: true, encoding: .utf8)
 91        try FileManager.default.moveItem(atPath: ours.appendingPathComponent(old).path, toPath: renamed.path)
 92
 93        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.path).sorted()
 94        #expect(names.count == 3)
 95        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.path).sorted() == names)
 96        for name in names {
 97            #expect(try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
 98                == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
 99        }
100    }
101
102    /// New notes in the Markdown and text file types, as files Denote and orgstar each make.
103    @Test(.enabled(if: enabled)) func textTypeNotesMatchDenote() throws {
104        let theirs = try Self.folder(), ours = try Self.folder()
105        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
106        let notes: [(type: Denote.FileType, title: String, keywords: [String], signature: String, minute: Int)] = [
107            (.markdownYAML, "Field \"Notes\": a\\b", ["work", "ideas"], "Part One", 1),
108            (.markdownYAML, "Bare", [], "", 2),
109            (.markdownTOML, "Toml Note", ["zeta", "alpha"], "1a", 3),
110            (.markdownTOML, "", [], "", 4),
111            (.text, "Plain Note", ["work", "ideas"], "x", 5),
112            (.text, "Bare Text", [], "", 6),
113        ]
114        let calls = notes.map { n in
115            "(denote \(n.title.debugDescription) (denote-keywords-sort (list \(n.keywords.map(\.debugDescription).joined(separator: " ")))) '\(n.type.rawValue) nil \(String(format: "\"2026-10-11 12:%02d:05\"", n.minute)) nil \(n.signature.debugDescription)) (save-buffer)"
116        }.joined(separator: "\n")
117        try Self.denote(theirs, "(progn \(calls))")
118        for n in notes {
119            _ = try DenoteNote.create(title: n.title, keywords: n.keywords, in: ours.path, now: DailiesTests.day.addingTimeInterval(Double(n.minute * 60 + 5)),
120                                      signature: n.signature, type: n.type)
121        }
122        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.path).sorted()
123        #expect(names.count == notes.count)
124        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.path).sorted() == names)
125        for name in names {
126            #expect(try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
127                == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
128        }
129    }
130
131    /// `denote-rename-file` and `denote-rename-file-using-front-matter` on Markdown and text
132    /// notes: front matter rewritten, a line added and one removed, front matter added to a file
133    /// without any, and names and front matter taken from edited front matter.
134    @Test(.enabled(if: enabled)) func textTypeRenamesMatchDenote() throws {
135        let theirs = try Self.folder(), ours = try Self.folder()
136        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
137        let files = [
138            "20261011T120000--old-yaml__x.md": "---\ntitle:      \"Old Yaml\"\ndate:       2026-10-11T12:00:00+02:00\ntags:       [\"x\"]\nidentifier: \"20261011T120000\"\n---\n\n# Body\n",
139            "20261011T130000==zz--old-toml.md": "+++\ntitle      = \"Old Toml\"\ndate       = 2026-10-11T13:00:00-05:00\ntags       = []\nidentifier = \"20261011T130000\"\nsignature  = \"zz\"\n+++\n\nBody\n",
140            "20261011T140000--old-text__x.txt": "title:      Old Text\ntags:       x\nidentifier: 20261011T140000\n---------------------------\n\nBody\n",
141            "plain.md": "# Heading\n\nNo front matter\n",
142            "plain.txt": "No front matter\n",
143            "20261011T150000--edited-yaml__x.md": "---\ntitle:      \"New \\\"Q\\\" Title\"\ndate:       2026-10-11T15:00:00+00:00\ntags:       [\"zeta\", \"alpha\"]\nidentifier: \"20261011T150000\"\nsignature:  \"Two Words\"\n---\n\nBody\n",
144            "20261011T160000--edited-toml__x.md": "+++\ntitle      = 'Toml Title'\ntags       = [\"zeta\", \"alpha\"]\nidentifier = \"20261011T160000\"\n+++\n\nBody\n",
145            "20261011T170000--edited-text__x.txt": "title:      Text Title\ndate:       2026-10-11\ntags:       zeta  alpha\nidentifier: 20261011T170000\n---------------------------\n\nBody\n",
146        ]
147        for dir in [theirs, ours] { for (name, text) in files { try text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) } }
148        let renames: [(file: String, title: String, keywords: [String], signature: String)] = [
149            ("20261011T120000--old-yaml__x.md", "New \"Yaml\"", ["zeta", "alpha"], "Part One"),
150            ("20261011T130000==zz--old-toml.md", "New Toml", ["k"], ""),
151            ("20261011T140000--old-text__x.txt", "New Text", ["a", "b"], "s1"),
152            ("plain.md", "Plain Markdown", ["k"], ""),
153            ("plain.txt", "Plain Text", [], ""),
154        ]
155        let fromFrontMatter = ["20261011T150000--edited-yaml__x.md", "20261011T160000--edited-toml__x.md", "20261011T170000--edited-text__x.txt"]
156        let calls = renames.map { r in
157            "(denote-rename-file \(theirs.appendingPathComponent(r.file).path.debugDescription) \(r.title.debugDescription) (list \(r.keywords.map(\.debugDescription).joined(separator: " "))) \(r.signature.debugDescription) \"2026-10-11 12:00:00\" \((Denote.identifier(ofFile: r.file) ?? "").debugDescription))"
158        } + fromFrontMatter.map { "(denote-rename-file-using-front-matter \(theirs.appendingPathComponent($0).path.debugDescription))" }
159        try Self.denote(theirs, "(progn " + calls.joined(separator: "\n") + "\n(save-some-buffers t))")
160        let date = Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 12))!
161        for r in renames {
162            let path = ours.appendingPathComponent(r.file).path
163            let text = try String(contentsOfFile: path, encoding: .utf8)
164            let (target, rewritten) = DenoteNote.renaming(path, text: text, title: r.title, keywords: r.keywords, signature: r.signature, date: date, roots: [ours.path])
165            try rewritten.write(toFile: path, atomically: true, encoding: .utf8)
166            if target != path { try FileManager.default.moveItem(atPath: path, toPath: target) }
167        }
168        for file in fromFrontMatter {
169            let path = ours.appendingPathComponent(file).path
170            let (target, rewritten) = try #require(Denote.renamed(path, text: String(contentsOfFile: path, encoding: .utf8)))
171            try rewritten.write(toFile: path, atomically: true, encoding: .utf8)
172            if target != path { try FileManager.default.moveItem(atPath: path, toPath: target) }
173        }
174        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.path).sorted()
175        #expect(names.contains("20261011T120000==part=one--new-yaml__alpha_zeta.md") && names.contains("20261011T160000--toml-title__alpha_zeta.md"))
176        #expect(!names.contains("plain.md") && !names.contains("plain.txt"))
177        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.path).sorted() == names)
178        for name in names {
179            #expect(try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
180                == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
181        }
182    }
183
184    /// A note in a subfolder with a signature and a template, dated a second some file's
185    /// identifier already has.
186    @Test(.enabled(if: enabled)) func optionsMatchDenote() throws {
187        let theirs = try Self.folder(), ours = try Self.folder()
188        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
189        let taken = "20261011T093000--taken.org"
190        for dir in [theirs, ours] {
191            try FileManager.default.createDirectory(at: dir.appendingPathComponent("work"), withIntermediateDirectories: true)
192            try "x\n".write(to: dir.appendingPathComponent(taken), atomically: true, encoding: .utf8)
193        }
194        let template = "* Goals\n\n* Notes\n"
195        try Self.denote(theirs, """
196            (let ((denote-templates '((plan . \(template.debugDescription)))))
197              (denote "Q4 Plan: draft" (denote-keywords-sort (list "work" "ideas")) 'org \(theirs.appendingPathComponent("work/").path.debugDescription)
198                      "2026-10-11 09:30" 'plan "Part One")
199              (save-buffer))
200            """)
201        let date = try #require(RoamActions.date("2026-10-11 09:30"))
202        _ = try DenoteNote.create(title: "Q4 Plan: draft", keywords: ["work", "ideas"], in: ours.appendingPathComponent("work").path, roots: [ours.path],
203                                  now: date, signature: "Part One", template: template)
204        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.appendingPathComponent("work").path)
205        #expect(names.count == 1)
206        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.appendingPathComponent("work").path) == names)
207        for name in names {
208            #expect(try String(contentsOf: ours.appendingPathComponent("work/" + name), encoding: .utf8)
209                == String(contentsOf: theirs.appendingPathComponent("work/" + name), encoding: .utf8), "\(name)")
210        }
211    }
212
213    /// denote-org's dynamic blocks, each updated in a note by Emacs and by orgstar.
214    @Test(.enabled(if: has("denote-org"))) func blocksMatchDenoteOrg() throws {
215        let dir = try Self.folder()
216        defer { try? FileManager.default.removeItem(at: dir) }
217        try FileManager.default.createDirectory(at: dir.appendingPathComponent("sub"), withIntermediateDirectories: true)
218        let notes = [
219            "20261001T090000--alpha-note__emacs_work.org": "#+title:      Alpha Note\n#+filetags:   :emacs:work:\n#+identifier: 20261001T090000\n\n* First\nSee [[denote:20261119T120000][Current]].\n** Deeper\n#+begin_src sh\necho\n#+end_src\n",
220            "20261002T090000==1a--beta__emacs.org": "#+title:      Beta\n#+filetags:   :emacs:\n#+identifier: 20261002T090000\n\nBeta body.\n",
221            "sub/20260930T090000--gamma-in-sub__work.org": "#+title:      Gamma in Sub\n#+filetags:   :work:\n#+identifier: 20260930T090000\n\nGamma links [[denote:20261119T120000::#top][here]].\n",
222            "20261003T090000--delta__misc.md": "---\ntitle: Delta\n---\n\nDelta.\n",
223            "plain.org": "* Not a note\n",
224            "20261004T090000==1--root__seq.org": "#+title:      Root\n\nR\n",
225            "20261005T090000==1=1--first__seq.org": "#+title:      First\n\nF\n",
226            "20261006T090000==1=2--second__seq.org": "#+title:      Second\n\nS\n",
227            "20261007T090000==1=1=1--deep__seq.org": "#+title:      Deep\n\nD\n",
228            "20261008T090000==2--other__seq.org": "#+title:      Other\n\nO\n",
229        ]
230        for (name, text) in notes { try text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) }
231        let current = dir.appendingPathComponent("20261119T120000--current.org")
232        let head = "#+title:      Current\n#+identifier: 20261119T120000\n\nAlready: [[denote:20261002T090000][Beta]]\n\n"
233        let blocks = [
234            "denote-links :regexp \"_emacs\"",
235            "denote-links :regexp \".\" :sort-by-component title :reverse-sort t",
236            "denote-links :regexp \"_work\" :id-only t",
237            "denote-links :regexp \"_work\" :include-date t :block-name \"mine\"",
238            "denote-links :regexp \".\" :not-regexp \"sub\" :sort-by-component signature",
239            "denote-missing-links :regexp \".\"",
240            "denote-backlinks",
241            "denote-files :regexp \"beta\"",
242            "denote-files :regexp \"_work\" :no-front-matter t :add-links t :file-separator t",
243            "denote-files :regexp \"_work\" :no-front-matter 2",
244            "denote-files-as-headings :regexp \"_work\"",
245            "denote-files-as-headings :regexp \"_work\" :add-links t :exclude-tags t",
246            "denote-sequence :sequence \"1\" :depth 2",
247            "denote-sequence :sequence \"1=1\"",
248            "denote-sequence :sequence \"\"",
249        ]
250        let paths = Self.loadPath!.map(\.debugDescription).joined(separator: " ")
251        for block in blocks {
252            let text = head + "#+BEGIN: \(block)\nold\n#+END:\n"
253            try text.write(to: current, atomically: true, encoding: .utf8)
254            let theirs = try DailiesTests.emacs("""
255                (progn (setq load-path (append (list \(paths)) load-path) coding-system-for-read 'utf-8 coding-system-for-write 'utf-8)
256                  (require 'org) (require 'denote) (require 'denote-sequence nil t) (require 'denote-org)
257                  (setq denote-directory \((dir.path + "/").debugDescription))
258                  (find-file \(current.path.debugDescription))
259                  (goto-char (point-min)) (re-search-forward "^#\\\\+BEGIN:") (beginning-of-line)
260                  (org-update-dblock)
261                  (princ (buffer-string)))
262                """)
263            var options = EditingOptions.org
264            options.filePath = current.path
265            options.denoteDirectories = [dir.path]
266            let begin = (text as NSString).range(of: "#+BEGIN:").location
267            let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [begin..<begin], options: options)
268            var ours = text
269            if case .commit(let result) = UpdateDynamicBlock().run(in: context) {
270                for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
271            } else {
272                ours = "failed"
273            }
274            #expect(ours == theirs, "\(block)\nours:\n\(ours)\ntheirs:\n\(theirs)")
275        }
276        // The insert commands, at the end of a line of text and on an empty line.
277        let inserts: [(lisp: String, kind: InsertDenoteBlock.Kind, answers: [String: String])] = [
278            ("(denote-org-dblock-insert-links \"_emacs\")", .links, ["regexp": "_emacs"]),
279            ("(denote-org-dblock-insert-missing-links \".\")", .missingLinks, ["regexp": "."]),
280            ("(denote-org-dblock-insert-backlinks)", .backlinks, [:]),
281            ("(denote-org-dblock-insert-files \"beta\" 'title)", .files, ["regexp": "beta", "sort": "title"]),
282            ("(denote-org-dblock-insert-files-as-headings \"_work\" nil)", .filesAsHeadings, ["regexp": "_work", "sort": ""]),
283            ("(denote-org-dblock-insert-sequence \(dir.appendingPathComponent("20261004T090000==1--root__seq.org").path.debugDescription) 2)", .sequence,
284             ["sequence": "20261004T090000==1--root__seq.org", "depth": "2"]),
285        ]
286        for (lisp, kind, answers) in inserts {
287            for text in [head + "Last line", head] {
288                try text.write(to: current, atomically: true, encoding: .utf8)
289                let theirs = try DailiesTests.emacs("""
290                    (progn (setq load-path (append (list \(paths)) load-path) coding-system-for-read 'utf-8 coding-system-for-write 'utf-8)
291                      (require 'org) (require 'denote) (require 'denote-sequence nil t) (require 'denote-org)
292                      (setq denote-directory \((dir.path + "/").debugDescription))
293                      (find-file \(current.path.debugDescription))
294                      (goto-char (point-max))
295                      \(lisp)
296                      (princ (buffer-string)))
297                    """)
298                var options = EditingOptions.org
299                options.filePath = current.path
300                options.denoteDirectories = [dir.path]
301                let end = (text as NSString).length
302                let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [end..<end], answers: answers, options: options)
303                var ours = text
304                if case .commit(let result) = InsertDenoteBlock(kind).run(in: context) {
305                    for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
306                } else {
307                    ours = "failed"
308                }
309                #expect(ours == theirs, "\(lisp)\nours:\n\(ours)\ntheirs:\n\(theirs)")
310            }
311        }
312    }
313
314    /// denote-sequence's new parents, children and siblings, relatives and conversions, for
315    /// notes in each scheme, from Emacs and from orgstar.
316    @Test(.enabled(if: has("denote-sequence"))) func sequencesMatchDenoteSequence() throws {
317        let sets: [(DenoteSequence.Scheme, [String])] = [
318            (.numeric, ["1", "1=1", "1=2", "1=1=1", "1=1=1=1", "2", "3=1", "10", "10=9", "10=10", "2=1=5"]),
319            (.alphanumeric, ["1", "1a", "1b", "1a1", "1a2", "1z", "2", "2a1a", "3", "1za"]),
320            (.alphanumericDelimited, ["1", "1=a", "1=b", "1=a1b", "1=a1b=1", "2", "2=a", "1=a2"]),
321        ]
322        let paths = Self.loadPath!.map(\.debugDescription).joined(separator: " ")
323        for (scheme, sequences) in sets {
324            let dir = try Self.folder()
325            defer { try? FileManager.default.removeItem(at: dir) }
326            for (index, sequence) in sequences.enumerated() {
327                try "x\n".write(to: dir.appendingPathComponent(String(format: "20260101T%06d==%@--n%d.org", index, sequence, index)), atomically: true, encoding: .utf8)
328            }
329            let names = sequences.map(\.debugDescription).joined(separator: " ")
330            let relations = DenoteSequence.Relation.allCases.map(\.rawValue).joined(separator: " ")
331            let theirs = try DailiesTests.emacs("""
332                (progn (setq load-path (append (list \(paths)) load-path))
333                  (require 'denote) (require 'denote-sequence)
334                  (setq denote-directory \((dir.path + "/").debugDescription) denote-sequence-scheme '\(scheme.rawValue))
335                  (defmacro try (form) `(condition-case nil ,form (error "ERR")))
336                  (princ (format "parent %s\\n" (try (denote-sequence-get-new 'parent))))
337                  (dolist (s (list \(names)))
338                    (princ (format "child %s %s\\n" s (try (denote-sequence-get-new 'child s))))
339                    (princ (format "sibling %s %s\\n" s (try (denote-sequence-get-new 'sibling s))))
340                    (dolist (target '(numeric alphanumeric alphanumeric-delimited))
341                      (princ (format "convert %s %s %s\\n" s target (try (denote-sequence-make-conversion s target)))))
342                    (dolist (relation '(\(relations)))
343                      (princ (format "%s %s %s\\n" relation s
344                                     (try (let ((found (denote-sequence-get-relative s relation)))
345                                            (string-join (sort (mapcar #'file-name-nondirectory (if (stringp found) (list found) found)) #'string<) ","))))))))
346                """)
347            let model = DenoteSequence(scheme: scheme)
348            let files = DenoteSequence.files(DenoteBlocks.files(in: [dir.path]).map(\.path))
349            let all = files.map(\.sequence)
350            func attempt(_ body: () throws -> String) -> String { (try? body()) ?? "ERR" }
351            var ours = "parent \(attempt { try model.newParent(among: all) })\n"
352            for s in sequences {
353                ours += "child \(s) \(attempt { try model.newChild(of: s, among: all) })\n"
354                ours += "sibling \(s) \(attempt { try model.newSibling(of: s, among: all) })\n"
355                for target in DenoteSequence.Scheme.allCases {
356                    ours += "convert \(s) \(target.rawValue) \(attempt { try model.converted(s, to: target) })\n"
357                }
358                for relation in DenoteSequence.Relation.allCases {
359                    ours += "\(relation.rawValue) \(s) \(attempt { try model.relatives(of: s, relation, in: files).map { ($0 as NSString).lastPathComponent }.sorted().joined(separator: ",") })\n"
360                }
361            }
362            let theirLines = theirs.split(separator: "\n").map(String.init), ourLines = ours.split(separator: "\n").map(String.init)
363            #expect(theirLines.count == ourLines.count, "\(scheme)\n\(theirs)")
364            for (a, b) in zip(ourLines, theirLines) where a != b {
365                Issue.record("\(scheme): ours \(a) | theirs \(b)")
366            }
367        }
368    }
369
370    /// `denote-rename-file` with a new title, keywords, signature and date: on a note, on one
371    /// whose signature goes, and on a file without front matter or identifier.
372    @Test(.enabled(if: enabled)) func renamesMatchDenote() throws {
373        let theirs = try Self.folder(), ours = try Self.folder()
374        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
375        let files = [
376            "20261011T120000--old-title__x.org": "#+title:      Old Title\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   :x:\n#+identifier: 20261011T120000\n#+startup: overview\n\nBody\n",
377            "20261011T130000==zz--has-sig.org": "#+title:      Has Sig\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   \n#+identifier: 20261011T130000\n#+signature:  zz\n\nBody\n",
378            "plain.org": "* Heading\nNo front matter\n",
379        ]
380        for dir in [theirs, ours] { for (name, text) in files { try text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) } }
381        let renames: [(file: String, title: String, keywords: [String], signature: String)] = [
382            ("20261011T120000--old-title__x.org", "New Title", ["zeta", "Alpha"], "Part One"),
383            ("20261011T130000==zz--has-sig.org", "Has Sig", [], ""),
384            ("plain.org", "Plain Note", ["k"], ""),
385        ]
386        let calls = renames.map { r in
387            "(denote-rename-file \(theirs.appendingPathComponent(r.file).path.debugDescription) \(r.title.debugDescription) (list \(r.keywords.map(\.debugDescription).joined(separator: " "))) \(r.signature.debugDescription) \"2026-10-11 12:00:00\" \((Denote.identifier(ofFile: r.file) ?? "").debugDescription))"
388        }.joined(separator: "\n")
389        try Self.denote(theirs, calls + "\n(save-some-buffers t)")
390        let date = Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 12))!
391        for r in renames {
392            let path = ours.appendingPathComponent(r.file).path
393            let text = try String(contentsOfFile: path, encoding: .utf8)
394            let (target, rewritten) = DenoteNote.renaming(path, text: text, title: r.title, keywords: r.keywords, signature: r.signature, date: date, roots: [ours.path])
395            try rewritten.write(toFile: path, atomically: true, encoding: .utf8)
396            if target != path { try FileManager.default.moveItem(atPath: path, toPath: target) }
397        }
398        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.path).sorted()
399        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.path).sorted() == names)
400        for name in names {
401            #expect(try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
402                == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
403        }
404    }
405}
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