Sources/OrgApp/Publish.swift

360 lines · 19679 bytes

26 symbols in this file
  1import Foundation
  2import OrgCore
  3
  4/// A publishing project from config.toml (`org-publish-project-alist`, ox-publish.el, Org 9.8.7):
  5///
  6/// ```toml
  7/// [[publish]]
  8/// name = "site"
  9/// base-directory = "~/notes"
 10/// publishing-directory = "~/public_html"
 11/// recursive = true
 12/// auto-sitemap = true
 13/// ```
 14///
 15/// Other keys: `base-extension` (an Emacs regexp, or `any`), `exclude` (a regexp on the path
 16/// under the base directory), `include` (file names separated by spaces), `publishing-function`
 17/// (`org-html-publish-to-html`, `org-md-publish-to-md`, `org-odt-publish-to-odt`,
 18/// `org-publish-attachment`, separated by spaces), `sitemap-filename`, `sitemap-title`, `sitemap-style` (`tree` or `list`),
 19/// `sitemap-sort-files` (`alphabetically`, `chronologically`, `anti-chronologically`, `nil`),
 20/// `sitemap-sort-folders` (`ignore`, `first`, `last`, `nil`), `sitemap-ignore-case`,
 21/// `body-only`, and `components` (project names separated by spaces) for a project of projects.
 22public struct PublishProject: Sendable, Equatable {
 23    public var name: String
 24    public var baseDirectory = ""
 25    public var publishingDirectory = ""
 26    public var baseExtension = "org"
 27    public var recursive = false
 28    public var exclude: String?
 29    public var include: [String] = []
 30    public var publishingFunctions = ["org-html-publish-to-html"]
 31    public var autoSitemap = false
 32    public var sitemapFilename = "sitemap.org"
 33    public var sitemapTitle: String?
 34    public var sitemapStyle = "tree"
 35    public var sitemapSortFiles = "alphabetically"
 36    public var sitemapSortFolders = "ignore"
 37    public var sitemapIgnoreCase = false
 38    public var bodyOnly = false
 39    public var components: [String] = []
 40
 41    public init(name: String) { self.name = name }
 42
 43    public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-latex-publish-to-latex", "org-odt-publish-to-odt", "org-ascii-publish-to-ascii", "org-publish-attachment"]
 44}
 45
 46public enum Publish {
 47    /// The `[[publish]]` tables of a config.toml, directories resolved against `root`.
 48    public static func projects(fromConfig text: String, root: String?) -> (projects: [PublishProject], problems: [String]) {
 49        guard let tables = try? TOML.parse(text) else { return ([], []) }
 50        var projects: [PublishProject] = []
 51        var problems: [String] = []
 52        for table in tables where table.name == "publish" {
 53            let v = table.values
 54            guard let name = v["name"]?.string, !name.isEmpty else {
 55                problems.append("config.toml line \(table.line): a [[publish]] project needs a name")
 56                continue
 57            }
 58            var p = PublishProject(name: name)
 59            func words(_ key: String) -> [String]? { v[key]?.string.map { $0.split(whereSeparator: \.isWhitespace).map(String.init) } }
 60            p.components = words("components") ?? []
 61            if p.components.isEmpty {
 62                guard let base = v["base-directory"]?.string, let out = v["publishing-directory"]?.string else {
 63                    problems.append("config.toml line \(table.line): project \(name) needs base-directory and publishing-directory")
 64                    continue
 65                }
 66                p.baseDirectory = resolve(base, root: root)
 67                p.publishingDirectory = resolve(out, root: root)
 68            }
 69            if let ext = v["base-extension"]?.string { p.baseExtension = ext }
 70            p.recursive = v["recursive"]?.bool ?? false
 71            p.exclude = v["exclude"]?.string
 72            p.include = words("include") ?? []
 73            if let functions = words("publishing-function") {
 74                let unknown = functions.filter { !PublishProject.functions.contains($0) }
 75                if !unknown.isEmpty { problems.append("config.toml line \(table.line): unknown publishing-function \(unknown.joined(separator: " "))") }
 76                p.publishingFunctions = functions.filter(PublishProject.functions.contains)
 77            }
 78            p.autoSitemap = v["auto-sitemap"]?.bool ?? false
 79            if let s = v["sitemap-filename"]?.string { p.sitemapFilename = s }
 80            p.sitemapTitle = v["sitemap-title"]?.string
 81            if let s = v["sitemap-style"]?.string { p.sitemapStyle = s }
 82            if let s = v["sitemap-sort-files"]?.string { p.sitemapSortFiles = s }
 83            if let s = v["sitemap-sort-folders"]?.string { p.sitemapSortFolders = s }
 84            p.sitemapIgnoreCase = v["sitemap-ignore-case"]?.bool ?? false
 85            p.bodyOnly = v["body-only"]?.bool ?? false
 86            projects.append(p)
 87        }
 88        return (projects, problems)
 89    }
 90
 91    /// Absolute, `~/…`, or relative to `root`.
 92    static func resolve(_ path: String, root: String?) -> String {
 93        if path.hasPrefix("/") { return path }
 94        if path.hasPrefix("~") { return OrgPaths.expandingTilde(path) }
 95        return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(path)
 96    }
 97
 98    public struct Failure: Error, Equatable, CustomStringConvertible {
 99        public let description: String
100    }
101
102    /// `org-publish-expand-projects`: components in place of projects of projects.
103    public static func expand(_ chosen: [PublishProject], all: [PublishProject]) throws -> [PublishProject] {
104        var rest = chosen
105        var out: [PublishProject] = []
106        while !rest.isEmpty {
107            let p = rest.removeFirst()
108            if p.components.isEmpty {
109                if !out.contains(where: { $0.name == p.name }) { out.append(p) }
110                continue
111            }
112            rest = try p.components.map { name in
113                guard let c = all.first(where: { $0.name == name }) else { throw Failure(description: "Unknown component \"\(name)\" in project \"\(p.name)\"") }
114                return c
115            } + rest
116        }
117        return out
118    }
119
120    static func directory(_ path: String) -> String { path.hasSuffix("/") ? path : path + "/" }
121
122    /// `org-publish-get-base-files`: the project's files, its sitemap and `include`.
123    public static func baseFiles(_ p: PublishProject) -> [String] {
124        let base = directory(p.baseDirectory)
125        let pattern = p.baseExtension == "any" ? "" : "^[^.].*\\.(?:" + EmacsRegex.translate(p.baseExtension) + ")$"
126        let regex = try? NSRegularExpression(pattern: pattern)
127        func matches(_ name: String) -> Bool {
128            regex?.firstMatch(in: name, range: NSRange(location: 0, length: (name as NSString).length)) != nil
129        }
130        var files: [String] = []
131        let fm = FileManager.default
132        func walk(_ dir: String, depth: Int) {
133            guard depth <= 100, let names = try? fm.contentsOfDirectory(atPath: dir) else { return }
134            for name in names.sorted() {
135                let path = dir + name
136                var isDirectory: ObjCBool = false
137                guard fm.fileExists(atPath: path, isDirectory: &isDirectory) else { continue }
138                if isDirectory.boolValue {
139                    if p.recursive { walk(path + "/", depth: depth + 1) }
140                } else if matches(name) {
141                    files.append(path)
142                }
143            }
144        }
145        walk(base, depth: 0)
146        if let exclude = p.exclude, let regex = try? NSRegularExpression(pattern: EmacsRegex.translate(exclude)) {
147            files.removeAll { file in
148                let relative = String(file.dropFirst(base.count))
149                return regex.firstMatch(in: relative, range: NSRange(location: 0, length: (relative as NSString).length)) != nil
150            }
151        }
152        if p.autoSitemap { files.append(base + p.sitemapFilename) }
153        files += p.include.map { $0.hasPrefix("/") ? $0 : base + $0 }
154        var seen: Set<String> = []
155        return files.filter { seen.insert($0).inserted }
156    }
157
158    // MARK: - Sitemap
159
160    /// `org-publish-find-title`: `#+TITLE`, or the file's base name.
161    static func title(_ path: String, read: (String) -> String?) -> String {
162        let titles = (read(path) ?? "").matches(of: #/(?mi)^[ \t]*#\+TITLE:[ \t]*(.*?)[ \t]*$/#).map { String($0.1) }
163        return titles.isEmpty ? ((path as NSString).lastPathComponent as NSString).deletingPathExtension : titles.joined(separator: " ")
164    }
165
166    /// `org-publish-find-date`: a timestamp in `#+DATE`, or the modification time.
167    static func date(_ path: String, read: (String) -> String?) -> Date {
168        if !path.hasSuffix("/"), let text = read(path),
169           let line = text.firstMatch(of: #/(?mi)^[ \t]*#\+DATE:[ \t]*(.*?)[ \t]*$/#),
170           let m = String(line.1).firstMatch(of: /[<\[][0-9]{4}-[0-9]{2}-[0-9]{2}[^>\]]*[>\]]/), let stamp = Timestamp.parse(m.0) {
171            let p = stamp.start
172            return Calendar.current.date(from: DateComponents(year: p.year, month: p.month, day: p.day, hour: p.hour ?? 0, minute: p.minute ?? 0)) ?? Date()
173        }
174        return (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date) ?? Date()
175    }
176
177    /// `org-publish-sitemap` with the default entry format and builder: the sitemap's text.
178    public static func sitemap(_ p: PublishProject, read: (String) -> String?) -> String {
179        let root = directory(p.baseDirectory)
180        let sitemapPath = root + p.sitemapFilename
181        var files = baseFiles(p).filter { $0 != sitemapPath }
182        if !(p.sitemapStyle == "list" && p.sitemapSortFolders == "ignore") {
183            var seen: Set<String> = []
184            let dirs = files.map { ($0 as NSString).deletingLastPathComponent + "/" }.filter { $0 != root && seen.insert($0).inserted }
185            files = dirs + files
186        }
187        if p.sitemapSortFiles != "nil" || p.sitemapSortFolders != "ignore" {
188            files = stableSorted(files) { a, b in before(a, b, p, read: read) }
189        }
190        func entry(_ path: String) -> String {
191            let relative = String(path.dropFirst(root.count))
192            if !path.hasSuffix("/") { return "[[file:\(relative)][\(title(path, read: read))]]" }
193            return p.sitemapStyle == "tree" ? (String(relative.dropLast()) as NSString).lastPathComponent : relative
194        }
195        var lines: [String] = []
196        if p.sitemapStyle == "list" {
197            lines = files.map { "- " + entry($0) }
198        } else {
199            let filesOnly = files.filter { !$0.hasSuffix("/") }
200            let dirs = files.filter { $0.hasSuffix("/") }
201            func subtree(_ dir: String, _ indent: String) {
202                for f in filesOnly where (f as NSString).deletingLastPathComponent + "/" == dir { lines.append(indent + "- " + entry(f)) }
203                for sub in dirs where (String(sub.dropLast()) as NSString).deletingLastPathComponent + "/" == dir {
204                    lines.append(indent + "- " + entry(sub))
205                    subtree(sub, indent + "  ")
206                }
207            }
208            subtree(root, "")
209        }
210        return "#+TITLE: " + (p.sitemapTitle ?? "Sitemap for project " + p.name) + "\n\n" + lines.joined(separator: "\n")
211    }
212
213    /// The sort predicate of `org-publish-sitemap`: whether `a` goes before `b`.
214    static func before(_ a: String, _ b: String, _ p: PublishProject, read: (String) -> String?) -> Bool {
215        var result: Bool?
216        switch p.sitemapSortFiles {
217        case "alphabetically":
218            func key(_ path: String) -> String {
219                guard path.hasSuffix(".org") else { return path }
220                return (path as NSString).deletingLastPathComponent + "/" + title(path, read: read)
221            }
222            var (x, y) = (key(a), key(b))
223            if p.sitemapIgnoreCase { (x, y) = (x.lowercased(), y.lowercased()) }
224            result = Array(x.unicodeScalars).lexicographicallyPrecedes(Array(y.unicodeScalars))
225        case "chronologically", "anti-chronologically":
226            let (x, y) = (date(a, read: read), date(b, read: read))
227            result = p.sitemapSortFiles == "chronologically" ? x < y : y < x
228        default:
229            result = nil
230        }
231        if p.sitemapSortFolders == "first" || p.sitemapSortFolders == "last" {
232            let (da, db) = (a.hasSuffix("/"), b.hasSuffix("/"))
233            if da != db { return da == (p.sitemapSortFolders == "first") }
234        }
235        return result ?? false
236    }
237
238    static func stableSorted<T>(_ items: [T], by before: (T, T) -> Bool) -> [T] {
239        items.enumerated().sorted { x, y in
240            if before(x.element, y.element) { return true }
241            if before(y.element, x.element) { return false }
242            return x.offset < y.offset
243        }.map(\.element)
244    }
245
246    // MARK: - Publishing
247
248    public struct Report: Equatable {
249        public var published: [String] = []
250        public var skipped: [String] = []
251    }
252
253    /// `org-publish-projects`: each project's sitemap, when it has one, then its files, through
254    /// its publishing functions. A file whose output is newer than it is skipped unless `force`.
255    /// `export` turns an Org file's text into the HTML, Markdown, LaTeX or plain text to write;
256    /// ODT is exported here, with `author` for a file without `#+AUTHOR:`.
257    public static func publish(
258        _ chosen: [PublishProject], all: [PublishProject], force: Bool = false, only: String? = nil, author: String = NSFullUserName(),
259        read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
260    ) throws -> Report {
261        var report = Report()
262        let fm = FileManager.default
263        for p in try expand(chosen, all: all) {
264            let base = directory(p.baseDirectory)
265            if p.autoSitemap, only == nil {
266                let text = sitemap(p, read: read)
267                let path = base + p.sitemapFilename
268                if (try? String(contentsOfFile: path, encoding: .utf8)) != text { try text.write(toFile: path, atomically: true, encoding: .utf8) }
269            }
270            for file in baseFiles(p) where only == nil || only == file {
271                let relative = String(file.dropFirst(base.count))
272                let outputDirectory = directory(p.publishingDirectory) + ((relative as NSString).deletingLastPathComponent.isEmpty ? "" : (relative as NSString).deletingLastPathComponent + "/")
273                for function in p.publishingFunctions {
274                    guard let output = try outputPath(file, function: function, in: outputDirectory, read: read) else { continue }
275                    if !force, upToDate(output, source: file) {
276                        report.skipped.append(file)
277                        continue
278                    }
279                    try fm.createDirectory(atPath: (output as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
280                    try write(file, to: output, function: function, bodyOnly: p.bodyOnly, author: author, read: read, export: export)
281                    report.published.append(file)
282                }
283            }
284        }
285        return report
286    }
287
288    /// What `function` makes of `text`, the file at `path`: HTML, Markdown, LaTeX or plain text,
289    /// with `settings` and the file's setup files. The `export` of `publish` on every platform.
290    public static func export(
291        _ function: String, text: String, path: String, bodyOnly: Bool, settings: OrgSettings, codeStyle: HTMLCodeStyle?,
292        author: String = NSFullUserName(), language: String = OrgPreferences.exportLanguage()
293    ) throws -> String {
294        let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
295        let name = (path as NSString).lastPathComponent
296        switch function {
297        case "org-md-publish-to-md":
298            return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly)
299        case "org-latex-publish-to-latex":
300            do {
301                return try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: author, language: language, file: true)
302            } catch let error as LaTeXExport.Unsupported {
303                throw LaTeXExport.Unsupported(reason: "Can't export \(name) to LaTeX: \(error.reason)")
304            }
305        case "org-ascii-publish-to-ascii":
306            do {
307                return try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: author, language: language, file: true)
308            } catch let error as ASCIIExport.Unsupported {
309                throw ASCIIExport.Unsupported(reason: "Can't export \(name) to plain text: \(error.reason)")
310            }
311        default:
312            let base = (name as NSString).deletingPathExtension
313            return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: language)
314        }
315    }
316
317    /// Where `function` publishes `file` in `outputDirectory`; nil for an attachment already there.
318    private static func outputPath(_ file: String, function: String, in outputDirectory: String, read: (String) -> String?) throws -> String? {
319        guard function != "org-publish-attachment" else {
320            if directory((file as NSString).deletingLastPathComponent) == outputDirectory { return nil }
321            return outputDirectory + (file as NSString).lastPathComponent
322        }
323        let ext = ["org-md-publish-to-md": "md", "org-latex-publish-to-latex": "tex", "org-odt-publish-to-odt": "odt", "org-ascii-publish-to-ascii": "txt"][function] ?? "html"
324        guard let text = read(file) else { throw Failure(description: "Can't read \(file)") }
325        return ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent),
326                                  name: ExportScope.fileName(text), extension: ext).path
327    }
328
329    /// Copies an attachment to `output`, or writes what `function` exports from `file`; ODT is
330    /// exported here, with the preferences' settings.
331    private static func write(
332        _ file: String, to output: String, function: String, bodyOnly: Bool, author: String,
333        read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) throws -> String
334    ) throws {
335        let fm = FileManager.default
336        if function == "org-publish-attachment" {
337            if fm.fileExists(atPath: output) { try fm.removeItem(atPath: output) }
338            try fm.copyItem(atPath: file, toPath: output)
339        } else if function == "org-odt-publish-to-odt" {
340            let text = read(file) ?? ""
341            let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: file, read: OrgSettings.readFile)
342            try ODTExport.document(text, settings: settings, path: file, author: author, language: OrgPreferences.exportLanguage())
343                .write(to: URL(fileURLWithPath: output), options: .atomic)
344        } else {
345            try export(function, read(file) ?? "", file, bodyOnly).write(toFile: output, atomically: true, encoding: .utf8)
346        }
347    }
348
349    static func upToDate(_ output: String, source: String) -> Bool {
350        let fm = FileManager.default
351        guard let out = try? fm.attributesOfItem(atPath: output)[.modificationDate] as? Date,
352              let src = try? fm.attributesOfItem(atPath: source)[.modificationDate] as? Date else { return false }
353        return out >= src
354    }
355
356    /// The projects publishing `path`, not counting projects of projects.
357    public static func projects(containing path: String, in all: [PublishProject]) -> [PublishProject] {
358        all.filter { $0.components.isEmpty && baseFiles($0).contains(path) }
359    }
360}