Sources/OrgApp/ICalendarFiles.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgApp/ICalendarFiles.swift history · blame · raw

44 lines · 2644 bytes

4 symbols in this file
 1import Foundation
 2import OrgCore
 3
 4/// Writing iCalendar files: one file or subtree (`org-icalendar-export-to-ics`), each agenda
 5/// file beside itself (`org-icalendar-export-agenda-files`), or all of them in one
 6/// (`org-icalendar-combine-agenda-files`).
 7public enum ICalendarFiles {
 8    /// Exports `text`, the file at `path`, to `destination` or where `EXPORT_FILE_NAME` says,
 9    /// else beside it. `subtree` exports the subtree at that offset alone.
10    @discardableResult
11    public static func export(
12        _ text: String, path: String, settings: OrgSettings, options: ICalendarOptions, subtree: Int? = nil, destination: URL? = nil
13    ) throws -> URL {
14        let target = destination ?? ExportScope.output(
15            for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: subtree, settings: settings), extension: "ics")
16        let text = ExportPreprocess.includes(text, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
17        let calendar = ICalendarExport.calendar(text, name: (path as NSString).lastPathComponent, settings: settings, options: options, subtree: subtree)
18        try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
19        try calendar.write(to: target, atomically: true, encoding: .utf8)
20        return target
21    }
22
23    /// Each file in `paths` to its own calendar. `read` gives a file's text and settings.
24    public static func exportEach(_ paths: [String], options: ICalendarOptions, read: (String) -> (text: String, settings: OrgSettings)?) throws -> [URL] {
25        try paths.compactMap { path in
26            guard let file = read(path) else { return nil }
27            return try export(file.text, path: path, settings: file.settings, options: options)
28        }
29    }
30
31    /// The files in `paths` in one calendar at `destination`.
32    @discardableResult
33    public static func combine(
34        _ paths: [String], to destination: String, options: ICalendarOptions, read: (String) -> (text: String, settings: OrgSettings)?
35    ) throws -> URL {
36        let files = paths.compactMap { path in
37            read(path).map { ((path as NSString).lastPathComponent, ExportPreprocess.includes($0.text, directory: URL(fileURLWithPath: path).deletingLastPathComponent()), $0.settings) }
38        }
39        let url = URL(fileURLWithPath: destination)
40        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
41        try ICalendarExport.combined(files, options: options).write(to: url, atomically: true, encoding: .utf8)
42        return url
43    }
44}