import Foundation import HelderCore @testable import HelderServices import Testing @Suite struct GitServiceLoadTests { /// A repository with `a.txt` committed as three lines. private func repo() throws -> TempGitRepo { let repo = try TempGitRepo() try repo.commit(["a.txt": "1\n2\n3\n"], message: "init") return repo } private func rows(_ snapshot: GitSnapshot?, _ path: String) -> [GitFileChange] { snapshot?.changes.filter { $0.path == path } ?? [] } @Test func aFolderOutsideGitLoadsAsNil() async throws { let dir = try TempDirectory() #expect(try await GitService(root: dir.root).load() == nil) } @Test func aModifiedFileCarriesHeadAndDiskText() async throws { let repo = try repo() try repo.write("a.txt", "1\nX\n3\n") let snapshot = try #require(try await GitService(root: repo.root).load()) #expect(snapshot.branch == "main") #expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\n2\n3\n", updated: "1\nX\n3\n")]) } @Test func anUntrackedFileIsAnUnstagedAddition() async throws { let repo = try repo() try repo.write("new.txt", "fresh\n") let snapshot = try await GitService(root: repo.root).load() #expect(rows(snapshot, "new.txt") == [GitFileChange(path: "new.txt", status: .added, staged: false, original: "", updated: "fresh\n")]) } @Test func aStagedFileHasOneStagedRow() async throws { let repo = try repo() try repo.write("a.txt", "1\n2\n3\n4\n") let service = GitService(root: repo.root) try await service.stage(["a.txt"]) let snapshot = try await service.load() #expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\n2\n3\n4\n")]) } @Test func aFileStagedThenEditedHasTwoRowsEachWithItsOwnPair() async throws { let repo = try repo() let service = GitService(root: repo.root) try repo.write("a.txt", "1\nSTAGED\n3\n") try await service.stage(["a.txt"]) try repo.write("a.txt", "1\nSTAGED\n3\n4\n") let snapshot = try await service.load() #expect(rows(snapshot, "a.txt") == [ GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\nSTAGED\n3\n"), GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\nSTAGED\n3\n", updated: "1\nSTAGED\n3\n4\n"), ]) } @Test func aStagedNewFileEditedAgainIsAnAdditionPlusAModification() async throws { let repo = try repo() let service = GitService(root: repo.root) try repo.write("fresh.txt", "one\n") try await service.stage(["fresh.txt"]) try repo.write("fresh.txt", "one\ntwo\n") let snapshot = try await service.load() #expect(rows(snapshot, "fresh.txt") == [ GitFileChange(path: "fresh.txt", status: .added, staged: true, original: "", updated: "one\n"), GitFileChange(path: "fresh.txt", status: .modified, staged: false, original: "one\n", updated: "one\ntwo\n"), ]) } @Test func aDeletedFileHasNoDiskText() async throws { let repo = try repo() try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt")) let snapshot = try await GitService(root: repo.root).load() #expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .deleted, staged: false, original: "1\n2\n3\n", updated: "")]) } @Test func aStagedRenameIsOneRowUnderTheNewPath() async throws { let repo = try repo() try repo.run("mv", "a.txt", "b.txt") let snapshot = try #require(try await GitService(root: repo.root).load()) #expect(snapshot.changes.map(\.path) == ["b.txt"]) #expect(snapshot.changes.first?.status == .renamed) #expect(snapshot.changes.first?.staged == true) } @Test func aBinaryFileReadsAsEmptyText() async throws { let repo = try repo() try Data([0x00, 0x01, 0x02]).write(to: repo.root.appendingPathComponent("logo.bin")) let snapshot = try await GitService(root: repo.root).load() #expect(rows(snapshot, "logo.bin").first?.updated == "") } @Test func aheadCountsCommitsTheRemoteLacks() async throws { let remote = try TempGitRepo(bare: true) let repo = try repo() try repo.run("remote", "add", "origin", remote.root.path) try repo.run("push", "-q", "-u", "origin", "main") try repo.commit(["b.txt": "b\n"], message: "second") let snapshot = try #require(try await GitService(root: repo.root).load()) #expect(snapshot.ahead == 1) #expect(snapshot.canPush) } @Test func aWorktreeWithAGitFileLoads() async throws { let repo = try repo() let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)") defer { try? FileManager.default.removeItem(at: worktree) } try repo.run("worktree", "add", "-q", "-b", "side", worktree.path) try Data("changed\n".utf8).write(to: worktree.appendingPathComponent("a.txt")) let snapshot = try #require(try await GitService(root: worktree).load()) #expect(snapshot.branch == "side") #expect(snapshot.changes.map(\.path) == ["a.txt"]) } @Test func aFailingStatusIsRetriedThenThrowsWithGitsStderr() async throws { let runner = ScriptedRunner { call in if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") } return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: Unable to create '.git/index.lock': File exists.\n") } let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 3, statusRetryDelay: 0.01) await #expect(throws: GitError.commandFailed(arguments: Porcelain.statusArguments, exitCode: 128, stderr: "fatal: Unable to create '.git/index.lock': File exists.")) { try await service.load() } #expect(runner.calls.filter { $0.arguments == Porcelain.statusArguments }.count == 3) #expect(runner.calls.last?.environment?["GIT_OPTIONAL_LOCKS"] == "0") } @Test func overlappingLoadsShareOneReadPlusOneTrailingRead() async throws { let gate = Gate() let runner = ScriptedRunner { call in if call.arguments.first == "rev-parse" { await gate.wait() return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") } return ProcessResult(exitCode: 1, stdout: "", stderr: "stop here") } let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 1) let first = Task { try? await service.load() } #expect(await eventually { !runner.calls.isEmpty }) let later = (0..<5).map { _ in Task { _ = try? await service.load() } } #expect(await eventuallyAsync { await service.coalescedLoads == 5 }) await gate.open() _ = await first.value for task in later { await task.value } #expect(runner.calls.filter { $0.arguments.first == "rev-parse" }.count == 2) } @Test func anUntrackedFileOverTheSizeCapLoadsWithoutText() async throws { let repo = try repo() try repo.write("dump.sql", String(repeating: "insert;\n", count: 200)) let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() #expect(rows(snapshot, "dump.sql") == [GitFileChange(path: "dump.sql", status: .added, staged: false, original: "", updated: "", isTooBig: true)]) } @Test func aCommittedFileOverTheSizeCapLoadsWithoutTextOnEitherSide() async throws { let repo = try repo() try repo.commit(["big.txt": String(repeating: "line\n", count: 300)]) try repo.write("big.txt", String(repeating: "line\n", count: 301)) let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() #expect(rows(snapshot, "big.txt") == [GitFileChange(path: "big.txt", status: .modified, staged: false, original: "", updated: "", isTooBig: true)]) } @Test func aFileThatOutgrewTheCapDropsTheSmallSideToo() async throws { let repo = try repo() try repo.commit(["grew.txt": "small\n"]) try repo.write("grew.txt", String(repeating: "line\n", count: 300)) let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() let row = try #require(rows(snapshot, "grew.txt").first) #expect(row.isTooBig) #expect(row.original.isEmpty && row.updated.isEmpty) } @Test func aFileUnderTheSizeCapStillCarriesItsText() async throws { let repo = try repo() try repo.write("small.txt", "ok\n") let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() #expect(rows(snapshot, "small.txt").first?.updated == "ok\n") #expect(rows(snapshot, "small.txt").first?.isTooBig == false) } @Test func aStagedRenameCarriesItsSourcePath() async throws { let repo = try repo() try repo.run("mv", "a.txt", "b.txt") let snapshot = try #require(try await GitService(root: repo.root).load()) #expect(snapshot.changes.first?.originalPath == "a.txt") } } @Suite struct GitServiceWriteTests { private func repo() throws -> TempGitRepo { let repo = try TempGitRepo() try repo.commit(["a.txt": "1\n2\n3\n", "b.txt": "b\n"], message: "init") return repo } private func status(_ repo: TempGitRepo) throws -> String { try repo.run("status", "--porcelain") } @Test func stagingADeletionRemovesTheFileFromTheIndex() async throws { let repo = try repo() try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt")) try await GitService(root: repo.root).stage(["a.txt"]) #expect(try status(repo) == "D a.txt\n") } @Test func stagingBothSidesOfAMoveRecordsARename() async throws { let repo = try repo() try FileManager.default.moveItem(at: repo.root.appendingPathComponent("a.txt"), to: repo.root.appendingPathComponent("c.txt")) try await GitService(root: repo.root).stage(["a.txt", "c.txt"]) #expect(try status(repo) == "R a.txt -> c.txt\n") } @Test func unstagingADeletionKeepsTheFileDeletedOnDisk() async throws { let repo = try repo() try repo.run("rm", "-q", "a.txt") try await GitService(root: repo.root).unstage(["a.txt"]) #expect(try status(repo) == " D a.txt\n") } @Test func unstagingARenameLeavesTheOldPathStagedAsDeleted() async throws { let repo = try repo() try repo.run("mv", "a.txt", "c.txt") try await GitService(root: repo.root).unstage(["c.txt"]) #expect(try status(repo) == "D a.txt\n?? c.txt\n") } @Test func unstagingWorksInARepositoryWithoutCommits() async throws { let repo = try TempGitRepo() try repo.write("first.txt", "x\n") let service = GitService(root: repo.root) try await service.stage(["first.txt"]) #expect(try status(repo) == "A first.txt\n") try await service.unstage(["first.txt"]) #expect(try status(repo) == "?? first.txt\n") } @Test func stagingNothingRunsNoGit() async throws { let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "") } let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner) try await service.stage([]) try await service.unstage([]) #expect(runner.calls.isEmpty) } @Test func aFailedCommitThrowsWithGitsStderr() async throws { let repo = try repo() do { try await GitService(root: repo.root).commit(message: "nothing") Issue.record("commit with nothing staged should fail") } catch let GitError.commandFailed(arguments, exitCode, _) { #expect(arguments == ["commit", "-m", "nothing"]) #expect(exitCode != 0) } } @Test func aFailedStageCarriesStderr() async throws { let repo = try repo() do { try await GitService(root: repo.root).stage(["missing.txt"]) Issue.record("staging a missing path should fail") } catch let GitError.commandFailed(_, _, stderr) { #expect(stderr.contains("missing.txt")) } } @Test func discardRevertsAModifiedFileToHead() async throws { let repo = try repo() try repo.write("a.txt", "1\nCHANGED\n3\n") try await GitService(root: repo.root).discard(["a.txt"]) #expect(try repo.read("a.txt") == "1\n2\n3\n") #expect(try status(repo) == "") } @Test func discardRevertsAFileStagedThenEdited() async throws { let repo = try repo() try repo.write("a.txt", "staged\n") try repo.run("add", "a.txt") try repo.write("a.txt", "edited again\n") try await GitService(root: repo.root).discard(["a.txt"]) #expect(try repo.read("a.txt") == "1\n2\n3\n") #expect(try status(repo) == "") } @Test func discardRemovesAnUntrackedFile() async throws { let repo = try repo() try repo.write("new.txt", "fresh\n") try await GitService(root: repo.root).discard(["new.txt"]) #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new.txt").path)) } @Test func discardUnstagesAndRemovesAStagedNewFile() async throws { let repo = try repo() try repo.write("staged-new.txt", "x\n") try repo.run("add", "staged-new.txt") try await GitService(root: repo.root).discard(["staged-new.txt"]) #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("staged-new.txt").path)) #expect(try status(repo) == "") } @Test func discardRestoresADeletedFile() async throws { let repo = try repo() try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt")) try await GitService(root: repo.root).discard(["a.txt"]) #expect(try repo.read("a.txt") == "1\n2\n3\n") } @Test func discardRestoresAStagedDeletion() async throws { let repo = try repo() try repo.run("rm", "-q", "a.txt") try await GitService(root: repo.root).discard(["a.txt"]) #expect(try repo.read("a.txt") == "1\n2\n3\n") #expect(try status(repo) == "") } @Test func discardHandlesSeveralPathsInOneCall() async throws { let repo = try repo() try repo.write("a.txt", "changed\n") try repo.write("new.txt", "new\n") try await GitService(root: repo.root).discard(["a.txt", "new.txt"]) #expect(try status(repo) == "") } @Test func discardNeverDeletesAFolderOrAnythingOutsideTheProject() async throws { let repo = try repo() let outside = repo.root.deletingLastPathComponent().appendingPathComponent("helder-outside-\(UUID().uuidString).txt") try Data("keep\n".utf8).write(to: outside) defer { try? FileManager.default.removeItem(at: outside) } try repo.write("folder/inner.txt", "keep\n") let service = GitService(root: repo.root) try await service.discard(["folder", "../" + outside.lastPathComponent]) #expect(FileManager.default.fileExists(atPath: outside.path)) #expect(try repo.read("folder/inner.txt") == "keep\n") } @Test func discardingAStagedRenameRestoresTheSourceAndRemovesTheTarget() async throws { let repo = try repo() try repo.run("mv", "a.txt", "c.txt") try await GitService(root: repo.root).discard(["c.txt"]) #expect(try repo.read("a.txt") == "1\n2\n3\n") #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path)) #expect(try status(repo) == "") } @Test func discardingAStagedRenameEditedAfterwardsStillRestoresTheSource() async throws { let repo = try repo() try repo.run("mv", "a.txt", "c.txt") try repo.write("c.txt", "edited\n") try await GitService(root: repo.root).discard(["c.txt"]) #expect(try repo.read("a.txt") == "1\n2\n3\n") #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path)) #expect(try status(repo) == "") } @Test func contentsReadsTheHeadAndIndexCopies() async throws { let repo = try repo() try repo.write("a.txt", "staged\n") try repo.run("add", "a.txt") try repo.write("a.txt", "disk\n") let service = GitService(root: repo.root) #expect(await service.contents(of: "a.txt", at: .head) == "1\n2\n3\n") #expect(await service.contents(of: "a.txt", at: .index) == "staged\n") #expect(await service.contents(of: "nope.txt", at: .head) == "") } @Test func isRepositoryAcceptsAWorktreeGitFile() async throws { let repo = try repo() let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)") defer { try? FileManager.default.removeItem(at: worktree) } try repo.run("worktree", "add", "-q", "-b", "side", worktree.path) let service = GitService(root: worktree) #expect(await service.isRepository()) try Data("wt\n".utf8).write(to: worktree.appendingPathComponent("a.txt")) try await service.discard(["a.txt"]) #expect(try String(contentsOf: worktree.appendingPathComponent("a.txt"), encoding: .utf8) == "1\n2\n3\n") } } /// Names git would read as globs or options unless every pathspec is literal. @Suite struct GitServiceLiteralPathTests { private func repo() throws -> TempGitRepo { let repo = try TempGitRepo() try repo.commit([ "pages/[id].vue": "id\n", "pages/i.vue": "i\n", "pages/d.vue": "d\n", "a*.txt": "star\n", "ab.txt": "ab\n", "a?.txt": "q\n", "ac.txt": "ac\n", "-dash.txt": "dash\n", "with space.txt": "space\n", ], message: "init") return repo } private func status(_ repo: TempGitRepo) throws -> String { try repo.run("status", "--porcelain") } private func editAll(_ repo: TempGitRepo) throws { for path in ["pages/[id].vue", "pages/i.vue", "pages/d.vue", "a*.txt", "ab.txt", "a?.txt", "ac.txt", "-dash.txt", "with space.txt"] { try repo.write(path, "changed\n") } } @Test func discardTouchesOnlyTheNamedFile() async throws { let repo = try repo() try editAll(repo) try await GitService(root: repo.root).discard(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"]) #expect(try repo.read("pages/[id].vue") == "id\n") #expect(try repo.read("pages/i.vue") == "changed\n") #expect(try repo.read("pages/d.vue") == "changed\n") #expect(try repo.read("a*.txt") == "star\n") #expect(try repo.read("ab.txt") == "changed\n") #expect(try repo.read("ac.txt") == "changed\n") #expect(try repo.read("-dash.txt") == "dash\n") #expect(try repo.read("with space.txt") == "space\n") } @Test func discardOfAnUntrackedGlobNameRemovesOnlyThatFile() async throws { let repo = try repo() try repo.write("new/[x].txt", "n\n") try repo.write("new/x.txt", "keep\n") try await GitService(root: repo.root).discard(["new/[x].txt"]) #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new/[x].txt").path)) #expect(try repo.read("new/x.txt") == "keep\n") } @Test func stageAndUnstageTouchOnlyTheNamedFile() async throws { let repo = try repo() try editAll(repo) let service = GitService(root: repo.root) try await service.stage(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"]) let staged = try repo.run("diff", "--cached", "--name-only") #expect(staged == "-dash.txt\na*.txt\na?.txt\npages/[id].vue\nwith space.txt\n") try await service.stage(["pages/i.vue", "ab.txt"]) try await service.unstage(["pages/[id].vue", "a*.txt"]) #expect(try repo.run("diff", "--cached", "--name-only") == "-dash.txt\na?.txt\nab.txt\npages/i.vue\nwith space.txt\n") } @Test func contentsReadsANameWithGlobCharactersOrALeadingDash() async throws { let repo = try repo() let service = GitService(root: repo.root) #expect(await service.contents(of: "pages/[id].vue", at: .head) == "id\n") #expect(await service.contents(of: "-dash.txt", at: .head) == "dash\n") #expect(await service.contents(of: "with space.txt", at: .index) == "space\n") } @Test func everyGitCallRunsWithLiteralPathspecs() async throws { let runner = ScriptedRunner { call in if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") } return ProcessResult(exitCode: 0, stdout: "", stderr: "") } let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner) _ = try await service.load() try await service.stage(["a"]) try await service.unstage(["a"]) try await service.discard(["a"]) _ = await service.contents(of: "a", at: .head) try await service.commit(message: "m") _ = await service.push() #expect(!runner.calls.isEmpty) #expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" }) } } @Suite struct GitServicePushTests { /// A committed repository plus a bare remote it knows as `origin`. private func repoWithRemote() throws -> (repo: TempGitRepo, remote: TempGitRepo) { let remote = try TempGitRepo(bare: true) let repo = try TempGitRepo() try repo.commit(["a.txt": "a\n"], message: "init") try repo.run("remote", "add", "origin", remote.root.path) return (repo, remote) } @Test func aFirstPushSetsTheUpstream() async throws { let (repo, remote) = try repoWithRemote() defer { withExtendedLifetime(remote) {} } let result = await GitService(root: repo.root).push() #expect(result.ok) #expect(result.message.contains("main")) #expect(try repo.run("rev-parse", "--abbrev-ref", "main@{upstream}") == "origin/main\n") } @Test func aPushWithNothingNewReportsUpToDate() async throws { let (repo, remote) = try repoWithRemote() defer { withExtendedLifetime(remote) {} } try repo.run("push", "-q", "-u", "origin", "main") let result = await GitService(root: repo.root).push() #expect(result == PushResult(ok: true, message: "Everything up-to-date")) } @Test func aPushWithoutARemoteFailsWithGitsLastLine() async throws { let repo = try TempGitRepo() try repo.commit(["a.txt": "a\n"]) let result = await GitService(root: repo.root).push() #expect(!result.ok) #expect(!result.message.isEmpty) } @Test func pushTurnsOffCredentialPrompts() async throws { let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "Everything up-to-date\n") } _ = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push() #expect(runner.calls.first?.arguments == ["push"]) #expect(runner.calls.first?.environment?["GIT_TERMINAL_PROMPT"] == "0") } @Test func aPushWithoutUpstreamRetriesWithTheCurrentBranch() async throws { let runner = ScriptedRunner { call in switch call.arguments { case ["push"]: return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: The current branch feature has no upstream branch.\n") case ["rev-parse", "--abbrev-ref", "HEAD"]: return ProcessResult(exitCode: 0, stdout: "feature\n", stderr: "") default: return ProcessResult(exitCode: 0, stdout: "", stderr: " * [new branch] feature -> feature\n") } } let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push() #expect(runner.calls.map(\.arguments).last == ["push", "-u", "origin", "feature"]) #expect(result == PushResult(ok: true, message: "* [new branch] feature -> feature")) } @Test func aHangingPushGivesUpAfterTheTimeout() async throws { let runner = ScriptedRunner { _ in try await Task.sleep(nanoseconds: 30_000_000_000) return ProcessResult(exitCode: 0, stdout: "", stderr: "") } let started = Date() let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, pushTimeout: 0.2).push() #expect(result == PushResult(ok: false, message: "push timed out")) #expect(Date().timeIntervalSince(started) < 5) } }