adds nice git interface
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,19 +14,4 @@ import Testing
|
||||
repo = nil
|
||||
#expect(!FileManager.default.fileExists(atPath: root.path))
|
||||
}
|
||||
|
||||
@Test func gitServiceStagesAndCommits() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "one\n"])
|
||||
try repo.write("a.txt", "two\n")
|
||||
let service = GitService(root: repo.root)
|
||||
#expect(await service.isRepository())
|
||||
try await service.stage(["a.txt"])
|
||||
#expect(try repo.run("status", "--porcelain") == "M a.txt\n")
|
||||
try await service.unstage(["a.txt"])
|
||||
#expect(try repo.run("status", "--porcelain") == " M a.txt\n")
|
||||
try await service.stage(["a.txt"])
|
||||
try await service.commit(message: "second")
|
||||
#expect(try repo.run("log", "--format=%s") == "second\ncommit\n")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,3 +63,93 @@ import Testing
|
||||
#expect(ExecutableLocator(directories: []).locate("/bin/sh")?.path == "/bin/sh")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ProcessRunnerStreamTests {
|
||||
let runner = ProcessRunner()
|
||||
|
||||
@Test func streamsEachLineWithItsStreamAndKeepsTheFullOutput() async throws {
|
||||
let log = LineLog()
|
||||
let result = try await runner.stream("sh", arguments: ["-c", "echo one; echo two >&2; printf 'three'"], in: nil,
|
||||
environment: nil, onLine: log.append)
|
||||
#expect(log.outputs == ["one", "three"])
|
||||
#expect(log.errors == ["two"])
|
||||
#expect(result == ProcessResult(exitCode: 0, stdout: "one\nthree", stderr: "two\n"))
|
||||
}
|
||||
|
||||
@Test func aCarriageReturnEndsALineAndEmptyLinesAreDropped() async throws {
|
||||
let log = LineLog()
|
||||
let script = "printf 'Counting 10%%\\rCounting 100%%\\r\\n\\ndone\\n' >&2"
|
||||
let result = try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil, onLine: log.append)
|
||||
#expect(log.errors == ["Counting 10%", "Counting 100%", "done"])
|
||||
#expect(result.stderr == "Counting 10%\rCounting 100%\r\n\ndone\n")
|
||||
}
|
||||
|
||||
@Test func linesArriveBeforeTheProcessEnds() async throws {
|
||||
let arrivals = LineLog()
|
||||
let started = Date()
|
||||
_ = try await runner.stream("sh", arguments: ["-c", "echo first; sleep 1; echo second"], in: nil, environment: nil) { line, _ in
|
||||
arrivals.append("\(line) \(Date().timeIntervalSince(started))", false)
|
||||
}
|
||||
let times = arrivals.texts.compactMap { $0.split(separator: " ").last.flatMap { Double($0) } }
|
||||
try #require(times.count == 2)
|
||||
#expect(times[1] - times[0] > 0.5)
|
||||
}
|
||||
|
||||
@Test func largeStreamedOutputOnBothPipesDoesNotDeadlock() async throws {
|
||||
let log = LineLog()
|
||||
let script = "i=0; while [ $i -lt 5000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done"
|
||||
let result = try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil, onLine: log.append)
|
||||
#expect(log.outputs.count == 5000)
|
||||
#expect(log.errors.count == 5000)
|
||||
#expect(log.outputs.last == "line4999")
|
||||
#expect(result.stdout.split(separator: "\n").count == 5000)
|
||||
}
|
||||
|
||||
@Test func stdinIsClosedWhileStreaming() async throws {
|
||||
let result = try await runner.stream("cat", arguments: [], in: nil, environment: nil) { _, _ in }
|
||||
#expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: ""))
|
||||
}
|
||||
|
||||
@Test func cancellationTerminatesAStreamingChild() async throws {
|
||||
let started = Date()
|
||||
let task = Task { try await runner.stream("sleep", arguments: ["10"], in: nil, environment: nil) { _, _ in } }
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
task.cancel()
|
||||
await #expect(throws: CancellationError.self) { try await task.value }
|
||||
#expect(Date().timeIntervalSince(started) < 5)
|
||||
}
|
||||
|
||||
@Test(.timeLimit(.minutes(1)))
|
||||
func cancellationDoesNotWaitForAGrandchildHoldingAPipe() async throws {
|
||||
let marker = "helder-grandchild-\(UUID().uuidString.prefix(8))"
|
||||
let script = "sleep 30 >&2 & echo $! > /tmp/\(marker); sleep 30"
|
||||
let started = Date()
|
||||
let task = Task { try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil) { _, _ in } }
|
||||
try await Task.sleep(for: .milliseconds(300))
|
||||
task.cancel()
|
||||
await #expect(throws: CancellationError.self) { try await task.value }
|
||||
#expect(Date().timeIntervalSince(started) < 2)
|
||||
let pid = try #require(pid_t(String(contentsOfFile: "/tmp/\(marker)", encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines)))
|
||||
try? FileManager.default.removeItem(atPath: "/tmp/\(marker)")
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
#expect(kill(pid, 0) != 0)
|
||||
}
|
||||
|
||||
@Test func theDefaultStreamEmitsStdoutThenStderrAfterTheRun() async throws {
|
||||
let log = LineLog()
|
||||
let fake = CannedRunner(result: ProcessResult(exitCode: 2, stdout: "a\r\nb\n", stderr: "c\n\nd"))
|
||||
let result = try await fake.stream("x", arguments: [], in: nil, environment: nil, onLine: log.append)
|
||||
#expect(log.lines.map(\.text) == ["a", "b", "c", "d"])
|
||||
#expect(log.lines.map(\.isError) == [false, false, true, true])
|
||||
#expect(result.exitCode == 2)
|
||||
}
|
||||
}
|
||||
|
||||
/// A runner that only implements `run`, so `stream` falls back to the protocol's default.
|
||||
private struct CannedRunner: ProcessRunning {
|
||||
var result: ProcessResult
|
||||
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import Foundation
|
||||
|
||||
/// Collects streamed output lines from any thread, for tests of `stream` and `execute`.
|
||||
final class LineLog: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var recorded: [(text: String, isError: Bool)] = []
|
||||
|
||||
var lines: [(text: String, isError: Bool)] { lock.withLock { recorded } }
|
||||
var texts: [String] { lines.map(\.text) }
|
||||
var errors: [String] { lines.filter(\.isError).map(\.text) }
|
||||
var outputs: [String] { lines.filter { !$0.isError }.map(\.text) }
|
||||
|
||||
func append(_ text: String, _ isError: Bool) {
|
||||
lock.withLock { recorded.append((text, isError)) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user