Tests/OrgProgramsTests/GitAutoCommitTests.swift
250 lines · 12300 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6@testable import OrgPrograms
7
8let git = Git.find()
9
10/// A repository in a temporary folder, with its own identity and no signing, hooks or
11/// credential helper from the user's configuration.
12struct Repository {
13 let folder: Folder
14 var url: URL { folder.url }
15
16 init(_ folder: Folder = try! Folder(), clone remote: URL? = nil) async throws {
17 self.folder = folder
18 if let remote {
19 try await run("clone", "-q", remote.path, ".")
20 } else {
21 try await run("init", "-q", "-b", "main")
22 }
23 for (key, value) in [("user.name", "Test"), ("user.email", "test@example.com"), ("commit.gpgsign", "false"), ("core.hooksPath", "/dev/null"), ("credential.helper", "")] {
24 try await run("config", key, value)
25 }
26 }
27
28 @discardableResult
29 func run(_ arguments: String...) async throws -> String {
30 let output = try await git!.run(arguments, in: url)
31 guard output.succeeded else { throw Git.Failure(description: "git \(arguments.joined(separator: " ")): \(output.problem)") }
32 return output.stdout
33 }
34
35 func commitAll(_ message: String) async throws {
36 try await run("add", "-A")
37 try await run("commit", "-q", "-m", message)
38 }
39
40 func head() async throws -> String { try await run("rev-parse", "HEAD").trimmingCharacters(in: .whitespacesAndNewlines) }
41 func path(_ name: String) -> String { url.appendingPathComponent(name).path }
42}
43
44/// A bare repository and two clones of it, the first with `a.org` and `b.org` pushed.
45private func remoteAndClones() async throws -> (remote: Folder, mine: Repository, theirs: Repository) {
46 let remote = try Folder()
47 _ = try await git!.run(["init", "-q", "--bare", "-b", "main"], in: remote.url)
48 let mine = try await Repository(clone: remote.url)
49 try mine.folder.write("a.org", "* A\n")
50 try mine.folder.write("b.org", "* B\n")
51 try await mine.commitAll("Start")
52 try await mine.run("push", "-q", "-u", "origin", "main")
53 let theirs = try await Repository(clone: remote.url)
54 return (remote, mine, theirs)
55}
56
57@Suite(.enabled(if: git != nil, "git isn't installed"))
58struct GitAutoCommitTests {
59 @Test func commitsOnlyTheFilesOrgstarWrote() async throws {
60 let repo = try await Repository()
61 try repo.folder.write("a.org", "* A\n")
62 try repo.folder.write("b.org", "* B\n")
63 try await repo.commitAll("Start")
64 try repo.folder.write("a.org", "* A\nsaved by orgstar\n")
65 try repo.folder.write("b.org", "* B\nsomeone's work in progress\n")
66 try repo.folder.write("c.txt", "staged by hand\n")
67 try await repo.run("add", "c.txt")
68 try repo.folder.write("sub/new.org", "* New\n")
69
70 let outcome = await GitAutoCommit.run(files: [repo.path("a.org"), repo.path("sub/new.org")], pullAndPush: false, git: git!)
71 #expect(outcome.committed.sorted() == ["a.org", "sub/new.org"])
72 #expect(outcome.messages == ["Committed a.org, new.org in \(repo.url.resolvingSymlinksInPath().lastPathComponent)."])
73 #expect(try await repo.run("show", "--name-only", "--format=%s", "HEAD") == "Update a.org, new.org\n\na.org\nsub/new.org\n")
74 // The other changes are where they were: b.org modified, c.txt staged.
75 #expect(try await repo.run("status", "--porcelain") == " M b.org\nA c.txt\n")
76 }
77
78 @Test func nothingChangedIsNotCommitted() async throws {
79 let repo = try await Repository()
80 try repo.folder.write("a.org", "* A\n")
81 try await repo.commitAll("Start")
82 let head = try await repo.head()
83 let outcome = await GitAutoCommit.run(files: [repo.path("a.org")], pullAndPush: false, git: git!)
84 #expect(outcome == GitAutoCommit.Outcome())
85 #expect(try await repo.head() == head)
86 }
87
88 @Test func noCommitWhileARebaseIsInProgress() async throws {
89 let repo = try await Repository()
90 try repo.folder.write("a.org", "* A\n")
91 try await repo.commitAll("Start")
92 let head = try await repo.head()
93 try FileManager.default.createDirectory(at: repo.url.appendingPathComponent(".git/rebase-merge"), withIntermediateDirectories: true)
94 try repo.folder.write("a.org", "* A\nchanged\n")
95
96 let outcome = await GitAutoCommit.run(files: [repo.path("a.org")], pullAndPush: true, git: git!)
97 #expect(outcome.committed.isEmpty)
98 #expect(outcome.retry == [repo.path("a.org")])
99 #expect(outcome.messages.count == 1 && outcome.messages[0].contains("a git rebase is in progress"))
100 #expect(try await repo.head() == head)
101 #expect(Git.operationInProgress(repo.url.appendingPathComponent(".git")) == "rebase")
102 }
103
104 @Test func pullsCommitsAndPushes() async throws {
105 let (remote, mine, theirs) = try await remoteAndClones()
106 try theirs.folder.write("b.org", "* B\nfrom the other Mac\n")
107 try await theirs.commitAll("Theirs")
108 try await theirs.run("push", "-q")
109 try mine.folder.write("a.org", "* A\nmine\n")
110
111 let outcome = await GitAutoCommit.run(files: [mine.path("a.org")], pullAndPush: true, git: git!)
112 #expect(outcome.committed == ["a.org"] && outcome.pushed)
113 #expect(outcome.messages.first?.hasPrefix("Committed and pushed a.org") == true)
114 // A fast-forward pull, then our commit on top: no merge commit.
115 #expect(try await mine.run("log", "--format=%s", "-3") == "Update a.org\nTheirs\nStart\n")
116 let remoteHead = try await git!.run(["rev-parse", "main"], in: remote.url).stdout
117 #expect(remoteHead == (try await mine.run("rev-parse", "HEAD")))
118 }
119
120 @Test func refusedFastForwardIsReportedAndNothingIsPushed() async throws {
121 let (remote, mine, theirs) = try await remoteAndClones()
122 try theirs.folder.write("b.org", "* B\ntheirs\n")
123 try await theirs.commitAll("Theirs")
124 try await theirs.run("push", "-q")
125 let remoteHead = try await git!.run(["rev-parse", "main"], in: remote.url).stdout
126 // A commit of mine the remote doesn't have: the histories have diverged.
127 try mine.folder.write("b.org", "* B\nmine, by hand\n")
128 try await mine.commitAll("Mine")
129 try mine.folder.write("a.org", "* A\nsaved\n")
130
131 let outcome = await GitAutoCommit.run(files: [mine.path("a.org")], pullAndPush: true, git: git!)
132 #expect(!outcome.pushed)
133 // Committed here; the pull left the repository as it was, with no merge.
134 #expect(outcome.committed == ["a.org"])
135 let message = try #require(outcome.messages.first)
136 #expect(message.contains("Couldn't pull in") && message.contains("Not possible to fast-forward") && message.contains("Not pushed"))
137 #expect(try await mine.run("log", "--format=%s", "-3") == "Update a.org\nMine\nStart\n")
138 #expect(Git.operationInProgress(mine.url.appendingPathComponent(".git")) == nil)
139 #expect(try await git!.run(["rev-parse", "main"], in: remote.url).stdout == remoteHead)
140 }
141
142 @Test(.enabled(if: FileManager.default.isExecutableFile(atPath: "/usr/bin/python3")))
143 func credentialsAreNeverPromptedFor() async throws {
144 // A server that wants a password for everything.
145 let server = Process()
146 server.executableURL = URL(fileURLWithPath: "/usr/bin/python3")
147 server.arguments = ["-c", """
148 import http.server
149 class H(http.server.BaseHTTPRequestHandler):
150 def do_GET(self):
151 self.send_response(401)
152 self.send_header('WWW-Authenticate', 'Basic realm="x"')
153 self.send_header('Content-Length', '0')
154 self.end_headers()
155 def log_message(self, *a): pass
156 s = http.server.HTTPServer(('127.0.0.1', 0), H)
157 print(s.server_port, flush=True)
158 s.serve_forever()
159 """]
160 let out = Pipe()
161 server.standardOutput = out
162 try server.run()
163 defer { server.terminate() }
164 let port = try #require(String(decoding: out.fileHandleForReading.availableData, as: UTF8.self).split(separator: "\n").first)
165 let repo = try await Repository()
166 try repo.folder.write("a.org", "* A\n")
167 try await repo.commitAll("Start")
168 try await repo.run("remote", "add", "origin", "http://127.0.0.1:\(port)/notes.git")
169 try await repo.run("config", "branch.main.remote", "origin")
170 try await repo.run("config", "branch.main.merge", "refs/heads/main")
171 try repo.folder.write("a.org", "* A\nchanged\n")
172
173 let start = ContinuousClock.now
174 let outcome = await GitAutoCommit.run(files: [repo.path("a.org")], pullAndPush: true, git: git!, networkTimeout: .seconds(20))
175 #expect(ContinuousClock.now - start < .seconds(15))
176 #expect(!outcome.pushed)
177 let message = try #require(outcome.messages.first)
178 #expect(message.contains("couldn't sign in"), "\(message)")
179 }
180
181 @MainActor
182 @Test func commitsAMinuteAfterTheLastWriteAndOnQuit() async throws {
183 let repo = try await Repository()
184 try repo.folder.write("a.org", "* A\n")
185 try repo.folder.write("b.org", "* B\n")
186 try await repo.commitAll("Start")
187 let start = try await repo.head()
188 let defaults = try #require(UserDefaults(suiteName: "orgstar-git-\(UUID().uuidString)"))
189 let settings = GitFolderSettings(defaults: defaults)
190 settings.set(.commit, for: repo.url.path)
191 let elsewhere = try Folder()
192 settings.set(.commit, for: elsewhere.url.path)
193 let autoCommit = GitAutoCommit(settings: settings)
194 autoCommit.git = git
195 autoCommit.delay = .milliseconds(600)
196 autoCommit.roots = { [repo.url.path] }
197 var reports: [String] = []
198 autoCommit.report = { reports.append($0) }
199
200 try repo.folder.write("a.org", "* A\none\n")
201 autoCommit.fileWritten(repo.path("a.org"))
202 // Outside every sidebar folder: not tracked.
203 try elsewhere.write("x.org", "x\n")
204 autoCommit.fileWritten(elsewhere.url.appendingPathComponent("x.org").path)
205 try await Task.sleep(for: .milliseconds(300))
206 try repo.folder.write("a.org", "* A\none\ntwo\n")
207 autoCommit.fileWritten(repo.path("a.org"))
208 try await Task.sleep(for: .milliseconds(300))
209 // The second write pushed the commit back.
210 #expect(try await repo.head() == start)
211 var tries = 0
212 while try await repo.head() == start, tries < 100 {
213 try await Task.sleep(for: .milliseconds(100))
214 tries += 1
215 }
216 #expect(try await repo.run("log", "--format=%s", "-2") == "Update a.org\nStart\n")
217 #expect(reports.count == 1 && reports[0].hasPrefix("Committed a.org"))
218 #expect(!autoCommit.hasPending)
219
220 // Quitting commits what is waiting without the delay.
221 autoCommit.delay = .seconds(600)
222 try repo.folder.write("b.org", "* B\nbefore quitting\n")
223 autoCommit.fileWritten(repo.path("b.org"))
224 #expect(autoCommit.hasPending)
225 await autoCommit.flush()
226 #expect(try await repo.run("log", "--format=%s", "-1") == "Update b.org\n")
227
228 // Off: nothing is tracked.
229 settings.set(.off, for: repo.url.path)
230 autoCommit.fileWritten(repo.path("b.org"))
231 #expect(!autoCommit.hasPending)
232 }
233
234 @MainActor
235 @Test func sessionReportsEachWrite() throws {
236 let notes = try Folder()
237 let file = try notes.write("a.org", "* A\n")
238 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
239 var written: [String] = []
240 session.fileWritten = { written.append($0) }
241 session.open(file.path)
242 #expect(session.save())
243 #expect(written.isEmpty)
244 let text = session.document!.text
245 _ = session.perform(PrecomputedEdit(EditResult(baseRevision: session.document!.revision, edits: lineEdits(from: text, to: text + "more\n"))),
246 path: file.path, at: 0, expect: nil)
247 #expect(session.save())
248 #expect(written == [file.path])
249 }
250}