Sources/OrgApp/SubtreeShare.swift

fbc792eb21866a31f8edcffd23f5105df3be2348
orgstar/Sources/OrgApp/SubtreeShare.swift

99 lines · 5768 bytes

 1import Foundation
 2import OrgCore
 3
 4/// Share Subtree…: the entry at the caret as an org file of its own or as text, with the files
 5/// attached to it and to the entries under it. The entry is taken as the file holds it, so an
 6/// encrypted entry is shared encrypted.
 7public struct SubtreeShare: Sendable, Identifiable {
 8    public let id = UUID()
 9    /// The entry with the file's keyword lines, as `ExportScope.entry` gives it.
10    public let text: String
11    /// The `.org` file's name: the heading's title.
12    public let fileName: String
13    /// Files in the attachment folders of the entry and the entries under it.
14    public let attachments: [URL]
15
16    /// The entry at `offset` in `text`, the file at `path`; nil before the first heading.
17    /// `idDir` and `inherit` are `org-attach-id-dir` and `org-attach-use-inheritance`.
18    public init?(text: String, at offset: Int, path: String, settings: OrgSettings = .default,
19                 idDir: String = OrgPreferences.attachIDDir(), inherit: Bool? = OrgPreferences.attachUseInheritance()) {
20        guard let entry = ExportScope.entry(text, at: offset, settings: settings) else { return nil }
21        self.text = entry.text
22        let tree = OrgParser.parse(text, defaults: settings)
23        let headings = DocumentModel(tree: tree).headings.filter { entry.range.contains($0.headingRange.lowerBound) }
24        fileName = Self.fileName(entry.title)
25        var folders: [String] = []
26        for heading in headings {
27            guard let dir = OrgAttach.directory(tree: tree, at: heading.headingRange.lowerBound, path: path, idDir: idDir, inherit: inherit, isDirectory: Attachments.isDirectory),
28                  !folders.contains(dir) else { continue }
29            folders.append(dir)
30        }
31        // Files only: hidden files and folders inside stay behind.
32        attachments = folders.flatMap { dir in
33            Attachments.files(in: dir).filter { !$0.hasPrefix(".") }.map { URL(fileURLWithPath: dir).appendingPathComponent($0) }
34                .filter { !Attachments.isDirectory($0.path) }
35        }
36    }
37
38    /// `title` as a file name: characters other systems refuse replaced, at most 80 long, with
39    /// `.org`.
40    static func fileName(_ title: String) -> String {
41        var name = title.components(separatedBy: CharacterSet(charactersIn: "/\\:*?\"<>|").union(.newlines).union(.controlCharacters))
42            .joined(separator: "-").trimmingCharacters(in: .whitespaces)
43        while name.hasPrefix(".") { name.removeFirst() }
44        if name.count > 80 { name = String(name.prefix(80)).trimmingCharacters(in: .whitespaces) }
45        return (name.isEmpty ? "Subtree" : name) + ".org"
46    }
47
48    /// Writes the entry as `fileName` in a new temporary folder; its URL.
49    public func writeFile() throws -> URL {
50        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("share-" + id.uuidString)
51        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
52        let url = folder.appendingPathComponent(fileName)
53        try Data(text.utf8).write(to: url, options: .atomic)
54        return url
55    }
56
57    /// What the share sheet sends: the written file and, when asked, the attachments, each as
58    /// an item of its own.
59    public func files(file: URL, withAttachments: Bool) -> [URL] {
60        [file] + (withAttachments ? attachments : [])
61    }
62}
63
64extension DocumentSession {
65    /// Share Subtree… for the entry at `offset` in the open file at `path`, its tagged entries
66    /// encrypted as they are on disk. Nil when there's no entry there, or `refusesSubtreeShare`.
67    public func subtreeShare(_ path: String, at offset: Int) -> SubtreeShare? {
68        guard refusesSubtreeShare(path, at: offset) == nil, var text = document(of: path)?.text else { return nil }
69        var offset = offset
70        if let (sealed, heading) = sealedSubtree(path, text: text, at: offset) {
71            text = sealed
72            offset = heading
73        }
74        return SubtreeShare(text: text, at: offset, path: path, settings: defaults)
75    }
76
77    /// Why the entry at `offset` in `path` isn't shared: its file is encrypted, or it has tagged
78    /// entries the file encrypts on disk and their passphrase isn't known.
79    public func refusesSubtreeShare(_ path: String, at offset: Int) -> String? {
80        let name = (path as NSString).lastPathComponent
81        if Self.isEncryptedFile(path) { return String(localized: "\(name) is encrypted; its entries aren't shared.") }
82        guard let text = document(of: path)?.text, crypt.sealsEntries(for: path), crypt.passphrase(for: path) == nil,
83              let range = subtreeRange(text, at: offset), !OrgCrypt.unencrypted(text, tag: cryptTag, within: range).isEmpty else { return nil }
84        return String(localized: "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first.")
85    }
86
87    private func subtreeRange(_ text: String, at offset: Int) -> Range<Int>? {
88        guard let heading = OrgCrypt.heading(text, at: offset) else { return nil }
89        return heading..<max(heading + 1, OrgCrypt.bodyRange(text, at: heading)?.upperBound ?? heading)
90    }
91
92    /// `text` with the subtree's tagged entries encrypted, and where its heading starts.
93    private func sealedSubtree(_ path: String, text: String, at offset: Int) -> (String, Int)? {
94        guard crypt.sealsEntries(for: path), let passphrase = crypt.passphrase(for: path), let range = subtreeRange(text, at: offset),
95              !OrgCrypt.unencrypted(text, tag: cryptTag, within: range).isEmpty,
96              let sealed = try? OrgCrypt.seal(text, passphrase: passphrase, tag: cryptTag, within: range).text else { return nil }
97        return (sealed, range.lowerBound)
98    }
99}
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