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
@@ -0,0 +1,166 @@
import Foundation
import HelderCore
import HelderServices
import Testing
@Suite struct GitServiceConsoleTests {
/// A repository with `a.txt` committed, 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)
}
// MARK: execute
@Test func executeStreamsTheLinesAndReturnsTheExitCode() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"])
try repo.write("a.txt", "b\n")
let log = LineLog()
let result = await GitService(root: repo.root).execute(["status"], onLine: log.append)
#expect(result.succeeded)
#expect(log.outputs.contains("On branch main"))
#expect(log.outputs.contains("\tmodified: a.txt"))
#expect(result.stdout.contains("modified: a.txt"))
}
@Test func aFailingCommandReturnsItsCodeAndStreamsStderr() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"])
let log = LineLog()
let result = await GitService(root: repo.root).execute(["checkout", "no-such-branch"], onLine: log.append)
#expect(!result.succeeded)
#expect(result.exitCode > 0)
#expect(log.errors.contains { $0.hasPrefix("error:") })
}
@Test func aCommitWithoutAMessageAbortsInsteadOfOpeningAnEditor() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"])
try repo.write("a.txt", "b\n")
try repo.run("add", "a.txt")
let log = LineLog()
let result = await GitService(root: repo.root).execute(["commit"], literalPathspecs: true, timeout: 10, onLine: log.append)
#expect(!result.succeeded)
#expect(result.exitCode != -1)
#expect(try repo.run("log", "--format=%s") == "commit\n")
}
@Test func executeSwitchesOffPromptsEditorsAndPagers() async throws {
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "") }
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
_ = await service.execute(["log"], onLine: { _, _ in })
_ = await service.execute(["log"], literalPathspecs: false, timeout: nil, onLine: { _, _ in })
let calls = runner.calls
#expect(calls.map(\.arguments) == [["log"], ["log"]])
for call in calls {
#expect(call.executable == "git")
#expect(call.environment?["GIT_TERMINAL_PROMPT"] == "0")
#expect(call.environment?["GCM_INTERACTIVE"] == "never")
#expect(call.environment?["GIT_EDITOR"] == "true")
#expect(call.environment?["GIT_PAGER"] == "cat")
#expect(call.environment?["PAGER"] == "cat")
}
#expect(calls[0].environment?["GIT_LITERAL_PATHSPECS"] == "1")
#expect(calls[1].environment?["GIT_LITERAL_PATHSPECS"] == nil)
}
@Test func aHangingCommandGivesUpAfterTheTimeout() async throws {
let runner = ScriptedRunner { _ in
try await Task.sleep(nanoseconds: 30_000_000_000)
return ProcessResult(exitCode: 0, stdout: "", stderr: "")
}
let log = LineLog()
let started = Date()
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
.execute(["fetch"], literalPathspecs: true, timeout: 0.2, onLine: log.append)
#expect(result == GitCommandResult(exitCode: -1, stdout: "", stderr: "timed out after 0.2s"))
#expect(log.errors == ["timed out after 0.2s"])
#expect(Date().timeIntervalSince(started) < 5)
}
@Test(.timeLimit(.minutes(1)))
func aTimeoutDoesNotWaitForAGrandchildHoldingStderr() async throws {
let repo = try TempGitRepo()
let log = LineLog()
let started = Date()
let result = await GitService(root: repo.root)
.execute(["-c", "alias.hang=!sleep 30 >&2 & sleep 30", "hang"], literalPathspecs: true, timeout: 0.5, onLine: log.append)
#expect(result == GitCommandResult(exitCode: -1, stdout: "", stderr: "timed out after 0.5s"))
#expect(Date().timeIntervalSince(started) < 1.5)
}
@Test func aMissingGitIsALaunchFailureNotAThrow() async throws {
let runner = ProcessRunner(locator: ExecutableLocator(directories: []))
let log = LineLog()
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).execute(["status"], onLine: log.append)
#expect(result == GitCommandResult(exitCode: -1, stdout: "", stderr: "git not found"))
#expect(log.errors == ["git not found"])
}
// MARK: branches
@Test func branchesListsLocalAndOriginBranches() async throws {
let (repo, remote) = try repoWithRemote()
defer { withExtendedLifetime(remote) {} }
try repo.run("branch", "feature/a")
try repo.run("push", "-q", "origin", "main", "feature/a")
try repo.run("branch", "local-only")
try repo.run("remote", "set-head", "origin", "main")
let list = await GitService(root: repo.root).branches()
#expect(list.local == ["feature/a", "local-only", "main"])
#expect(list.remote == ["origin/feature/a", "origin/main"])
}
@Test func branchesOutsideARepositoryAreEmpty() async throws {
let dir = try TempDirectory()
#expect(await GitService(root: dir.root).branches() == .empty)
}
// MARK: author
@Test func authorReadsNameAndEmailFromConfig() async throws {
let repo = try TempGitRepo()
#expect(await GitService(root: repo.root).author() == "Helder Tests <tests@helder.invalid>")
}
@Test func authorIsNilWithoutAName() async throws {
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 1, stdout: "", stderr: "") }
#expect(await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).author() == nil)
}
@Test func authorIsTheNameAloneWithoutAnEmail() async throws {
let runner = ScriptedRunner { call in
call.arguments.last == "user.name"
? ProcessResult(exitCode: 0, stdout: "Ada\n", stderr: "")
: ProcessResult(exitCode: 1, stdout: "", stderr: "")
}
#expect(await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).author() == "Ada")
}
// MARK: status header
@Test func loadReadsBehindAndUpstream() async throws {
let (repo, remote) = try repoWithRemote()
defer { withExtendedLifetime(remote) {} }
try repo.commit(["b.txt": "b\n"], message: "second")
try repo.run("push", "-q", "-u", "origin", "main")
try repo.run("reset", "-q", "--hard", "HEAD~1")
try repo.commit(["c.txt": "c\n"], message: "local")
let snapshot = try #require(try await GitService(root: repo.root).load())
#expect(snapshot.ahead == 1)
#expect(snapshot.behind == 1)
#expect(snapshot.upstream == "origin/main")
}
@Test func aBranchWithoutUpstreamHasNone() async throws {
let repo = try TempGitRepo()
try repo.commit(["a.txt": "a\n"])
let snapshot = try #require(try await GitService(root: repo.root).load())
#expect(snapshot.upstream == nil)
#expect(snapshot.behind == 0)
}
}