Tests/OrgAppTests/ReplaceInFilesTests.swift
192 lines · 8816 bytes
12 symbols in this file
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// Replace in Files and the renames over a folder: files on disk and open buffers, unticked
8/// changes, recovery versions, config.toml, refusals and cancelling.
9@MainActor
10struct ReplaceInFilesTests {
11 let notes: Folder
12 let other: Folder
13 let recovery: Folder
14 let workspace: WorkspaceModel
15 let session: DocumentSession
16 /// config.toml's settings as `Config.set` leaves them.
17 final class ConfigBox {
18 var todoKeywords = "TODO NEXT | DONE"
19 var tagAlist = "work(w) home"
20 var writes: [String: String] = [:]
21 }
22 let config = ConfigBox()
23
24 init() async throws {
25 notes = try Folder()
26 other = try Folder()
27 recovery = try Folder()
28 workspace = try WorkspaceModel(directory: nil)
29 session = DocumentSession(recovery: FileRecoveryStore(directory: recovery.url))
30 session.saveMode = .explicit
31 }
32
33 func model() -> ReplaceInFiles {
34 let box = config
35 return ReplaceInFiles(session: session, workspace: workspace, config: ReplaceInFiles.Config(todoKeywords: box.todoKeywords, tagAlist: box.tagAlist) { key, value in
36 box.writes[key] = value
37 })
38 }
39
40 /// The indexed path of `name` in `folder`.
41 func path(_ name: String, in folder: Folder? = nil) throws -> String {
42 let root = (folder ?? notes).url.lastPathComponent
43 return try #require(workspace.files.first { $0.path.hasSuffix(root + "/" + name) }?.path)
44 }
45
46 func disk(_ path: String) throws -> String { try String(contentsOfFile: path, encoding: .utf8) }
47
48 func search(_ model: ReplaceInFiles, _ mode: ReplaceInFiles.Mode, scope: String? = nil, includeConfig: Bool = true) async {
49 model.start(mode, scope: scope, includeConfig: includeConfig)
50 await model.waitForSearch()
51 }
52
53 @Test func replacesInFilesAndOpenBuffers() async throws {
54 try notes.write("a.org", "* foo\nFoo and foo\n")
55 try notes.write("b.org", "foo\n")
56 try notes.write("c.txt", "foo\n")
57 try notes.write("d.png", "foo\n")
58 try notes.write("s.org.gpg", "foo\n")
59 try notes.write("none.org", "nothing here\n")
60 try other.write("e.org", "foo\n")
61 try await workspace.addRoot(notes.url)
62 try await workspace.addRoot(other.url)
63 let a = try path("a.org"), b = try path("b.org"), c = try path("c.txt"), e = try path("e.org", in: other)
64
65 // b.org is open with an unsaved edit, which the search sees.
66 session.open(b)
67 let doc = try #require(session.document(of: b))
68 _ = session.perform(PrecomputedEdit(EditResult(baseRevision: doc.revision, edits: [TextEdit(range: 0..<0, replacement: "typed foo\n")])), path: b, at: 0, expect: nil)
69 #expect(session.isDirty)
70
71 let model = model()
72 await search(model, .replace(TextReplace(pattern: "foo", replacement: "bar")), scope: workspace.files.first { $0.path == a }?.root)
73 #expect(model.progress.done == model.progress.total)
74 #expect(model.files.map(\.path) == [a, b, c])
75 #expect(model.files[0].changes.map(\.line) == [1, 2, 2])
76 #expect(model.files[0].changes.map(\.replacement) == ["bar", "Bar", "bar"])
77 #expect(model.files[1].changes.count == 2)
78
79 // Untick the second change in a.org.
80 model.setTicked(false, change: 1, in: a)
81 #expect(model.tickedCount == 5)
82 let summary = model.apply()
83 #expect(summary == "Files changed: 3")
84 #expect(try disk(a) == "* bar\nFoo and bar\n")
85 #expect(try disk(c) == "bar\n")
86 #expect(try disk(e) == "foo\n")
87 #expect(try disk(notes.url.appendingPathComponent("s.org.gpg").path) == "foo\n")
88
89 // The open buffer took it as one undoable change and stays unsaved; the disk is as it was.
90 #expect(session.document(of: b)?.text == "typed bar\nbar\n")
91 #expect(session.isDirty)
92 #expect(try disk(b) == "foo\n")
93 var undone = try #require(session.document(of: b))
94 _ = undone.undo()
95 #expect(undone.text == "typed foo\nfoo\n")
96
97 // A file that wasn't open has its old text in recovery.
98 let store = FileRecoveryStore(directory: recovery.url)
99 let kept = try #require(try store.versions(for: URL(fileURLWithPath: a)).first { $0.lastPathComponent.contains("-replace-") })
100 #expect(try String(contentsOf: kept, encoding: .utf8) == "* foo\nFoo and foo\n")
101 }
102
103 @Test func regexpGroupsAndUntickedFiles() async throws {
104 try notes.write("a.org", "Call 555-1234\n")
105 try notes.write("b.org", "Call 555-9999\n")
106 try await workspace.addRoot(notes.url)
107 let a = try path("a.org"), b = try path("b.org")
108 let model = model()
109 await search(model, .replace(TextReplace(pattern: "([0-9]{3})-([0-9]{4})", replacement: "(\\1) $2", isRegexp: true)))
110 model.setTicked(false, file: b)
111 model.apply()
112 #expect(try disk(a) == "Call (555) 1234\n")
113 #expect(try disk(b) == "Call 555-9999\n")
114
115 await search(model, .replace(TextReplace(pattern: "(", replacement: "", isRegexp: true)))
116 #expect(model.problem != nil && model.files.isEmpty)
117 }
118
119 @Test func aFileChangedAfterTheSearchIsLeftAlone() async throws {
120 try notes.write("a.org", "foo\n")
121 try await workspace.addRoot(notes.url)
122 let a = try path("a.org")
123 let model = model()
124 await search(model, .replace(TextReplace(pattern: "foo", replacement: "bar")))
125 try Data("foo foo\n".utf8).write(to: URL(fileURLWithPath: a))
126 let summary = model.apply()
127 #expect(summary.contains("changed after the search"))
128 #expect(try disk(a) == "foo foo\n")
129 }
130
131 @Test func cancelStopsTheSearch() async throws {
132 for i in 0..<1000 { try notes.write("f\(i).org", String(repeating: "foo bar\n", count: 400)) }
133 try await workspace.addRoot(notes.url)
134 let model = model()
135 model.start(.replace(TextReplace(pattern: "foo", replacement: "bar")), scope: nil)
136 #expect(model.isSearching)
137 model.cancel()
138 await model.waitForSearch()
139 #expect(model.wasCancelled && !model.isSearching)
140 #expect(model.files.count < 1000)
141 }
142
143 @Test func renameTagWithConfig() async throws {
144 try notes.write("a.org", "#+FILETAGS: :work:\n* Plan :work:\nwork :work: in the body\n")
145 try await workspace.addRoot(notes.url)
146 let a = try path("a.org")
147 let model = model()
148 await search(model, .renameTag(from: "work", to: "office"))
149 #expect(model.configChange?.new == "office(w) home")
150 #expect(model.files.first?.changes.map(\.line) == [1, 2])
151 model.changesConfig = false
152 model.apply()
153 #expect(config.writes.isEmpty)
154 let renamed = try disk(a)
155 #expect(renamed.hasPrefix("#+FILETAGS: :office:\n* Plan"))
156 #expect(renamed.hasSuffix(":office:\nwork :work: in the body\n"))
157
158 await search(model, .renameTag(from: "home", to: "office"))
159 model.apply()
160 #expect(config.writes == ["tagAlist": "work(w) office"])
161
162 await search(model, .renameTag(from: "office", to: "two words"))
163 #expect(model.problem != nil)
164 }
165
166 @Test func renameKeywordFollowsWhereItIsDefined() async throws {
167 // own.org defines NEXT; uses.org relies on config.toml's keywords.
168 try notes.write("own.org", "#+TODO: TODO NEXT | DONE\n* NEXT a\n")
169 try notes.write("uses.org", "* NEXT b\nNEXT in the body\n")
170 try await workspace.addRoot(notes.url)
171 session.defaults = OrgSettings.default.withTodoKeywords(config.todoKeywords)!
172 let own = try path("own.org"), uses = try path("uses.org")
173
174 let model = model()
175 await search(model, .renameKeyword(from: "NEXT", to: "WAIT"), includeConfig: false)
176 #expect(model.files.map(\.path) == [own])
177 await search(model, .renameKeyword(from: "NEXT", to: "WAIT"))
178 #expect(model.files.map(\.path) == [own, uses])
179 model.apply()
180 #expect(try disk(own) == "#+TODO: TODO WAIT | DONE\n* WAIT a\n")
181 #expect(try disk(uses) == "* WAIT b\nNEXT in the body\n")
182 #expect(config.writes == ["todoKeywords": "TODO WAIT | DONE"])
183
184 // Across done and not-done states is refused, in config.toml or in a file.
185 await search(model, .renameKeyword(from: "TODO", to: "DONE"))
186 #expect(model.problem?.contains("done state") == true && model.files.isEmpty)
187 try notes.write("types.org", "#+TODO: A | B\n* A x\n")
188 await workspace.refresh()
189 await search(model, .renameKeyword(from: "A", to: "B"))
190 #expect(model.problem?.contains("types.org") == true)
191 }
192}