Tests/OrgAppTests/AttachmentsTests.swift
243 lines · 13943 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// org-attach's commands against Emacs: the text after each step, the link stored and the
8/// files left, run in the same folder.
9struct AttachmentsTests {
10 static let id = "6a1b2c3d-0000-4000-8000-000000000001"
11 static let notes = """
12 * Task
13 Body.
14 * Done :work:
15 :PROPERTIES:
16 :ID: 20240101T120000
17 :END:
18 * Moved
19
20 """
21
22 static func setUp(_ folder: URL) throws {
23 try? FileManager.default.removeItem(at: folder)
24 try FileManager.default.createDirectory(at: folder.appendingPathComponent("src"), withIntermediateDirectories: true)
25 try FileManager.default.createDirectory(at: folder.appendingPathComponent("data/202401/01T120000"), withIntermediateDirectories: true)
26 try notes.write(to: folder.appendingPathComponent("notes.org"), atomically: true, encoding: .utf8)
27 for name in ["a", "b", "c", "d", "e", "f"] {
28 try "\(name)\n".write(to: folder.appendingPathComponent("src/\(name).txt"), atomically: true, encoding: .utf8)
29 }
30 }
31
32 /// Every file and folder under `folder`, relative, sorted.
33 static func listing(_ folder: URL) -> [String] {
34 let base = folder.path + "/"
35 let paths = FileManager.default.enumerator(atPath: folder.path)?.allObjects as? [String] ?? []
36 return paths.filter { !$0.hasPrefix(base) }.sorted()
37 }
38
39 @Test func commandsMatchEmacs() throws {
40 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-\(UUID().uuidString)").resolvingSymlinksInPath()
41 defer { try? FileManager.default.removeItem(at: folder) }
42 try Self.setUp(folder)
43 let dir = folder.path
44 let form = #"""
45 (progn
46 (require 'org) (require 'org-attach) (require 'json)
47 (let ((out nil))
48 (cl-letf (((symbol-function 'org-id-new) (lambda (&rest _) "\#(Self.id)"))
49 ((symbol-function 'yes-or-no-p) (lambda (&rest _) nil))
50 ((symbol-function 'read-directory-name) (lambda (&rest _) "\#(dir)/elsewhere/")))
51 (with-current-buffer (find-file-noselect "\#(dir)/notes.org")
52 (cl-flet ((at (h) (goto-char (point-min)) (re-search-forward (concat "^\\* " h)) (beginning-of-line))
53 (rec () (push (buffer-substring-no-properties (point-min) (point-max)) out)))
54 (at "Task") (org-attach-attach "\#(dir)/src/a.txt") (rec) (push (caar org-stored-links) out)
55 (at "Task") (org-attach-attach "\#(dir)/src/b.txt" nil 'mv) (rec)
56 (at "Task") (org-attach-attach "\#(dir)/src/e.txt" nil 'ln)
57 (at "Task") (org-attach-attach "\#(dir)/src/f.txt" nil 'lns) (rec)
58 (at "Task") (org-attach-delete-one "a.txt") (rec)
59 (at "Task") (org-attach-sync) (rec)
60 (at "Task") (push (string-join (directory-files (org-attach-dir) nil "^[^.]") " ") out)
61 (at "Task") (org-attach-delete-all t) (rec)
62 (at "Task") (org-attach-sync) (rec)
63 (at "Done") (org-attach-attach "\#(dir)/src/c.txt") (rec)
64 (at "Moved") (org-attach-set-directory) (org-attach-attach "\#(dir)/src/d.txt") (rec)
65 (at "Moved") (org-attach-unset-directory) (rec))))
66 (with-temp-file "\#(dir)/out.json" (insert (json-encode (vconcat (nreverse out)))))))
67 """#
68 let process = Process()
69 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
70 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
71 let pipe = Pipe()
72 process.standardOutput = pipe
73 process.standardError = pipe
74 try process.run()
75 let log = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
76 process.waitUntilExit()
77 let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: folder.appendingPathComponent("out.json")))
78 try FileManager.default.removeItem(at: folder.appendingPathComponent("out.json"))
79 let emacsFiles = Self.listing(folder)
80
81 try Self.setUp(folder)
82 let path = folder.appendingPathComponent("notes.org").path
83 var entry = Attachments.Entry(text: Self.notes, offset: 0, path: path, idDir: "data/")
84 var ours: [String] = []
85 func at(_ heading: String) {
86 entry = Attachments.Entry(text: entry.text, offset: (entry.text as NSString).range(of: "* " + heading).location, path: path, idDir: "data/")
87 }
88 func rec() { ours.append(entry.text) }
89 func src(_ name: String) -> URL { folder.appendingPathComponent("src/\(name).txt") }
90 at("Task"); _ = try Attachments.directoryCreating(&entry, newID: { Self.id })
91 let link = try Attachments.attach(src("a"), method: .cp, to: &entry); rec(); ours.append(link.link)
92 at("Task"); try Attachments.attach(src("b"), method: .mv, to: &entry); rec()
93 at("Task"); try Attachments.attach(src("e"), method: .ln, to: &entry)
94 at("Task"); try Attachments.attach(src("f"), method: .lns, to: &entry); rec()
95 at("Task"); try Attachments.delete("a.txt", in: entry); rec()
96 at("Task"); _ = Attachments.sync(&entry); rec()
97 at("Task"); ours.append(Attachments.files(in: Attachments.directory(entry)!).joined(separator: " "))
98 at("Task"); try Attachments.deleteAll(&entry); rec()
99 at("Task"); _ = Attachments.sync(&entry); rec()
100 at("Done"); try Attachments.attach(src("c"), method: .cp, to: &entry); rec()
101 at("Moved"); _ = Attachments.setDirectory(dir + "/elsewhere/", in: &entry); try Attachments.attach(src("d"), method: .cp, to: &entry); rec()
102 at("Moved"); _ = Attachments.unsetDirectory(&entry); rec()
103 try entry.text.write(toFile: path, atomically: true, encoding: .utf8)
104
105 #expect(ours.count == emacs.count, "\(log)")
106 for (index, (mine, theirs)) in zip(ours, emacs).enumerated() {
107 #expect(mine == theirs, "step \(index)")
108 }
109 // Emacs leaves the buffer unsaved.
110 #expect(Self.listing(folder).filter { $0 != "notes.org" } == emacsFiles.filter { $0 != "notes.org" })
111 }
112
113 /// `org-attach-dir` without the file system check, for each inheritance setting.
114 @Test func inheritanceMatchesEmacs() throws {
115 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-\(UUID().uuidString)").resolvingSymlinksInPath()
116 defer { try? FileManager.default.removeItem(at: folder) }
117 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
118 let text = """
119 #+PROPERTY: DIR top/
120 * Parent
121 :PROPERTIES:
122 :ID: aabbcc
123 :END:
124 ** Child
125 ** Child with DIR
126 :PROPERTIES:
127 :DIR: ~/own/
128 :END:
129 *** Grandchild
130 * Plain
131
132 """
133 let path = folder.appendingPathComponent("notes.org").path
134 try text.write(toFile: path, atomically: true, encoding: .utf8)
135 let headings = ["Parent", "Child", "Child with DIR", "Grandchild", "Plain"]
136 let settings = ["selective": nil, "t": true, "nil": false] as [String: Bool?]
137 let tree = OrgParser.parse(text)
138 for (symbol, inherit) in settings {
139 let form = #"""
140 (progn (require 'org) (require 'org-attach)
141 (setq org-attach-use-inheritance '\#(symbol) org-use-property-inheritance '("DIR"))
142 (with-current-buffer (find-file-noselect "\#(path)")
143 (dolist (h '(\#(headings.map { "\"\($0)\"" }.joined(separator: " "))))
144 (goto-char (point-min)) (re-search-forward (concat "^\\*+ " h "$"))
145 (princ (format "%s\n" (let ((d (org-attach-dir nil t))) (if d (directory-file-name (expand-file-name d)) "none")))))))
146 """#
147 let process = Process()
148 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
149 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
150 let pipe = Pipe()
151 process.standardOutput = pipe
152 process.standardError = pipe
153 try process.run()
154 let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
155 process.waitUntilExit()
156 let emacs = output.split(separator: "\n").map(String.init).filter { $0.hasPrefix("/") || $0 == "none" }
157 var withDIR = tree.settings
158 withDIR.propertyInheritance = .only(["DIR"])
159 let ours = headings.map { heading in
160 OrgAttach.directory(tree: OrgParser.parse(text, defaults: withDIR), at: (text as NSString).range(of: "* " + heading + "\n").location,
161 path: path, inherit: inherit, noFSCheck: true) { _ in false } ?? "none"
162 }
163 #expect(ours == emacs, "\(symbol): \(output)")
164 }
165 }
166
167 @Test func expandKeepsPrivate() {
168 #expect(OrgAttach.expand("other/", in: "/private/tmp/n") == "/private/tmp/n/other")
169 #expect(OrgAttach.expand("../x", in: "/private/tmp/n") == "/private/tmp/x")
170 }
171
172 @Test func urlNames() {
173 #expect(Attachments.name(ofURL: "https://example.com/a/b.png") == "b.png")
174 #expect(Attachments.name(ofURL: "https://example.com/a/b.png?x=1") == "b.png?x=1")
175 #expect(Attachments.name(ofURL: "https://example.com/") == "")
176 }
177
178 @Test func folderForID() {
179 let none: (String) -> Bool = { _ in false }
180 #expect(OrgAttach.folder(forID: "abcdef12", idDir: "data/", in: "/n", existing: false, isDirectory: none) == "/n/data/ab/cdef12")
181 #expect(OrgAttach.folder(forID: "ab", idDir: "data/", in: "/n", existing: false, isDirectory: none) == "/n/data/__/a/ab")
182 #expect(OrgAttach.folder(forID: "abcdef12", idDir: "~/.attach/", in: "/n", existing: true, isDirectory: { $0 == "/n/data" || $0 == "/n/data/abcdef/12" })
183 == "/n/data/abcdef/12")
184 }
185}
186
187@MainActor
188struct AttachmentInboxTests {
189 @Test func sharedFilesAttachToAnEntryOfAClosedFile() throws {
190 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-inbox-\(UUID().uuidString)").resolvingSymlinksInPath()
191 defer { try? FileManager.default.removeItem(at: folder) }
192 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
193 let shared = folder.appendingPathComponent("photo.jpg")
194 try Data("jpeg".utf8).write(to: shared)
195 let inbox = AttachmentInbox(folder: folder.appendingPathComponent("inbox"))
196 try inbox.add([shared])
197 let batch = try #require(inbox.batches().first)
198 #expect(AttachmentInbox.files(in: batch).map(\.lastPathComponent) == ["photo.jpg"])
199
200 let notes = folder.appendingPathComponent("notes.org").path
201 try "* Trip\n:PROPERTIES:\n:ID: abcdef\n:END:\n".write(toFile: notes, atomically: true, encoding: .utf8)
202 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
203 let message = session.attach(AttachmentInbox.files(in: batch), to: notes, at: 0)
204 inbox.remove(batch)
205 #expect(message == "File \"photo.jpg\" is now an attachment")
206 #expect(try String(contentsOfFile: notes, encoding: .utf8).hasPrefix("* Trip" + String(repeating: " ", count: 63) + ":ATTACH:\n"))
207 #expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("data/ab/cdef/photo.jpg").path))
208 #expect(inbox.batches().isEmpty)
209 }
210}
211
212struct AttachmentImageTests {
213 /// `attachment:` links resolve as following them does: an ID entry's folder under
214 /// `org-attach-id-dir`, a `DIR` property's folder, and the file's folder otherwise.
215 @Test func attachmentLinksResolveToTheEntrysFolder() throws {
216 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-image-\(UUID().uuidString)").resolvingSymlinksInPath()
217 defer { try? FileManager.default.removeItem(at: folder) }
218 try FileManager.default.createDirectory(at: folder.appendingPathComponent("data/202401/01T120000"), withIntermediateDirectories: true)
219 try FileManager.default.createDirectory(at: folder.appendingPathComponent("imgs"), withIntermediateDirectories: true)
220 let text = """
221 * With ID
222 :PROPERTIES:
223 :ID: 20240101T120000
224 :END:
225 [[attachment:pic.png]]
226 * With DIR
227 :PROPERTIES:
228 :DIR: imgs
229 :END:
230 [[attachment:pic.png]]
231
232 """
233 let path = folder.appendingPathComponent("notes.org").path
234 let tree = OrgParser.parse(text)
235 let ns = text as NSString
236 let first = ns.range(of: "[[attachment").location
237 let second = ns.range(of: "[[attachment", options: .backwards).location
238 #expect(DocumentSession.attachmentPath("pic.png", at: first, tree: tree, path: path) == folder.appendingPathComponent("data/202401/01T120000/pic.png").path)
239 #expect(DocumentSession.attachmentPath("pic.png", at: second, tree: tree, path: path) == folder.appendingPathComponent("imgs/pic.png").path)
240 #expect(InlineImages.image(atLine: second, in: ns, attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) })?.path
241 == folder.appendingPathComponent("imgs/pic.png").path)
242 }
243}