adds nice git interface

This commit is contained in:
2026-10-30 13:21:45 +01:00
parent b9c03a7637
commit caec81e762
107 changed files with 6466 additions and 3992 deletions
@@ -39,7 +39,7 @@ import Testing
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"])
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")])
}
@@ -48,7 +48,7 @@ import Testing
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.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") == [
@@ -61,7 +61,7 @@ import Testing
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.run("add", "--", "fresh.txt")
try repo.write("fresh.txt", "one\ntwo\n")
let snapshot = try await service.load()
#expect(rows(snapshot, "fresh.txt") == [
@@ -192,183 +192,13 @@ import Testing
}
}
@Suite struct GitServiceWriteTests {
@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
}
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)")
@@ -376,9 +206,6 @@ import Testing
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")
}
}
@@ -394,59 +221,6 @@ import Testing
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: "") }
@@ -454,83 +228,7 @@ import Testing
}
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)
}
}