Files
helder/Tests/HelderServicesTests/Git/GitServiceTests.swift
T

290 lines
14 KiB
Swift

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 repo.run("add", "--", "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 repo.run("add", "--", "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 repo.run("add", "--", "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 GitServiceReadTests {
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
}
@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())
}
@Test func recentCommitsReadHeadNewestFirst() async throws {
let repo = try repo()
let before = await GitService(root: repo.root).recentCommits().count
try repo.commit(["c.txt": "c\n"], message: "add \"c\" | 100% done")
let commits = await GitService(root: repo.root).recentCommits()
#expect(commits.count == before + 1)
let commit = try #require(commits.first)
#expect(commit.subject == "add \"c\" | 100% done")
#expect(commit.author == "Helder Tests")
#expect(!commit.hash.isEmpty)
#expect(abs(commit.date.timeIntervalSinceNow) < 600)
}
@Test func recentCommitsStopAtThirty() async throws {
let repo = try repo()
for index in 0..<32 {
try repo.commit(["n.txt": "\(index)\n"], message: "commit \(index)")
}
let commits = await GitService(root: repo.root).recentCommits()
#expect(commits.count == GitCommitLogParsing.limit)
#expect(commits.first?.subject == "commit 31")
}
@Test func aRepositoryWithoutCommitsHasNoRecentCommits() async throws {
let repo = try TempGitRepo()
#expect(await GitService(root: repo.root).recentCommits().isEmpty)
}
}
/// 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
}
@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()
#expect(!runner.calls.isEmpty)
#expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" })
}
}
@Suite struct GitServiceStagedDiffTests {
@Test func stagedDiffHoldsOnlyTheStagedChanges() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "1\n", "b.txt": "1\n"], message: "init")
try repo.write("a.txt", "1\nstaged\n")
try repo.run("add", "a.txt")
try repo.write("b.txt", "1\nunstaged\n")
let diff = try #require(await GitService(root: repo.root).stagedDiff())
#expect(diff.stat.contains("a.txt"))
#expect(!diff.stat.contains("b.txt"))
#expect(diff.patch.contains("+staged"))
#expect(!diff.patch.contains("unstaged"))
}
@Test func nothingStagedIsAnEmptyDiff() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "1\n"], message: "init")
let diff = try #require(await GitService(root: repo.root).stagedDiff())
#expect(diff.isEmpty)
}
@Test func outsideARepositoryThereIsNoDiff() async throws {
let dir = try TempDirectory()
#expect(await GitService(root: dir.root).stagedDiff() == nil)
}
}