Tests/OrgAppTests/PublishTests.swift

361 lines · 20433 bytes

15 symbols in this file
  1import Foundation
  2import Testing
  3@testable import OrgApp
  4import OrgCore
  5
  6/// `org-publish` against Emacs: sitemaps and the files published.
  7struct PublishTests {
  8    static let files: [(String, String, TimeInterval)] = [
  9        ("a.org", "#+TITLE: Zeta page\n#+DATE: <2026-01-05 Mon>\n* H\nText [[file:sub/b.org][b]].\n", 1_780_000_000),
 10        ("b2.org", "#+TITLE: Alpha\n", 1_780_000_300),
 11        ("sub/b.org", "#+TITLE: Beta\n#+TITLE: two\n* B\n", 1_780_000_200),
 12        ("sub/deep/c.org", "no title\n", 1_780_000_100),
 13        ("other/z.org", "#+TITLE: alpha lower\n", 1_780_000_400),
 14        ("draft-x.org", "#+TITLE: Draft\n", 1_780_000_500),
 15        ("style.css", "body{}", 1_780_000_600),
 16        ("img/logo.png", "png", 1_780_000_700),
 17        (".hidden.org", "#+TITLE: Hidden\n", 1_780_000_800),
 18    ]
 19
 20    static func tree(_ folder: URL) throws {
 21        for (path, text, time) in files {
 22            let url = folder.appendingPathComponent("src").appendingPathComponent(path)
 23            try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
 24            try text.write(to: url, atomically: true, encoding: .utf8)
 25            try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: time)], ofItemAtPath: url.path)
 26        }
 27    }
 28
 29    /// Projects as config.toml writes them and as Lisp, over `folder`.
 30    static func projects(_ folder: String) -> (toml: String, lisp: String) {
 31        let toml = """
 32        fill-column = 80
 33
 34        [[publish]]
 35        name = "site"
 36        base-directory = "\(folder)/src"
 37        publishing-directory = "\(folder)/out"
 38        recursive = true
 39        exclude = "^draft-"
 40        auto-sitemap = true
 41        sitemap-title = "Site"
 42
 43        [[publish]]
 44        name = "list"
 45        base-directory = "\(folder)/src"
 46        publishing-directory = "\(folder)/out2"
 47        recursive = true
 48        auto-sitemap = true
 49        sitemap-filename = "index.org"
 50        sitemap-style = "list"
 51        sitemap-sort-folders = "first"
 52
 53        [[publish]]
 54        name = "dated"
 55        base-directory = "\(folder)/src"
 56        publishing-directory = "\(folder)/out3"
 57        include = "sub/b.org"
 58        auto-sitemap = true
 59        sitemap-filename = "dated.org"
 60        sitemap-style = "list"
 61        sitemap-sort-files = "anti-chronologically"
 62        publishing-function = "org-md-publish-to-md"
 63
 64        [[publish]]
 65        name = "static"
 66        base-directory = "\(folder)/src"
 67        base-extension = "css\\\\|png"
 68        recursive = true
 69        publishing-directory = "\(folder)/out"
 70        publishing-function = "org-publish-attachment"
 71
 72        [[publish]]
 73        name = "all"
 74        components = "site list dated static"
 75        """
 76        let lisp = """
 77        '(("site" :base-directory "\(folder)/src" :publishing-directory "\(folder)/out" :recursive t :exclude "^draft-" :auto-sitemap t :sitemap-title "Site")
 78          ("list" :base-directory "\(folder)/src" :publishing-directory "\(folder)/out2" :recursive t :auto-sitemap t :sitemap-filename "index.org" :sitemap-style list :sitemap-sort-folders first)
 79          ("dated" :base-directory "\(folder)/src" :publishing-directory "\(folder)/out3" :include ("sub/b.org") :auto-sitemap t :sitemap-filename "dated.org" :sitemap-style list :sitemap-sort-files anti-chronologically :publishing-function org-md-publish-to-md)
 80          ("static" :base-directory "\(folder)/src" :base-extension "css\\\\|png" :recursive t :publishing-directory "\(folder)/out" :publishing-function org-publish-attachment)
 81          ("all" :components ("site" "list" "dated" "static")))
 82        """
 83        return (toml, lisp)
 84    }
 85
 86    static func listing(_ folder: URL) -> [String] {
 87        let base = folder.path + "/"
 88        let enumerator = FileManager.default.enumerator(atPath: folder.path)
 89        var out: [String] = []
 90        while let path = enumerator?.nextObject() as? String {
 91            var isDirectory: ObjCBool = false
 92            if FileManager.default.fileExists(atPath: base + path, isDirectory: &isDirectory), !isDirectory.boolValue, !path.hasPrefix("ts/") { out.append(path) }
 93        }
 94        return out.sorted()
 95    }
 96
 97    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 98    func publishesLikeOrg() throws {
 99        let emacsFolder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-e-\(UUID().uuidString)").resolvingSymlinksInPath()
100        let ourFolder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-o-\(UUID().uuidString)").resolvingSymlinksInPath()
101        defer {
102            try? FileManager.default.removeItem(at: emacsFolder)
103            try? FileManager.default.removeItem(at: ourFolder)
104        }
105        try Self.tree(emacsFolder)
106        try Self.tree(ourFolder)
107        let form = """
108        (progn
109          (require 'ox-publish) (require 'ox-md)
110          (setq org-publish-timestamp-directory "\(emacsFolder.path)/ts/"
111                org-publish-project-alist \(Self.projects(emacsFolder.path).lisp))
112          (org-publish "all" t))
113        """
114        let process = Process()
115        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
116        process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
117        process.standardOutput = FileHandle.nullDevice
118        let errors = Pipe()
119        process.standardError = errors
120        try process.run()
121        let log = errors.fileHandleForReading.readDataToEndOfFile()
122        process.waitUntilExit()
123        #expect(process.terminationStatus == 0, "\(String(decoding: log, as: UTF8.self))")
124
125        let loaded = Publish.projects(fromConfig: Self.projects(ourFolder.path).toml, root: nil)
126        #expect(loaded.problems.isEmpty, "\(loaded.problems)")
127        let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
128        let all = loaded.projects.first { $0.name == "all" }!
129        let report = try Publish.publish([all], all: loaded.projects, force: true, read: read) { function, text, _, _ in function + "\n" + text }
130        #expect(!report.published.isEmpty)
131        for name in ["sitemap.org", "index.org", "dated.org"] {
132            let theirs = try String(contentsOf: emacsFolder.appendingPathComponent("src/" + name), encoding: .utf8)
133            let ours = try String(contentsOf: ourFolder.appendingPathComponent("src/" + name), encoding: .utf8)
134            #expect(ours == theirs, "\(name)\nours:\n\(ours)\nemacs:\n\(theirs)")
135        }
136        #expect(Self.listing(ourFolder) == Self.listing(emacsFolder))
137    }
138
139    /// `org-latex-publish-to-latex`: the same `.tex` files as Emacs writes, the `% Created`
140    /// line and the labels aside.
141    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
142    func publishesLaTeXLikeOrg() throws {
143        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-tex-\(UUID().uuidString)").resolvingSymlinksInPath()
144        defer { try? FileManager.default.removeItem(at: folder) }
145        let sources = ["a.org": "#+TITLE: A\n* One\nText with a [[https://orgmode.org][link]].\n", "sub/b.org": "#+OPTIONS: toc:nil\n- item\n- [X] done\n"]
146        for (path, text) in sources {
147            let url = folder.appendingPathComponent("src/" + path)
148            try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
149            try text.write(to: url, atomically: true, encoding: .utf8)
150        }
151        let form = """
152        (progn
153          (require 'ox-publish) (require 'ox-latex)
154          (setq user-full-name "A. Writer"
155                org-publish-timestamp-directory "\(folder.path)/ts/"
156                org-publish-project-alist '(("tex" :base-directory "\(folder.path)/src" :publishing-directory "\(folder.path)/emacs"
157                                             :recursive t :publishing-function org-latex-publish-to-latex)))
158          (org-publish "tex" t))
159        """
160        let process = Process()
161        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
162        process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
163        process.standardOutput = FileHandle.nullDevice
164        process.standardError = FileHandle.nullDevice
165        try process.run()
166        process.waitUntilExit()
167
168        let toml = """
169        [[publish]]
170        name = "tex"
171        base-directory = "\(folder.path)/src"
172        publishing-directory = "\(folder.path)/ours"
173        recursive = true
174        publishing-function = "org-latex-publish-to-latex"
175        """
176        let loaded = Publish.projects(fromConfig: toml, root: nil)
177        #expect(loaded.problems.isEmpty, "\(loaded.problems)")
178        let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
179        let report = try Publish.publish(loaded.projects, all: loaded.projects, force: true, read: read) { _, text, path, bodyOnly in
180            try LaTeXExport.document(text, path: path, bodyOnly: bodyOnly, author: "A. Writer", file: true)
181        }
182        #expect(report.published.count == 2)
183        func normalized(_ s: String) -> String {
184            var labels: [String: String] = [:]
185            return s.replacing(#/(?m)^% Created .*\n/#, with: "").replacing(#/org[0-9a-f]{7}/#) { m in
186                let key = String(m.output)
187                if labels[key] == nil { labels[key] = "org\(labels.count + 1)" }
188                return labels[key]!
189            }
190        }
191        for path in ["a.tex", "sub/b.tex"] {
192            let theirs = try String(contentsOf: folder.appendingPathComponent("emacs/" + path), encoding: .utf8)
193            let ours = try String(contentsOf: folder.appendingPathComponent("ours/" + path), encoding: .utf8)
194            #expect(normalized(ours) == normalized(theirs), "\(path)\nours:\n\(ours)\nemacs:\n\(theirs)")
195        }
196    }
197
198    /// `org-ascii-publish-to-ascii`: the same `.txt` files as Emacs writes.
199    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
200    func publishesASCIILikeOrg() throws {
201        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-txt-\(UUID().uuidString)").resolvingSymlinksInPath()
202        defer { try? FileManager.default.removeItem(at: folder) }
203        let sources = ["a.org": "#+TITLE: A\n* One\nText with a [[https://orgmode.org][link]].\n| x | y |\n", "sub/b.org": "#+OPTIONS: toc:nil\n- item\n- [X] done\n"]
204        for (path, text) in sources {
205            let url = folder.appendingPathComponent("src/" + path)
206            try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
207            try text.write(to: url, atomically: true, encoding: .utf8)
208        }
209        let form = """
210        (progn
211          (require 'ox-publish) (require 'ox-ascii)
212          (setq user-full-name "A. Writer"
213                org-publish-timestamp-directory "\(folder.path)/ts/"
214                org-publish-project-alist '(("txt" :base-directory "\(folder.path)/src" :publishing-directory "\(folder.path)/emacs"
215                                             :recursive t :publishing-function org-ascii-publish-to-ascii)))
216          (org-publish "txt" t))
217        """
218        let process = Process()
219        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
220        process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
221        process.standardOutput = FileHandle.nullDevice
222        process.standardError = FileHandle.nullDevice
223        try process.run()
224        process.waitUntilExit()
225
226        let toml = """
227        [[publish]]
228        name = "txt"
229        base-directory = "\(folder.path)/src"
230        publishing-directory = "\(folder.path)/ours"
231        recursive = true
232        publishing-function = "org-ascii-publish-to-ascii"
233        """
234        let loaded = Publish.projects(fromConfig: toml, root: nil)
235        #expect(loaded.problems.isEmpty, "\(loaded.problems)")
236        let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
237        let report = try Publish.publish(loaded.projects, all: loaded.projects, force: true, read: read) { _, text, path, bodyOnly in
238            try ASCIIExport.document(text, path: path, bodyOnly: bodyOnly, author: "A. Writer", file: true)
239        }
240        #expect(report.published.count == 2)
241        for path in ["a.txt", "sub/b.txt"] {
242            let theirs = try String(contentsOf: folder.appendingPathComponent("emacs/" + path), encoding: .utf8)
243            let ours = try String(contentsOf: folder.appendingPathComponent("ours/" + path), encoding: .utf8)
244            #expect(ours == theirs, "\(path)\nours:\n\(ours)\nemacs:\n\(theirs)")
245        }
246    }
247
248    /// `org-odt-publish-to-odt` writes `.odt` files, which the export closure doesn't see.
249    @Test func publishesODT() throws {
250        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)")
251        defer { try? FileManager.default.removeItem(at: folder) }
252        try Self.tree(folder)
253        let config = "[[publish]]\nname = \"odt\"\nbase-directory = \"\(folder.path)/src\"\npublishing-directory = \"\(folder.path)/odt\"\npublishing-function = \"org-odt-publish-to-odt\"\n"
254        let loaded = Publish.projects(fromConfig: config, root: nil)
255        #expect(loaded.problems.isEmpty)
256        let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
257        let report = try Publish.publish(loaded.projects, all: loaded.projects, read: read) { _, _, _, _ in Issue.record("exported as text"); return "" }
258        #expect(report.published.count == 3)
259        let data = try Data(contentsOf: folder.appendingPathComponent("odt/a.odt"))
260        #expect(data.prefix(4) == Data([0x50, 0x4b, 0x03, 0x04]))
261        #expect(String(decoding: data[30..<38], as: UTF8.self) == "mimetype")
262    }
263
264    /// The ODT author comes from the caller: iOS passes none, as its Export menu does.
265    @Test func publishesODTWithTheCallersAuthor() throws {
266        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)")
267        defer { try? FileManager.default.removeItem(at: folder) }
268        try Self.tree(folder)
269        let config = "[[publish]]\nname = \"odt\"\nbase-directory = \"\(folder.path)/src\"\npublishing-directory = \"\(folder.path)/odt\"\npublishing-function = \"org-odt-publish-to-odt\"\n"
270        let loaded = Publish.projects(fromConfig: config, root: nil)
271        let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
272        let odt = folder.appendingPathComponent("odt/a.odt")
273        _ = try Publish.publish(loaded.projects, all: loaded.projects, author: "Quill Writer", read: read) { _, _, _, _ in "" }
274        #expect(try Data(contentsOf: odt).range(of: Data("Quill Writer".utf8)) != nil)
275        _ = try Publish.publish(loaded.projects, all: loaded.projects, force: true, author: "", read: read) { _, _, _, _ in "" }
276        #expect(try Data(contentsOf: odt).range(of: Data("Quill Writer".utf8)) == nil)
277    }
278
279    @Test func skipsUpToDateFilesAndFindsProjects() throws {
280        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)").resolvingSymlinksInPath()
281        defer { try? FileManager.default.removeItem(at: folder) }
282        try Self.tree(folder)
283        let loaded = Publish.projects(fromConfig: Self.projects(folder.path).toml, root: nil)
284        let site = loaded.projects.first { $0.name == "site" }!
285        let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
286        let first = try Publish.publish([site], all: loaded.projects, read: read) { _, text, _, _ in text }
287        let second = try Publish.publish([site], all: loaded.projects, read: read) { _, text, _, _ in text }
288        #expect(!first.published.isEmpty && second.published.isEmpty && second.skipped.count == first.published.count)
289        let a = folder.path + "/src/a.org"
290        #expect(Publish.projects(containing: a, in: loaded.projects).map(\.name) == ["site", "list", "dated"])
291        let one = try Publish.publish([site], all: loaded.projects, force: true, only: a, read: read) { _, text, _, _ in text }
292        #expect(one.published == [a])
293        #expect(Publish.projects(fromConfig: "[[publish]]\nname = \"x\"\n", root: nil).problems.count == 1)
294        #expect(throws: Publish.Failure.self) { try Publish.expand([PublishProject(name: "m")].map { var p = $0; p.components = ["nope"]; return p }, all: []) }
295    }
296
297    /// The exporter both apps publish with: each function's format, and the file named in a
298    /// refusal.
299    @Test func exportsByFunction() throws {
300        let path = "/notes/a.org"
301        let text = "#+TITLE: A\n* One\nText.\n"
302        func export(_ function: String) throws -> String {
303            try Publish.export(function, text: text, path: path, bodyOnly: false, settings: .default, codeStyle: nil, author: "A. Writer", language: "en")
304        }
305        #expect(try export("org-html-publish-to-html").contains("<title>A</title>"))
306        #expect(try export("org-md-publish-to-md").contains("# One"))
307        #expect(try export("org-latex-publish-to-latex").contains("\\title{A}"))
308        #expect(try export("org-ascii-publish-to-ascii").contains("1 One"))
309        #expect(throws: LaTeXExport.Unsupported(reason: "Can't export a.org to LaTeX: Radio targets")) {
310            try Publish.export("org-latex-publish-to-latex", text: "<<<radio>>> radio\n", path: path, bodyOnly: false, settings: .default, codeStyle: nil, author: "", language: "en")
311        }
312    }
313}
314
315/// Publishing on iOS: a project that publishes outside the app's folders writes to the folder
316/// chosen for it, kept as a bookmark.
317@MainActor
318struct PublishFoldersTests {
319    @Test func publishesToTheBookmarkedFolder() throws {
320        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-ios-\(UUID().uuidString)").resolvingSymlinksInPath()
321        defer { try? FileManager.default.removeItem(at: folder) }
322        try PublishTests.tree(folder)
323        let chosen = folder.appendingPathComponent("chosen")
324        try FileManager.default.createDirectory(at: chosen, withIntermediateDirectories: true)
325        let config = """
326        [[publish]]
327        name = "site"
328        base-directory = "src"
329        publishing-directory = "~/public_html"
330
331        [[publish]]
332        name = "inside"
333        base-directory = "src"
334        publishing-directory = "src/out"
335
336        [[publish]]
337        name = "both"
338        components = "site inside"
339        """
340        let root = folder.path
341        let loaded = Publish.projects(fromConfig: config, root: root)
342        let defaults = TestDefaults("orgstar-publish")
343        let folders = PublishFolders(defaults: defaults, sandboxed: false)
344        let both = loaded.projects.first { $0.name == "both" }!
345        #expect(try folders.needed([both], all: loaded.projects, roots: [root]).map(\.name) == ["site"])
346        #expect(folders.set(chosen, for: "site"))
347
348        // After a relaunch, the bookmark gives the folder back.
349        let again = PublishFolders(defaults: defaults, sandboxed: false)
350        #expect(again.folder(for: "site")?.standardizedFileURL == chosen.standardizedFileURL)
351        #expect(try again.needed([both], all: loaded.projects, roots: [root]).isEmpty)
352        let projects = again.applied(to: loaded.projects)
353        let site = projects.first { $0.name == "site" }!
354        #expect(URL(fileURLWithPath: site.publishingDirectory).standardizedFileURL == chosen.standardizedFileURL)
355        #expect(projects.first { $0.name == "inside" }?.publishingDirectory == root + "/src/out")
356        let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
357        let report = try Publish.publish([site], all: projects, read: read) { _, text, _, _ in text }
358        #expect(!report.published.isEmpty)
359        #expect(FileManager.default.fileExists(atPath: chosen.appendingPathComponent("a.html").path))
360    }
361}