Sources/OrgApp/MarkdownImport.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgApp/MarkdownImport.swift

482 lines · 24270 bytes

27 symbols in this file
  1import Foundation
  2import OrgCore
  3
  4/// File ▸ Import ▸ Markdown Files… and Obsidian Vault…: converts Markdown files to new org
  5/// files in one of the person's folders, leaving the sources alone.
  6///
  7/// A chosen file becomes `name.org` in the destination; a chosen folder or vault becomes a new
  8/// folder of the same name holding its notes at the same relative paths. Names already taken
  9/// get ` 2`, ` 3`… Files a note links to or embeds are copied: a folder's into the new folder
 10/// at the same relative path, a loose file's into `attachments` in the destination. Links
 11/// between notes become `file:` links to the converted files.
 12public enum MarkdownImport {
 13    public enum Kind: Sendable {
 14        case markdown, obsidian
 15    }
 16
 17    public struct Problem: Sendable, Hashable {
 18        public enum Reason: Sendable, Hashable {
 19            case converted(MarkdownImportIssue)
 20            /// Not UTF-8 or unreadable.
 21            case unreadable
 22            /// An Obsidian canvas or base, which has no org equivalent.
 23            case notConverted
 24        }
 25
 26        /// The source file, relative to what was chosen.
 27        public let file: String
 28        public let reason: Reason
 29    }
 30
 31    /// What an import will write, for the preview, and the text to write.
 32    public struct Plan: Sendable {
 33        public let kind: Kind
 34        public let destination: URL
 35        public fileprivate(set) var notes = 0
 36        public fileprivate(set) var headings = 0
 37        public fileprivate(set) var links = 0
 38        public fileprivate(set) var attachments = 0
 39        public fileprivate(set) var problems: [Problem] = []
 40        /// Names chosen instead of the source's because the destination has that name.
 41        public fileprivate(set) var renamed: [(from: String, to: String)] = []
 42
 43        struct Top {
 44            var name: String
 45            let natural: String
 46            let folder: Bool
 47            /// `attachments`, which may already exist and is shared by loose files.
 48            let shared: Bool
 49        }
 50
 51        enum Content {
 52            case text(String)
 53            case copy(URL)
 54        }
 55
 56        struct Output {
 57            let top: Int
 58            /// The path inside the top folder; empty for a loose file.
 59            var inner: String
 60            let content: Content
 61        }
 62
 63        fileprivate var tops: [Top] = []
 64        fileprivate var outputs: [Output] = []
 65    }
 66
 67    // MARK: - Planning
 68
 69    /// A note or attachment in the sources, by where it ends up.
 70    fileprivate struct SourceFile {
 71        let url: URL
 72        /// The chosen item's index.
 73        let top: Int
 74        /// Path below the chosen folder; the file name for a loose file.
 75        let relative: String
 76        let note: Bool
 77    }
 78
 79    static let noteExtensions: Set<String> = ["md", "markdown"]
 80
 81    /// Reads `sources` (files, folders or a vault) and converts every note, choosing names
 82    /// that are free in `destination`. Reads files, so call it off the main actor.
 83    public static func plan(_ kind: Kind, sources: [URL], into destination: URL) throws -> Plan {
 84        var plan = Plan(kind: kind, destination: destination)
 85        let manager = FileManager.default
 86        var takenTop = Set<String>()
 87        var files: [SourceFile] = []
 88        for source in sources {
 89            var isFolder: ObjCBool = false
 90            guard manager.fileExists(atPath: source.path, isDirectory: &isFolder) else { continue }
 91            if isFolder.boolValue {
 92                let natural = source.lastPathComponent
 93                let name = freeName(natural, in: destination, taken: takenTop)
 94                takenTop.insert(name.lowercased())
 95                if name != natural { plan.renamed.append((natural, name)) }
 96                plan.tops.append(Plan.Top(name: name, natural: natural, folder: true, shared: false))
 97                let top = plan.tops.count - 1
 98                for relative in folderFiles(source) {
 99                    let url = source.appendingPathComponent(relative)
100                    let ext = url.pathExtension.lowercased()
101                    if ext == "canvas" || ext == "base" {
102                        plan.problems.append(Problem(file: natural + "/" + relative, reason: .notConverted))
103                    }
104                    files.append(SourceFile(url: url, top: top, relative: relative, note: noteExtensions.contains(ext)))
105                }
106            } else if noteExtensions.contains(source.pathExtension.lowercased()) {
107                let natural = source.deletingPathExtension().lastPathComponent + ".org"
108                let name = freeName(natural, in: destination, taken: takenTop)
109                takenTop.insert(name.lowercased())
110                if name != natural { plan.renamed.append((source.lastPathComponent, name)) }
111                plan.tops.append(Plan.Top(name: name, natural: natural, folder: false, shared: false))
112                files.append(SourceFile(url: source, top: plan.tops.count - 1, relative: source.lastPathComponent, note: true))
113            }
114        }
115
116        // Where each note goes, relative to the destination.
117        var outputPath: [URL: String] = [:]
118        var takenInner: [Int: Set<String>] = [:]
119        for file in files where file.note {
120            let top = plan.tops[file.top]
121            if top.folder {
122                let natural = (file.relative as NSString).deletingPathExtension + ".org"
123                var inner = natural
124                var n = 2
125                while takenInner[file.top, default: []].contains(inner.lowercased()) {
126                    inner = (natural as NSString).deletingPathExtension + " \(n).org"
127                    n += 1
128                }
129                takenInner[file.top, default: []].insert(inner.lowercased())
130                outputPath[file.url.standardizedFileURL] = top.name + "/" + inner
131            } else {
132                outputPath[file.url.standardizedFileURL] = top.name
133            }
134        }
135
136        let collector = Collector()
137        let index = VaultIndex(files: files.filter { plan.tops[$0.top].folder })
138        plan.tops.append(Plan.Top(name: "attachments", natural: "attachments", folder: true, shared: true))
139        let attachmentsTop = plan.tops.count - 1
140
141        // Parse every note first, so links can name headings in other notes.
142        var parsed: [URL: MarkdownToOrg.Parsed] = [:]
143        var texts: [(file: SourceFile, parsed: MarkdownToOrg.Parsed)] = []
144        for file in files where file.note {
145            let label = display(file, plan)
146            guard let data = try? Data(contentsOf: file.url), let text = String(data: data, encoding: .utf8) else {
147                plan.problems.append(Problem(file: label, reason: .unreadable))
148                continue
149            }
150            let result = MarkdownToOrg.parse(text, obsidian: kind == .obsidian)
151            parsed[file.url.standardizedFileURL] = result
152            texts.append((file, result))
153        }
154
155        for (file, note) in texts {
156            let url = file.url.standardizedFileURL
157            guard let own = outputPath[url] else { continue }
158            let ownFolder = (own as NSString).deletingLastPathComponent
159            let label = display(file, plan)
160            let folderTop = plan.tops[file.top].folder ? file.top : nil
161            let context = LinkContext(note: url, own: own, ownFolder: ownFolder, folderTop: folderTop, topName: plan.tops[file.top].name,
162                                      attachmentsTop: plan.tops[attachmentsTop].name, destination: destination,
163                                      outputPath: outputPath, parsed: parsed, index: index, collector: collector, obsidian: kind == .obsidian)
164            let targets = MarkdownTargets(link: { destination, image in context.link(destination, image: image) },
165                                          wikilink: { target, fragment, embed in context.wikilink(target, fragment: fragment, embed: embed) })
166            let title = kind == .obsidian ? url.deletingPathExtension().lastPathComponent : nil
167            let result = MarkdownToOrg.render(note, title: title, targets: targets)
168            plan.notes += 1
169            plan.headings += result.headings
170            plan.links += result.links
171            plan.problems += (result.issues + collector.take()).map { Problem(file: label, reason: .converted($0)) }
172            let inner = plan.tops[file.top].folder ? String(own.dropFirst(plan.tops[file.top].name.count + 1)) : ""
173            plan.outputs.append(Plan.Output(top: file.top, inner: inner, content: .text(result.text)))
174        }
175
176        // Attachments: a folder's at the same path inside the new folder, a loose note's in
177        // `attachments` under a free name.
178        var takenAttachments = Set<String>()
179        for (source, place) in collector.attachments.sorted(by: { $0.key.path < $1.key.path }) {
180            switch place {
181            case .inFolder(let top, let relative):
182                plan.outputs.append(Plan.Output(top: top, inner: relative, content: .copy(source)))
183            case .loose(let name):
184                takenAttachments.insert(name.lowercased())
185                if name != source.lastPathComponent { plan.renamed.append((source.lastPathComponent, "attachments/" + name)) }
186                plan.outputs.append(Plan.Output(top: attachmentsTop, inner: name, content: .copy(source)))
187            }
188            plan.attachments += 1
189        }
190        if takenAttachments.isEmpty { plan.tops[attachmentsTop].name = "" }
191        plan.problems = plan.problems.reduce(into: []) { if !$0.contains($1) { $0.append($1) } }
192        return plan
193    }
194
195    private static func display(_ file: SourceFile, _ plan: Plan) -> String {
196        plan.tops[file.top].folder ? plan.tops[file.top].natural + "/" + file.relative : file.relative
197    }
198
199    /// Files below `folder`, relative to it, leaving out hidden files and folders
200    /// (`.obsidian`, `.trash`, `.git`).
201    static func folderFiles(_ folder: URL) -> [String] {
202        let manager = FileManager.default
203        guard let enumerator = manager.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) else { return [] }
204        let base = folder.standardizedFileURL.resolvingSymlinksInPath().path
205        var out: [String] = []
206        for case let url as URL in enumerator {
207            guard (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true else { continue }
208            let path = url.standardizedFileURL.resolvingSymlinksInPath().path
209            guard path.hasPrefix(base + "/") else { continue }
210            out.append(String(path.dropFirst(base.count + 1)))
211        }
212        return out.sorted()
213    }
214
215    /// `natural`, or `name 2.ext`, `name 3.ext`… when that name is in `folder` or `taken`
216    /// (lowercased).
217    static func freeName(_ natural: String, in folder: URL, taken: Set<String>) -> String {
218        let ext = (natural as NSString).pathExtension
219        let stem = (natural as NSString).deletingPathExtension
220        var name = natural
221        var n = 2
222        while taken.contains(name.lowercased()) || FileManager.default.fileExists(atPath: folder.appendingPathComponent(name).path) {
223            name = stem + " \(n)" + (ext.isEmpty ? "" : "." + ext)
224            n += 1
225        }
226        return name
227    }
228
229    /// `path` relative to the folder `from`, both relative to the same folder.
230    static func relative(_ path: String, from folder: String) -> String {
231        let target = path.split(separator: "/").map(String.init)
232        let base = folder.split(separator: "/").map(String.init)
233        var common = 0
234        while common < min(target.count - 1, base.count), target[common] == base[common] { common += 1 }
235        return (Array(repeating: "..", count: base.count - common) + target[common...]).joined(separator: "/")
236    }
237
238    // MARK: - Links
239
240    enum Placement: Sendable {
241        case inFolder(top: Int, relative: String)
242        case loose(name: String)
243    }
244
245    /// Attachments links ask for, gathered while notes render.
246    final class Collector: @unchecked Sendable {
247        private let lock = NSLock()
248        private(set) var attachments: [URL: Placement] = [:]
249        private var looseNames = Set<String>()
250        private var issues: [MarkdownImportIssue] = []
251
252        func add(_ issue: MarkdownImportIssue) {
253            lock.withLock { issues.append(issue) }
254        }
255
256        func take() -> [MarkdownImportIssue] {
257            lock.withLock {
258                defer { issues = [] }
259                return issues
260            }
261        }
262
263        /// Where `source` is copied, choosing a free name in `attachments` for a loose note's.
264        func place(_ source: URL, inFolder: (top: Int, relative: String)?, attachments folder: URL?) -> Placement {
265            lock.withLock {
266                if let placed = attachments[source] { return placed }
267                let placement: Placement
268                if let inFolder {
269                    placement = .inFolder(top: inFolder.top, relative: inFolder.relative)
270                } else {
271                    let name = MarkdownImport.freeName(source.lastPathComponent, in: folder ?? source, taken: looseNames)
272                    looseNames.insert(name.lowercased())
273                    placement = .loose(name: name)
274                }
275                attachments[source] = placement
276                return placement
277            }
278        }
279    }
280
281    /// A folder's files by name, for wikilinks, which name a note or file anywhere in the vault.
282    struct VaultIndex: Sendable {
283        /// Lowercased names (notes without their extension) to the files with them.
284        let byName: [String: [(url: URL, top: Int, relative: String)]]
285        let byPath: [String: (url: URL, top: Int, relative: String)]
286        let byURL: [URL: (top: Int, relative: String)]
287
288        fileprivate init(files: [SourceFile]) {
289            var byName: [String: [(url: URL, top: Int, relative: String)]] = [:]
290            var byPath: [String: (url: URL, top: Int, relative: String)] = [:]
291            var byURL: [URL: (top: Int, relative: String)] = [:]
292            for file in files {
293                let entry = (file.url.standardizedFileURL, file.top, file.relative)
294                byURL[file.url.standardizedFileURL] = (file.top, file.relative)
295                let key = (file.note ? (file.relative as NSString).deletingPathExtension : file.relative).lowercased()
296                byPath["\(file.top)/" + key] = entry
297                byName[(key as NSString).lastPathComponent, default: []].append(entry)
298            }
299            for key in byName.keys { byName[key]?.sort { $0.relative.count < $1.relative.count } }
300            self.byName = byName
301            self.byPath = byPath
302            self.byURL = byURL
303        }
304    }
305
306    /// Resolves one note's links.
307    struct LinkContext: Sendable {
308        let note: URL
309        /// The note's output path, relative to the destination.
310        let own: String
311        let ownFolder: String
312        /// The note's chosen folder, when it's in one.
313        let folderTop: Int?
314        let topName: String
315        let attachmentsTop: String
316        let destination: URL
317        let outputPath: [URL: String]
318        let parsed: [URL: MarkdownToOrg.Parsed]
319        let index: VaultIndex
320        let collector: Collector
321        let obsidian: Bool
322
323        /// The org path for a note at `target` with `fragment`, relative to this note.
324        func notePath(_ target: URL, fragment: String?, original: String) -> String? {
325            guard let output = outputPath[target] else { return nil }
326            let same = target == note
327            var search = ""
328            if let fragment, !fragment.isEmpty {
329                let part = fragment.split(separator: "#").last.map(String.init) ?? fragment
330                if part.hasPrefix("^") {
331                    if parsed[target]?.blockIDs.contains(String(part.dropFirst())) == true {
332                        search = String(part.dropFirst())
333                    } else {
334                        collector.add(.missingHeading(original))
335                    }
336                } else if let title = MarkdownToOrg.heading(part, in: parsed[target]?.headings ?? []) {
337                    search = "*" + title
338                } else {
339                    collector.add(.missingHeading(original))
340                }
341            }
342            if same, !search.isEmpty { return search }
343            let path = "file:" + MarkdownImport.relative(output, from: ownFolder)
344            return search.isEmpty ? path : path + "::" + search
345        }
346
347        /// The org path for a file copied as an attachment.
348        func attachmentPath(_ url: URL) -> String {
349            let inFolder: (top: Int, relative: String)?
350            if let folderTop, let found = index.byURL[url], found.top == folderTop {
351                inFolder = (folderTop, found.relative)
352            } else {
353                inFolder = nil
354            }
355            let placement = collector.place(url, inFolder: inFolder, attachments: destination.appendingPathComponent(attachmentsTop))
356            switch placement {
357            case .inFolder(_, let relative): return "file:" + MarkdownImport.relative(topName + "/" + relative, from: ownFolder)
358            case .loose(let name): return "file:" + MarkdownImport.relative(attachmentsTop + "/" + name, from: ownFolder)
359            }
360        }
361
362        func link(_ destination: String, image: Bool) -> String? {
363            if destination.hasPrefix("#") {
364                return notePath(note, fragment: String(destination.dropFirst()), original: destination) ?? destination
365            }
366            if let colon = destination.firstIndex(of: ":"), destination[..<colon].count >= 2,
367               destination[..<colon].allSatisfy({ $0.isLetter || $0.isNumber || "+.-".contains($0) }) { return nil }
368            var path = destination
369            var fragment: String?
370            if let hash = path.firstIndex(of: "#") {
371                fragment = String(path[path.index(after: hash)...])
372                path = String(path[..<hash])
373            }
374            path = path.removingPercentEncoding ?? path
375            let folder = note.deletingLastPathComponent()
376            var candidates = [path.hasPrefix("/") ? URL(fileURLWithPath: path) : folder.appendingPathComponent(path)]
377            if obsidian, let folderTop {
378                if let entry = index.byPath["\(folderTop)/" + ((path as NSString).pathExtension.lowercased() == "md" ? (path as NSString).deletingPathExtension : path).lowercased()] {
379                    candidates.append(entry.url)
380                }
381                if let entry = index.byName[((path as NSString).pathExtension.lowercased() == "md" ? (path as NSString).deletingPathExtension : path).lowercased()]?.first {
382                    candidates.append(entry.url)
383                }
384            }
385            for candidate in candidates.map(\.standardizedFileURL) {
386                if outputPath[candidate] != nil { return notePath(candidate, fragment: fragment, original: destination) }
387                var isFolder: ObjCBool = false
388                if FileManager.default.fileExists(atPath: candidate.path, isDirectory: &isFolder), !isFolder.boolValue {
389                    if MarkdownImport.noteExtensions.contains(candidate.pathExtension.lowercased()) { break }
390                    return attachmentPath(candidate)
391                }
392            }
393            collector.add(.unresolvedLink(destination))
394            return nil
395        }
396
397        func wikilink(_ target: String, fragment: String?, embed: Bool) -> (path: String, image: Bool)? {
398            let original = target + (fragment.map { "#" + $0 } ?? "")
399            if target.isEmpty {
400                guard let path = notePath(note, fragment: fragment, original: original) else { return nil }
401                return (path, false)
402            }
403            var key = target.lowercased()
404            if (key as NSString).pathExtension == "md" { key = (key as NSString).deletingPathExtension }
405            let entry: (url: URL, top: Int, relative: String)?
406            if key.contains("/") {
407                entry = folderTop.flatMap { index.byPath["\($0)/" + key] } ?? index.byName[(key as NSString).lastPathComponent]?.first { $0.relative.lowercased().hasSuffix(key) }
408            } else {
409                entry = index.byName[key]?.first
410            }
411            guard let entry else {
412                // Obsidian links to notes that don't exist yet; the link goes where one would be.
413                collector.add(.unresolvedLink(original))
414                let ext = (key as NSString).pathExtension
415                guard ext.isEmpty else { return nil }
416                return ("file:" + MarkdownImport.relative((folderTop == nil ? "" : topName + "/") + target + ".org", from: ownFolder), false)
417            }
418            if outputPath[entry.url] != nil {
419                guard let path = notePath(entry.url, fragment: fragment, original: original) else { return nil }
420                return (path, false)
421            }
422            return (attachmentPath(entry.url), MarkdownToOrg.imageExtensions.contains(entry.url.pathExtension.lowercased()))
423        }
424    }
425
426    // MARK: - Writing
427
428    public struct Written: Sendable {
429        /// Every file written, notes and attachments.
430        public var paths: [String] = []
431        /// Names taken since the preview, and what was used instead.
432        public var renamed: [(from: String, to: String)] = []
433    }
434
435    /// Writes `plan`'s files. Nothing existing is replaced: a name taken since the plan was
436    /// made gets another free name. Each file appears whole or not at all.
437    public static func write(_ plan: Plan) throws -> Written {
438        let manager = FileManager.default
439        var written = Written()
440        var tops = plan.tops
441        for (k, top) in tops.enumerated() where top.folder && !top.name.isEmpty {
442            if top.shared {
443                try manager.createDirectory(at: plan.destination.appendingPathComponent(top.name), withIntermediateDirectories: true)
444                continue
445            }
446            var name = top.name
447            while true {
448                do {
449                    try manager.createDirectory(at: plan.destination.appendingPathComponent(name), withIntermediateDirectories: false)
450                    break
451                } catch CocoaError.fileWriteFileExists {
452                    name = freeName(top.natural, in: plan.destination, taken: Set(tops.map { $0.name.lowercased() }))
453                }
454            }
455            if name != top.name { written.renamed.append((top.name, name)) }
456            tops[k].name = name
457        }
458        for output in plan.outputs {
459            let top = tops[output.top]
460            guard !top.name.isEmpty else { continue }
461            var url = top.folder ? plan.destination.appendingPathComponent(top.name).appendingPathComponent(output.inner) : plan.destination.appendingPathComponent(top.name)
462            try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
463            let temporary = url.deletingLastPathComponent().appendingPathComponent(".\(url.lastPathComponent).\(UUID().uuidString).tmp")
464            switch output.content {
465            case .text(let text): try Data(text.utf8).write(to: temporary, options: .withoutOverwriting)
466            case .copy(let source): try manager.copyItem(at: source, to: temporary)
467            }
468            while renamex_np(temporary.path, url.path, UInt32(RENAME_EXCL)) != 0 {
469                guard errno == EEXIST else {
470                    let code = errno
471                    try? manager.removeItem(at: temporary)
472                    throw NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: url.path])
473                }
474                let taken = url.lastPathComponent
475                url = url.deletingLastPathComponent().appendingPathComponent(freeName(taken, in: url.deletingLastPathComponent(), taken: []))
476                written.renamed.append((taken, url.lastPathComponent))
477            }
478            written.paths.append(url.path)
479        }
480        return written
481    }
482}
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