Tests/OrgCoreTests/LinkTests.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Tests/OrgCoreTests/LinkTests.swift history · blame · raw

171 lines · 7978 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct LinkTests {
  6    static let links = [
  7        "[[https://orgmode.org/manual][the manual]]", "[[file:notes.org::*Heading two]]", "[[./sub/a.org::#custom]]",
  8        "[[~/x.org::42]]", "[[/abs/path.txt]]", "[[file+sys:/a.pdf]]", "[[id:3F2A-77]]", "[[#my-id][custom]]", "[[(ref)]]",
  9        "[[Some heading]]", "[[*Starred title]]", "[[gh:krz/orgstar]]", "[[wiki:Org mode]]", "[[mailto:a@b.c]]",
 10        "[[doi:10.1000/182]]", "[[a \\[b\\] c]]", "[[file:a.org::target text]]", "[[shell:ls -l]]", "[[unknown:thing]]",
 11        "<https://example.com/a b>", "https://example.com/x?y=1", "file:plain.org::*H",
 12    ]
 13
 14    static let header = "#+LINK: gh https://github.com/%s\n#+LINK: wiki https://en.wikipedia.org/wiki/\n"
 15
 16    static func emacsParse() throws -> [String] {
 17        let text = header + links.map { "- " + $0 + "\n" }.joined()
 18        return try EmacsOracle.evaluate(text, """
 19            (let (out)
 20              (goto-char (point-min))
 21              (forward-line 2)
 22              (while (not (eobp))
 23                (forward-char 2)
 24                (let ((l (org-element-link-parser)))
 25                  (push (format "%s|%s|%s|%s" (org-element-property :type l) (org-element-property :path l)
 26                                (or (org-element-property :search-option l) "-") (org-element-property :raw-link l)) out))
 27                (forward-line 1))
 28              (nreverse out))
 29            """)
 30    }
 31
 32    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 33    func parsesLikeOrgElement() throws {
 34        let emacs = try Self.emacsParse()
 35        let text = Self.header + Self.links.map { "- " + $0 + "\n" }.joined()
 36        let tree = OrgParser.parse(text)
 37        let ns = text as NSString
 38        var ours: [String] = []
 39        for link in Self.links {
 40            let offset = ns.range(of: "- " + link).location + 3
 41            guard let found = Links.link(at: offset, text: text, tree: tree) else { ours.append("none"); continue }
 42            let l = found.link
 43            ours.append("\(l.type)|\(l.path)|\(l.searchOption ?? "-")|\(l.raw)")
 44        }
 45        #expect(ours == emacs)
 46    }
 47
 48    static let searchText = """
 49        #+TITLE: Search
 50        * First heading
 51        Body with <<a target>> and <<<radio>>>.
 52        * TODO [#A] Second [1/2] heading :tag:
 53        :PROPERTIES:
 54        :CUSTOM_ID: second
 55        :END:
 56        #+NAME: my table
 57        | a |
 58        * COMMENT Third
 59        ** Nested heading
 60
 61        """
 62
 63    static let searches = [
 64        "a target", "A   Target", "my table", "Second heading", "*Second heading", "#second", "#missing", "Third", "nested heading",
 65        "radio", "no such thing", "*a target", "(ref)", "/re/",
 66    ]
 67
 68    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 69    func searchesLikeOrgLinkSearch() throws {
 70        let quoted = Self.searches.map { "\"" + $0.replacingOccurrences(of: "\"", with: "\\\"") + "\"" }.joined(separator: " ")
 71        let emacs = try EmacsOracle.evaluate(Self.searchText, """
 72            (let ((org-link-search-must-match-exact-headline t) out)
 73              (dolist (s (list \(quoted)))
 74                (goto-char (point-min))
 75                (push (condition-case err (progn (org-link-search s) (format "at %d" (point)))
 76                        (error (error-message-string err)))
 77                      out))
 78              (nreverse out))
 79            """)
 80        let tree = OrgParser.parse(Self.searchText)
 81        for (s, expected) in zip(Self.searches, emacs) {
 82            let ours: String = switch Links.search(s, text: Self.searchText, tree: tree) {
 83            case .found(let offset): "at \(EmacsOracle.point(offset, in: Self.searchText))"
 84            case .failed(let message): message
 85            case .occur(let regexp): "occur \(regexp)"
 86            }
 87            // Org opens a sparse tree for regexps.
 88            if s == "/re/" {
 89                #expect(ours == "occur re")
 90                continue
 91            }
 92            #expect(ours == expected, "\(s)")
 93        }
 94    }
 95
 96    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 97    func followsRadioLinksLikeOrg() throws {
 98        let text = "* A\nSome <<<Radio  Target>>> here.\n* B\nThen radio\ntarget again, and RADIO TARGET.\n"
 99        let tree = OrgParser.parse(text)
100        let ns = text as NSString
101        let offsets = [ns.range(of: "radio\ntarget").location + 1, ns.range(of: "RADIO TARGET").location + 2]
102        let emacs = try EmacsOracle.run(offsets.map { EmacsOracle.Case(text: text, point: EmacsOracle.point($0, in: text), form: "(org-open-at-point)") })
103        for (offset, theirs) in zip(offsets, emacs) {
104            let link = try #require(Links.link(at: offset, text: text, tree: tree)?.link)
105            #expect(link.type == "radio")
106            #expect(Links.searchRadio(link.path, tree: tree) == .found(EmacsOracle.offset(theirs.point, in: theirs.text)), "\(theirs)")
107        }
108        #expect(Links.searchRadio("elsewhere", tree: tree) == .failed("No match for radio target: elsewhere"))
109    }
110
111    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
112    func findsAttachmentsLikeOrgAttach() throws {
113        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-\(UUID().uuidString)")
114        defer { try? FileManager.default.removeItem(at: folder) }
115        for dir in ["top", "files", "data/3f/2a77c0-1111", "data/202601/05T101010"] {
116            try FileManager.default.createDirectory(at: folder.appendingPathComponent(dir), withIntermediateDirectories: true)
117        }
118        let text = """
119            :PROPERTIES:
120            :DIR: top
121            :END:
122            [[attachment:t.txt]]
123            * Dir
124            :PROPERTIES:
125            :DIR: files
126            :END:
127            [[attachment:a.txt::3]]
128            * By ID
129            :PROPERTIES:
130            :ID: 3f2a77c0-1111
131            :END:
132            [[attachment:b.txt]]
133            ** Child without its own
134            [[attachment:inherit.txt]]
135            * Missing
136            :PROPERTIES:
137            :ID: zz99-none
138            :END:
139            [[attachment:c.txt]]
140            * Timestamp ID
141            :PROPERTIES:
142            :ID: 20260105T101010
143            :END:
144            [[attachment:sub/d.txt]]
145
146            """
147        let file = folder.appendingPathComponent("notes.org").path
148        try text.write(toFile: file, atomically: true, encoding: .utf8)
149        let ns = text as NSString
150        let offsets = ["t.txt", "a.txt", "b.txt", "inherit.txt", "c.txt", "d.txt"].map { ns.range(of: $0).location }
151        let points = offsets.map { String(EmacsOracle.point($0, in: text)) }.joined(separator: " ")
152        let output = try EmacsOracle.run(["-Q", "--batch", "--eval", """
153            (progn (require 'org) (require 'org-attach)
154              (with-current-buffer (find-file-noselect "\(file)")
155                (dolist (p '(\(points)))
156                  (goto-char p)
157                  (princ (format "%s\\n" (org-attach-expand (org-element-property :path (org-element-context))))))))
158            """])
159        let emacs = output.split(separator: "\n").map(String.init).filter { $0.hasPrefix("/") }
160        let tree = OrgParser.parse(text)
161        let ours = offsets.map { offset -> String in
162            guard let link = Links.link(at: offset, text: text, tree: tree)?.link,
163                  let target = Links.attachmentFile(link, tree: tree, path: file, isDirectory: { path in
164                      var directory: ObjCBool = false
165                      return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
166                  }) else { return "none" }
167            return target.path + (target.searchOption.map { "::" + $0 } ?? "")
168        }
169        #expect(ours == emacs, "\(output)")
170    }
171}