Sources/OrgApp/Attachments.swift

design-themes-widgets
orgstar/Sources/OrgApp/Attachments.swift history · blame · raw

201 lines · 9786 bytes

  1import Foundation
  2import OrgCore
  3
  4/// org-attach's commands on the file system, with `org-attach-preferred-new-method` `id`,
  5/// `org-attach-auto-tag` "ATTACH" and `org-attach-store-link-p` `attached`. Each takes the
  6/// file's text and returns it as the command leaves it.
  7public enum Attachments {
  8    /// `org-attach-method`.
  9    public enum Method: String, Sendable {
 10        case cp, mv, ln, lns
 11    }
 12
 13    public struct Failure: Error, Equatable, CustomStringConvertible {
 14        public let description: String
 15        public init(_ description: String) { self.description = description }
 16    }
 17
 18    /// Where an entry is: its file's text and path, and an offset in the entry.
 19    public struct Entry: Sendable {
 20        public var text: String
 21        public let offset: Int
 22        public let path: String
 23        public let idDir: String
 24        /// `org-attach-use-inheritance`, as `OrgAttach.directory` takes it.
 25        public let inherit: Bool?
 26        public let options: EditingOptions
 27
 28        public init(text: String, offset: Int, path: String, idDir: String = OrgPreferences.attachIDDir(),
 29                    inherit: Bool? = OrgPreferences.attachUseInheritance(), options: EditingOptions = .org) {
 30            self.text = text
 31            self.offset = offset
 32            self.path = path
 33            self.idDir = idDir
 34            self.inherit = inherit
 35            self.options = options
 36        }
 37    }
 38
 39    static func isDirectory(_ path: String) -> Bool {
 40        var directory: ObjCBool = false
 41        return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
 42    }
 43
 44    /// `org-attach-dir`: the entry's attachment folder when it exists.
 45    public static func directory(_ entry: Entry, noFSCheck: Bool = false) -> String? {
 46        OrgAttach.directory(tree: OrgParser.parse(entry.text), at: entry.offset, path: entry.path, idDir: entry.idDir, inherit: entry.inherit, noFSCheck: noFSCheck, isDirectory: isDirectory)
 47    }
 48
 49    /// `org-attach-dir-get-create`: the folder, made if missing; an entry without DIR or ID
 50    /// gets an ID.
 51    public static func directoryCreating(_ entry: inout Entry, newID: () -> String = { UUID().uuidString.lowercased() }) throws -> String {
 52        var dir = directory(entry, noFSCheck: true)
 53        if dir == nil {
 54            let (text, id) = OrgAttach.ensuringID(entry.text, at: entry.offset, newID: newID)
 55            entry.text = text
 56            dir = OrgAttach.folder(forID: id, idDir: entry.idDir, in: (entry.path as NSString).deletingLastPathComponent, existing: false, isDirectory: isDirectory)
 57        }
 58        guard let dir else { throw Failure("No attachment directory is associated with the current node") }
 59        try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
 60        return dir
 61    }
 62
 63    static func tag(_ entry: inout Entry, on: Bool) {
 64        entry.text = OrgAttach.tagging(entry.text, at: entry.offset, on: on, options: entry.options)
 65    }
 66
 67    static func stored(_ name: String) -> StoredLink {
 68        StoredLink(link: "attachment:" + name, description: name)
 69    }
 70
 71    /// `org-attach-attach`: `source` moved, copied or linked into the folder. The link it
 72    /// stores.
 73    @discardableResult
 74    public static func attach(_ source: URL, method: Method, to entry: inout Entry) throws -> StoredLink {
 75        let dir = try directoryCreating(&entry)
 76        let name = source.standardizedFileURL.lastPathComponent
 77        let target = (dir as NSString).appendingPathComponent(name)
 78        let files = FileManager.default
 79        switch method {
 80        case .mv: try files.moveItem(atPath: source.path, toPath: target)
 81        case .cp: try files.copyItem(atPath: source.path, toPath: target)
 82        case .ln: try files.linkItem(atPath: source.path, toPath: target)
 83        case .lns: try files.createSymbolicLink(atPath: target, withDestinationPath: source.path)
 84        }
 85        tag(&entry, on: true)
 86        return stored(name)
 87    }
 88
 89    /// `org-attach-url` and `org-attach-buffer`: `data` written as `name` in the folder.
 90    @discardableResult
 91    public static func attach(_ data: Data, named name: String, to entry: inout Entry) throws -> StoredLink {
 92        guard !name.isEmpty, !name.contains("/") else { throw Failure("No file name to attach as") }
 93        let dir = try directoryCreating(&entry)
 94        let target = (dir as NSString).appendingPathComponent(name)
 95        guard !FileManager.default.fileExists(atPath: target) else { throw Failure("File exists: \(target)") }
 96        try data.write(to: URL(fileURLWithPath: target))
 97        tag(&entry, on: true)
 98        return stored(name)
 99    }
100
101    /// The name `org-attach-url` gives a download: the URL after its last slash.
102    public static func name(ofURL url: String) -> String {
103        url.split(separator: "/", omittingEmptySubsequences: false).last.map(String.init) ?? ""
104    }
105
106    /// `org-attach-new`: the path of `name` in the folder, made empty if missing, to open.
107    public static func create(_ name: String, in entry: inout Entry) throws -> String {
108        let dir = try directoryCreating(&entry)
109        tag(&entry, on: true)
110        let file = OrgAttach.expand(name, in: dir)
111        if !FileManager.default.fileExists(atPath: file) {
112            try FileManager.default.createDirectory(atPath: (file as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
113            try Data().write(to: URL(fileURLWithPath: file))
114        }
115        return file
116    }
117
118    /// `org-attach-file-list`.
119    public static func files(in dir: String) -> [String] {
120        OrgAttach.fileList((try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? [])
121    }
122
123    /// `org-attach-delete-one`.
124    public static func delete(_ name: String, in entry: Entry) throws {
125        guard let dir = directory(entry) else { throw Failure("No attachment directory exist") }
126        let file = OrgAttach.expand(name, in: dir)
127        guard FileManager.default.fileExists(atPath: file) else { throw Failure("No such attachment: \(file)") }
128        try FileManager.default.removeItem(atPath: file)
129    }
130
131    /// `org-attach-delete-all`: the folder and everything in it, and the tag.
132    public static func deleteAll(_ entry: inout Entry) throws {
133        guard let dir = directory(entry) else { return }
134        try FileManager.default.removeItem(atPath: dir)
135        tag(&entry, on: false)
136    }
137
138    /// `org-attach-sync`: the tag on when the folder has files, off when it hasn't or is
139    /// missing. The folder when it's empty, for the caller to offer to delete.
140    public static func sync(_ entry: inout Entry) -> String? {
141        guard let dir = directory(entry) else {
142            tag(&entry, on: false)
143            return nil
144        }
145        let files = files(in: dir)
146        tag(&entry, on: !files.isEmpty)
147        return ((try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? []).isEmpty ? dir : nil
148    }
149
150    /// `org-attach-set-directory`'s DIR: `dir` expanded against the file's folder, absolute as
151    /// with `org-attach-dir-relative` nil. The old folder when it existed and is another.
152    public static func setDirectory(_ dir: String, in entry: inout Entry) -> (new: String, old: String?) {
153        let old = directory(entry)
154        let new = OrgAttach.expand(dir, in: (entry.path as NSString).deletingLastPathComponent)
155        entry.text = OrgAttach.settingDirectory(entry.text, at: entry.offset, to: dir.hasSuffix("/") ? new + "/" : new)
156        return (new, old.flatMap { $0 == new ? nil : $0 })
157    }
158
159    /// `org-attach-unset-directory`: DIR and ATTACH_DIR removed. The old and new folders when
160    /// they differ.
161    public static func unsetDirectory(_ entry: inout Entry) -> (old: String?, new: String?) {
162        let old = directory(entry)
163        entry.text = OrgAttach.settingDirectory(entry.text, at: entry.offset, to: nil)
164        let new = directory(entry)
165        return old == new ? (nil, nil) : (old, new)
166    }
167
168    /// `copy-directory` of the old folder's contents into the new one, which is made if
169    /// missing; files there already are kept.
170    public static func copyContents(of old: String, to new: String) throws {
171        let files = FileManager.default
172        try files.createDirectory(atPath: new, withIntermediateDirectories: true)
173        for name in try files.contentsOfDirectory(atPath: old) {
174            let target = (new as NSString).appendingPathComponent(name)
175            if !files.fileExists(atPath: target) { try files.copyItem(atPath: (old as NSString).appendingPathComponent(name), toPath: target) }
176        }
177    }
178}
179
180extension DocumentSession {
181    /// `files` moved into the attachment folder of the entry at `offset` of `path`, open or
182    /// not. A message for the echo area.
183    public func attach(_ files: [URL], to path: String, at offset: Int) -> String {
184        guard let text = text(of: path) else { return "Can't read \((path as NSString).lastPathComponent)" }
185        var entry = Attachments.Entry(text: text, offset: offset, path: path, options: options)
186        var names: [String] = []
187        var failure: String?
188        for file in files {
189            do {
190                names.append(try Attachments.attach(file, method: .mv, to: &entry).description ?? file.lastPathComponent)
191            } catch {
192                failure = (error as? Attachments.Failure)?.description ?? error.localizedDescription
193                break
194            }
195        }
196        if entry.text != text, case .failed(let message) = perform(ReplaceText(old: text, new: entry.text), path: path, at: offset, expect: nil) {
197            return message
198        }
199        return failure ?? AttachActions.attached(names) ?? "Nothing to attach"
200    }
201}