Repository Public
1import Foundation2import Testing3@testable import GitKit4import SPProcess56/// Throwaway repositories created with `/usr/bin/git` directly (never through `GitRunner`).7struct Sandbox {8 struct GitFailure: Error { let arguments: [String]; let output: String }910 /// Container directory (real path) holding `repo/` and anything else a test creates.11 let base: URL12 var repo: URL { base.appendingPathComponent("repo", isDirectory: true) }1314 init(initialize: Bool = true) throws {15 let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("GitKitTests-\(UUID().uuidString)")16 try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)17 guard let resolved = realpath(temporary.path, nil) else { throw CocoaError(.fileNoSuchFile) }18 defer { free(resolved) }19 base = URL(fileURLWithPath: String(cString: resolved), isDirectory: true)20 try FileManager.default.createDirectory(at: repo, withIntermediateDirectories: true)21 if initialize {22 try git("init", "-q", "-b", "main")23 try Self.configure(repo)24 }25 }2627 static func configure(_ directory: URL) throws {28 try run(["config", "--local", "user.name", "Test User"], in: directory)29 try run(["config", "--local", "user.email", "test@example.invalid"], in: directory)30 try run(["config", "--local", "commit.gpgsign", "false"], in: directory)31 }3233 func cleanup() { try? FileManager.default.removeItem(at: base) }3435 @discardableResult func git(_ arguments: String...) throws -> String { try Self.run(arguments, in: repo) }3637 @discardableResult38 static func run(_ arguments: [String], in directory: URL, allowFailure: Bool = false) throws -> String {39 let process = Process()40 process.executableURL = URL(fileURLWithPath: "/usr/bin/git")41 process.arguments = arguments42 process.currentDirectoryURL = directory43 var environment = ProcessInfo.processInfo.environment.filter { !$0.key.hasPrefix("GIT_") }44 environment["GIT_CONFIG_GLOBAL"] = "/dev/null"45 environment["GIT_CONFIG_NOSYSTEM"] = "1"46 environment["GIT_TERMINAL_PROMPT"] = "0"47 process.environment = environment48 let pipe = Pipe()49 process.standardInput = FileHandle.nullDevice50 process.standardOutput = pipe51 process.standardError = pipe52 try process.run()53 let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)54 process.waitUntilExit()55 if process.terminationStatus != 0 && !allowFailure { throw GitFailure(arguments: arguments, output: output) }56 return output57 }5859 func write(_ path: String, _ contents: String, in directory: URL? = nil) throws {60 let url = (directory ?? repo).appendingPathComponent(path)61 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)62 try contents.write(to: url, atomically: true, encoding: .utf8)63 }6465 func commit(_ path: String, _ contents: String, message: String) throws {66 try write(path, contents)67 try git("add", "--", path)68 try git("commit", "-q", "-m", message)69 }70}7172@Suite struct GitRepositoryTests {73 @Test func discoverFindsRootFromSubdirectoryAndFile() async throws {74 let sandbox = try Sandbox()75 defer { sandbox.cleanup() }76 try sandbox.write("a/b/file.txt", "x\n")77 let fromDirectory = try await GitRepository.discover(from: sandbox.repo.appendingPathComponent("a/b"))78 #expect(fromDirectory.rootURL.path == sandbox.repo.path)79 let fromFile = try await GitRepository.discover(from: sandbox.repo.appendingPathComponent("a/b/file.txt"))80 #expect(fromFile.rootURL.path == sandbox.repo.path)81 let fromRoot = try await GitRepository.discover(from: sandbox.repo)82 #expect(fromRoot.rootURL.path == sandbox.repo.path)83 }8485 @Test func discoverThrowsOutsideARepository() async throws {86 let sandbox = try Sandbox(initialize: false)87 defer { sandbox.cleanup() }88 await #expect(throws: GitError.notARepository(sandbox.repo.path)) {89 try await GitRepository.discover(from: sandbox.repo)90 }91 let missing = sandbox.base.appendingPathComponent("does-not-exist")92 await #expect(throws: GitError.notARepository(missing.path)) {93 try await GitRepository.discover(from: missing)94 }95 }9697 @Test func statusOfUnbornRepository() async throws {98 let sandbox = try Sandbox()99 defer { sandbox.cleanup() }100 let repository = try await GitRepository.discover(from: sandbox.repo)101 let status = try await repository.status()102 #expect(status.head == .branch("main"))103 #expect(status.headOID == nil)104 #expect(status.upstream == nil)105 #expect(status.ahead == nil)106 #expect(status.isClean)107 #expect(try await repository.recentCommits(limit: 5).isEmpty)108 #expect(try await repository.diff(staged: true).isEmpty)109 }110111 @Test func statusCategorizesStagedUnstagedUntrackedAndRenames() async throws {112 let sandbox = try Sandbox()113 defer { sandbox.cleanup() }114 let body = (1...20).map { "line \($0)\n" }.joined()115 try sandbox.write("modified.txt", "one\n")116 try sandbox.write("both.txt", "one\n")117 try sandbox.write("deleted.txt", "bye\n")118 try sandbox.write("old name.txt", body)119 try sandbox.git("add", "-A")120 try sandbox.git("commit", "-q", "-m", "initial")121 let head = try sandbox.git("rev-parse", "HEAD").trimmingCharacters(in: .whitespacesAndNewlines)122123 try sandbox.write("modified.txt", "two\n") // unstaged only124 try sandbox.write("both.txt", "two\n")125 try sandbox.git("add", "both.txt")126 try sandbox.write("both.txt", "three\n") // staged + unstaged127 try sandbox.git("rm", "-q", "deleted.txt") // staged deletion128 try sandbox.git("mv", "old name.txt", "new name.txt") // staged rename, path with a space129 try sandbox.write("added.txt", "new\n")130 try sandbox.git("add", "added.txt") // staged addition131 try sandbox.write("untracked é.txt", "?\n") // untracked, non-ASCII132133 let status = try await GitRepository(rootURL: sandbox.repo).status()134 #expect(status.head == .branch("main"))135 #expect(status.headOID == head)136 #expect(!status.isClean)137 #expect(!status.isTruncated)138 let byPath = Dictionary(uniqueKeysWithValues: status.entries.map { ($0.path, $0) })139 #expect(byPath.count == 6)140 #expect(byPath["modified.txt"] == GitStatusEntry(kind: .changed, path: "modified.txt", worktree: .modified))141 #expect(byPath["both.txt"] == GitStatusEntry(kind: .changed, path: "both.txt", index: .modified, worktree: .modified))142 #expect(byPath["deleted.txt"] == GitStatusEntry(kind: .changed, path: "deleted.txt", index: .deleted))143 #expect(byPath["new name.txt"] == GitStatusEntry(kind: .changed, path: "new name.txt", originalPath: "old name.txt", index: .renamed))144 #expect(byPath["added.txt"] == GitStatusEntry(kind: .changed, path: "added.txt", index: .added))145 #expect(byPath["untracked é.txt"] == GitStatusEntry(kind: .untracked, path: "untracked é.txt"))146 #expect(Set(status.staged.map(\.path)) == ["both.txt", "deleted.txt", "new name.txt", "added.txt"])147 #expect(Set(status.unstaged.map(\.path)) == ["modified.txt", "both.txt"])148 #expect(status.untracked.map(\.path) == ["untracked é.txt"])149 #expect(status.conflicted.isEmpty)150 }151152 @Test func statusReportsConflicts() async throws {153 let sandbox = try Sandbox()154 defer { sandbox.cleanup() }155 try sandbox.commit("f.txt", "base\n", message: "base")156 try sandbox.git("checkout", "-q", "-b", "feature")157 try sandbox.commit("f.txt", "feature\n", message: "feature")158 try sandbox.git("checkout", "-q", "main")159 try sandbox.commit("f.txt", "main\n", message: "main")160 try Sandbox.run(["merge", "feature"], in: sandbox.repo, allowFailure: true)161162 let status = try await GitRepository(rootURL: sandbox.repo).status()163 #expect(status.conflicted == [GitStatusEntry(kind: .conflicted, path: "f.txt", index: .unmerged, worktree: .unmerged)])164 #expect(status.staged.isEmpty)165 #expect(status.unstaged.isEmpty)166 }167168 @Test func statusReportsDetachedHead() async throws {169 let sandbox = try Sandbox()170 defer { sandbox.cleanup() }171 try sandbox.commit("f.txt", "1\n", message: "one")172 try sandbox.git("checkout", "-q", "--detach")173 let status = try await GitRepository(rootURL: sandbox.repo).status()174 #expect(status.head == .detached)175 #expect(status.headOID?.count == 40)176 #expect(status.upstream == nil)177 }178179 @Test func statusReportsUpstreamAheadAndBehind() async throws {180 let sandbox = try Sandbox()181 defer { sandbox.cleanup() }182 try sandbox.commit("f.txt", "1\n", message: "one")183 // A local-path clone: no network involved.184 try Sandbox.run(["clone", "-q", sandbox.repo.path, "clone"], in: sandbox.base)185 let clone = sandbox.base.appendingPathComponent("clone", isDirectory: true)186 try Sandbox.configure(clone)187 let repository = GitRepository(rootURL: clone)188189 var status = try await repository.status()190 #expect(status.upstream == "origin/main")191 #expect(status.ahead == 0)192 #expect(status.behind == 0)193194 try sandbox.write("local.txt", "x\n", in: clone)195 try Sandbox.run(["add", "local.txt"], in: clone)196 try Sandbox.run(["commit", "-q", "-m", "local 1"], in: clone)197 try sandbox.write("local2.txt", "x\n", in: clone)198 try Sandbox.run(["add", "local2.txt"], in: clone)199 try Sandbox.run(["commit", "-q", "-m", "local 2"], in: clone)200 try sandbox.commit("remote.txt", "y\n", message: "remote")201 try Sandbox.run(["fetch", "-q"], in: clone)202203 status = try await repository.status()204 #expect(status.head == .branch("main"))205 #expect(status.ahead == 2)206 #expect(status.behind == 1)207 #expect(status.isClean)208 }209210 @Test func recentCommitsParsesFieldsNewestFirst() async throws {211 let sandbox = try Sandbox()212 defer { sandbox.cleanup() }213 try sandbox.commit("f.txt", "1\n", message: "first")214 try sandbox.commit("f.txt", "2\n", message: "second: with \"quotes\", é and | pipes")215 try sandbox.write("f.txt", "3\n")216 try sandbox.git("commit", "-q", "-a", "-m", "third subject", "-m", "A body paragraph\nthat is not part of the subject.")217 let head = try sandbox.git("rev-parse", "HEAD").trimmingCharacters(in: .whitespacesAndNewlines)218219 let repository = GitRepository(rootURL: sandbox.repo)220 let commits = try await repository.recentCommits(limit: 10)221 #expect(commits.map(\.subject) == ["third subject", "second: with \"quotes\", é and | pipes", "first"])222 let latest = try #require(commits.first)223 #expect(latest.hash == head)224 #expect(latest.hash.hasPrefix(latest.shortHash))225 #expect(latest.shortHash.count >= 4 && latest.shortHash.count < 40)226 #expect(latest.authorName == "Test User")227 #expect(latest.authorEmail == "test@example.invalid")228 #expect(abs(latest.date.timeIntervalSinceNow) < 300)229 #expect(Set(commits.map(\.id)).count == 3)230231 #expect(try await repository.recentCommits(limit: 2).map(\.subject) == ["third subject", "second: with \"quotes\", é and | pipes"])232 #expect(try await repository.recentCommits(limit: 0).isEmpty)233 }234235 @Test func diffUnstagedStagedAndByPath() async throws {236 let sandbox = try Sandbox()237 defer { sandbox.cleanup() }238 try sandbox.write("a.txt", "alpha\n")239 try sandbox.write("dir/b *.txt", "beta\n")240 try sandbox.git("add", "-A")241 try sandbox.git("commit", "-q", "-m", "initial")242 let repository = GitRepository(rootURL: sandbox.repo)243 #expect(try await repository.diff().isEmpty)244245 try sandbox.write("a.txt", "alpha changed\n")246 try sandbox.write("dir/b *.txt", "beta changed\n")247 try sandbox.git("add", "a.txt")248249 let unstaged = try await repository.diff()250 #expect(!unstaged.truncated)251 #expect(unstaged.text.contains("+beta changed"))252 #expect(unstaged.text.contains("-beta"))253 #expect(!unstaged.text.contains("alpha"))254 #expect(!unstaged.text.contains("\u{1b}["))255256 let staged = try await repository.diff(staged: true)257 #expect(staged.text.contains("diff --git a/a.txt b/a.txt"))258 #expect(staged.text.contains("+alpha changed"))259 #expect(!staged.text.contains("beta"))260261 // The path is literal: `*` is not a glob, and another file's diff is not included.262 #expect(try await repository.diff(path: "dir/b *.txt").text.contains("+beta changed"))263 #expect(try await repository.diff(path: "a.txt").isEmpty)264 #expect(try await repository.diff(staged: true, path: "a.txt").text.contains("+alpha changed"))265 #expect(try await repository.diff(path: "*").isEmpty)266 #expect(try await repository.diff(path: "--output=pwned").isEmpty)267 #expect(!FileManager.default.fileExists(atPath: sandbox.repo.appendingPathComponent("pwned").path))268 await #expect(throws: GitError.invalidArgument("empty or malformed path")) { try await repository.diff(path: "") }269 }270271 @Test func diffIsCappedAndFlaggedTruncated() async throws {272 let sandbox = try Sandbox()273 defer { sandbox.cleanup() }274 try sandbox.commit("big.txt", "start\n", message: "initial")275 try sandbox.write("big.txt", (0..<50_000).map { "changed line number \($0)\n" }.joined())276 let repository = GitRepository(rootURL: sandbox.repo)277278 let capped = try await repository.diff(maxBytes: 4096)279 #expect(capped.truncated)280 #expect(capped.text.utf8.count <= 4096 + 2)281 #expect(capped.text.hasPrefix("diff --git a/big.txt b/big.txt"))282283 let full = try await repository.diff(maxBytes: 8 << 20)284 #expect(!full.truncated)285 #expect(full.text.contains("+changed line number 49999"))286 }287288 @Test func externalDiffAndTextconvConfiguredInTheRepositoryAreNotExecuted() async throws {289 let sandbox = try Sandbox()290 defer { sandbox.cleanup() }291 try sandbox.commit("a.txt", "one\n", message: "initial")292 let marker = sandbox.base.appendingPathComponent("executed").path293 try sandbox.git("config", "--local", "diff.external", "/usr/bin/touch \(marker) #")294 try sandbox.git("config", "--local", "core.fsmonitor", "/usr/bin/touch \(marker) #")295 try sandbox.write("a.txt", "two\n")296 let repository = GitRepository(rootURL: sandbox.repo)297 #expect(try await repository.diff().text.contains("+two"))298 _ = try await repository.status()299 _ = try await repository.recentCommits()300 #expect(!FileManager.default.fileExists(atPath: marker))301 }302303 @Test func queriesDoNotModifyTheRepository() async throws {304 let sandbox = try Sandbox()305 defer { sandbox.cleanup() }306 try sandbox.commit("a.txt", "one\n", message: "initial")307 try sandbox.write("a.txt", "two\n")308 let indexURL = sandbox.repo.appendingPathComponent(".git/index")309 let before = try Data(contentsOf: indexURL)310 let modified = try FileManager.default.attributesOfItem(atPath: indexURL.path)[.modificationDate] as? Date311 let repository = GitRepository(rootURL: sandbox.repo)312 _ = try await repository.status()313 _ = try await repository.diff()314 _ = try await repository.diff(staged: true)315 _ = try await repository.recentCommits()316 #expect(try Data(contentsOf: indexURL) == before)317 #expect(try FileManager.default.attributesOfItem(atPath: indexURL.path)[.modificationDate] as? Date == modified)318 #expect(!FileManager.default.fileExists(atPath: sandbox.repo.appendingPathComponent(".git/index.lock").path))319 }320}321322@Suite struct GitRunnerTests {323 static let refused: [[String]] = [324 [],325 ["commit", "-m", "x"], ["add", "."], ["push"], ["pull"], ["fetch"], ["checkout", "main"], ["switch", "main"],326 ["reset", "--hard"], ["clean", "-fd"], ["stash"], ["merge", "x"], ["rebase", "x"], ["tag", "v1"], ["config", "user.name", "x"],327 ["init"], ["clone", "x"], ["gc"], ["update-index", "--refresh"], ["rm", "a.txt"], ["mv", "a", "b"], ["apply"], ["am"],328 ["-c", "core.pager=evil", "status"], ["-C", "/tmp", "status"], ["--exec-path=/tmp", "status"], ["--git-dir=/tmp/x", "status"],329 ["status\0--x"], ["status", "a\0b"],330 ["branch"], ["branch", "newbranch"], ["branch", "-d", "main"], ["branch", "-D", "main"], ["branch", "-m", "a", "b"],331 ["branch", "-a", "newbranch"], ["branch", "--list", "-d", "main"], ["branch", "-f", "main", "HEAD"],332 ["branch", "--set-upstream-to=origin/main"], ["branch", "--edit-description"], ["branch", "-u", "origin/main"],333 ["worktree"], ["worktree", "add", "../x"], ["worktree", "remove", "x"], ["worktree", "prune"], ["worktree", "list", "--expire=now"],334 ["remote", "add", "o", "url"], ["remote", "remove", "origin"], ["remote", "set-url", "origin", "u"], ["remote", "update"],335 ["remote", "show", "origin"], ["remote", "prune", "origin"], ["remote", "get-url"], ["remote", "get-url", "a", "b"], ["remote", "-v", "add", "o", "u"],336 ["diff", "--output=/tmp/x"], ["diff", "--output", "/tmp/x"], ["diff", "--outp=/tmp/x"], ["log", "--output=/tmp/x"], ["show", "--output=x", "HEAD"],337 ["diff", "--ext-diff"], ["diff", "--ext"], ["log", "--textconv"], ["show", "--textc"], ["diff", "--no-index", "/etc/passwd", "/etc/hosts"],338 ["log", "--show-signature"],339 ]340341 @Test(arguments: refused)342 func refusesAnythingNotReadOnly(arguments: [String]) {343 #expect(throws: GitError.self) { try GitRunner.validate(arguments) }344 do {345 try GitRunner.validate(arguments)346 } catch let error as GitError {347 guard case .commandNotAllowed = error else {348 Issue.record("unexpected error \(error)")349 return350 }351 } catch {352 Issue.record("unexpected error \(error)")353 }354 }355356 @Test(arguments: [357 ["rev-parse", "--show-toplevel"], ["rev-parse", "--abbrev-ref", "HEAD"],358 ["status", "--porcelain=v2", "-z", "--branch"],359 ["log", "-n", "5", "--oneline"], ["log", "--format=%H", "--", "--output=file-named-like-an-option"],360 ["diff", "--cached", "--stat"], ["diff", "--text"], ["diff", "--no-ext-diff", "--no-textconv"], ["show", "HEAD", "--stat"],361 ["branch", "--list"], ["branch", "-a", "-vv"], ["branch", "--show-current"], ["branch", "--list", "feat*"], ["branch", "-r", "--format=%(refname)"],362 ["worktree", "list"], ["worktree", "list", "--porcelain"],363 ["remote"], ["remote", "-v"], ["remote", "get-url", "origin"], ["remote", "get-url", "--push", "origin"],364 ])365 func acceptsReadOnlyCommands(arguments: [String]) throws {366 try GitRunner.validate(arguments)367 }368369 @Test func commandLineCarriesSafetyFlags() throws {370 let argv = try GitRunner.commandLine(for: ["diff", "--cached"])371 #expect(argv.first == "--no-optional-locks")372 #expect(argv.contains("--no-pager"))373 #expect(argv.suffix(4) == ["diff", "--no-ext-diff", "--no-textconv", "--cached"])374 let statusArgv = try GitRunner.commandLine(for: ["status"])375 #expect(statusArgv.last == "status")376 #expect(!statusArgv.contains("--no-ext-diff"))377 #expect(GitRunner.environmentOverrides["GIT_TERMINAL_PROMPT"] == "0")378 #expect(GitRunner.environmentOverrides["GIT_OPTIONAL_LOCKS"] == "0")379 }380381 @Test func refusedCommandsLeaveARealRepositoryUntouched() async throws {382 let sandbox = try Sandbox()383 defer { sandbox.cleanup() }384 try sandbox.commit("a.txt", "one\n", message: "initial")385 try sandbox.write("untracked.txt", "x\n")386 let head = try sandbox.git("rev-parse", "HEAD")387 let branches = try sandbox.git("branch", "--list")388 let runner = GitRunner()389390 let attempts: [[String]] = [391 ["commit", "-a", "-m", "evil"], ["add", "-A"], ["branch", "evil"], ["checkout", "-b", "evil"], ["tag", "evil"],392 ["clean", "-fdx"], ["reset", "--hard"], ["remote", "add", "evil", "/tmp"], ["worktree", "add", "../evil"],393 ["diff", "--output=\(sandbox.repo.path)/leak.txt"], ["config", "user.name", "evil"], ["-c", "alias.x=!touch pwned", "x"],394 ]395 for arguments in attempts {396 do {397 _ = try await runner.run(arguments, in: sandbox.repo)398 Issue.record("\(arguments) was not refused")399 } catch let error as GitError {400 guard case .commandNotAllowed = error else {401 Issue.record("\(arguments): unexpected \(error)")402 continue403 }404 }405 }406 #expect(try sandbox.git("rev-parse", "HEAD") == head)407 #expect(try sandbox.git("branch", "--list") == branches)408 #expect(try sandbox.git("tag", "--list").isEmpty)409 #expect(try sandbox.git("remote").isEmpty)410 #expect(try sandbox.git("config", "--local", "user.name") == "Test User\n")411 #expect(try sandbox.git("status", "--porcelain") == "?? untracked.txt\n")412 let contents = try FileManager.default.contentsOfDirectory(atPath: sandbox.repo.path).sorted()413 #expect(contents == [".git", "a.txt", "untracked.txt"])414 #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.base.path) == ["repo"])415 }416417 @Test func runsAllowedReadsAndReportsFailures() async throws {418 let sandbox = try Sandbox()419 defer { sandbox.cleanup() }420 try sandbox.commit("a.txt", "one\n", message: "initial")421 try sandbox.git("remote", "add", "origin", "/nonexistent/remote.git")422 let runner = GitRunner()423 #expect(try await runner.run(["branch", "--show-current"], in: sandbox.repo).text == "main\n")424 #expect(try await runner.run(["remote", "get-url", "origin"], in: sandbox.repo).text == "/nonexistent/remote.git\n")425 #expect(try await runner.run(["remote", "-v"], in: sandbox.repo).text.contains("origin\t/nonexistent/remote.git (fetch)"))426 #expect(try await runner.run(["worktree", "list", "--porcelain"], in: sandbox.repo).text.hasPrefix("worktree \(sandbox.repo.path)\n"))427 #expect(try await runner.run(["show", "--stat", "--format=%s", "HEAD"], in: sandbox.repo).text.hasPrefix("initial\n"))428 let output = try await runner.run(["log", "--format=%s"], in: sandbox.repo, maxOutputBytes: 3)429 #expect(output.truncated)430 #expect(output.text == "ini")431432 do {433 _ = try await runner.run(["rev-parse", "--verify", "no-such-ref"], in: sandbox.repo)434 Issue.record("expected a failure")435 } catch let error as GitError {436 guard case .commandFailed(let status, let stderr) = error else {437 Issue.record("unexpected \(error)")438 return439 }440 #expect(status != 0)441 #expect(stderr.contains("fatal"))442 }443 await #expect(throws: GitError.self) {444 try await GitRunner(executable: "/nonexistent/git").run(["status"], in: sandbox.repo)445 }446 }447}448449@Suite struct StatusParserTests {450 @Test func parsesSyntheticPorcelainV2() {451 let records = [452 "# branch.oid 1234567890abcdef1234567890abcdef12345678",453 "# branch.head feature/x",454 "# branch.upstream origin/feature/x",455 "# branch.ab +3 -7",456 "1 .M N... 100644 100644 100644 aaa bbb path with spaces.txt",457 "2 R. N... 100644 100644 100644 aaa bbb R100 new.txt", "old.txt",458 "2 CM N... 100644 100644 100644 aaa bbb C75 copy.txt", "source.txt",459 "u AA N... 100644 100644 100644 100644 aaa bbb ccc both added.txt",460 "u DU N... 100644 100644 100644 100644 aaa bbb ccc deleted-by-us.txt",461 "1 T. N... 100644 120000 120000 aaa bbb link",462 "? new dir/",463 "! ignored.o",464 "garbage",465 ]466 let data = Data((records.joined(separator: "\0") + "\0").utf8)467 let status = GitStatus.parse(porcelainV2: data)468 #expect(status.head == .branch("feature/x"))469 #expect(status.headOID == "1234567890abcdef1234567890abcdef12345678")470 #expect(status.upstream == "origin/feature/x")471 #expect(status.ahead == 3)472 #expect(status.behind == 7)473 #expect(status.entries == [474 GitStatusEntry(kind: .changed, path: "path with spaces.txt", worktree: .modified),475 GitStatusEntry(kind: .changed, path: "new.txt", originalPath: "old.txt", index: .renamed),476 GitStatusEntry(kind: .changed, path: "copy.txt", originalPath: "source.txt", index: .copied, worktree: .modified),477 GitStatusEntry(kind: .conflicted, path: "both added.txt", index: .added, worktree: .added),478 GitStatusEntry(kind: .conflicted, path: "deleted-by-us.txt", index: .deleted, worktree: .unmerged),479 GitStatusEntry(kind: .changed, path: "link", index: .typeChanged),480 GitStatusEntry(kind: .untracked, path: "new dir/"),481 ])482 #expect(status.conflicted.count == 2)483 #expect(status.staged.map(\.path) == ["new.txt", "copy.txt", "link"])484 }485486 @Test func truncatedOutputDropsThePartialRecord() {487 let text = "# branch.oid (initial)\0# branch.head main\0? complete.txt\0? partial-na"488 let status = GitStatus.parse(porcelainV2: Data(text.utf8), truncated: true)489 #expect(status.headOID == nil)490 #expect(status.entries.map(\.path) == ["complete.txt"])491 #expect(status.isTruncated)492 #expect(!status.isClean)493 #expect(GitStatus.parse(porcelainV2: Data()).entries.isEmpty)494 }495496 @Test func modelsAreCodable() throws {497 let status = GitStatus(head: .branch("main"), headOID: "abc", upstream: "origin/main", ahead: 1, behind: 2, entries: [498 GitStatusEntry(kind: .changed, path: "a", originalPath: "b", index: .renamed, worktree: .modified),499 ])500 #expect(try JSONDecoder().decode(GitStatus.self, from: JSONEncoder().encode(status)) == status)501 let detached = GitStatus(head: .detached)502 #expect(try JSONDecoder().decode(GitStatus.self, from: JSONEncoder().encode(detached)) == detached)503 }504}505506@Suite struct ProcessExecutionTests {507 @Test func timeoutKillsTheProcess() async throws {508 let start = ContinuousClock.now509 let output = try await runProcess(executable: URL(fileURLWithPath: "/bin/sleep"), arguments: ["30"], timeout: .milliseconds(300), maxOutputBytes: 1024)510 #expect(output.timedOut)511 #expect(output.exitStatus != 0)512 #expect(ContinuousClock.now - start < .seconds(10))513 }514515 @Test func gitRunnerMapsTimeout() async throws {516 // /bin/sleep stands in for a hanging git: it ignores git's arguments' meaning and fails fast or sleeps.517 let sandbox = try Sandbox()518 defer { sandbox.cleanup() }519 let script = sandbox.base.appendingPathComponent("slow-git")520 try "#!/bin/sh\nexec /bin/sleep 30\n".write(to: script, atomically: true, encoding: .utf8)521 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path)522 let runner = GitRunner(executable: script.path, timeout: .milliseconds(300))523 await #expect(throws: GitError.timedOut) { try await runner.run(["status"], in: sandbox.repo) }524 }525526 @Test func outputIsBoundedAndProcessStopped() async throws {527 let start = ContinuousClock.now528 let output = try await runProcess(executable: URL(fileURLWithPath: "/usr/bin/yes"), arguments: [], timeout: .seconds(20), maxOutputBytes: 1000)529 #expect(output.outputTruncated)530 #expect(!output.timedOut)531 #expect(output.standardOutput.count == 1000)532 #expect(ContinuousClock.now - start < .seconds(10))533 }534535 @Test func capturesOutputStatusAndEnvironment() async throws {536 let output = try await runProcess(537 executable: URL(fileURLWithPath: "/bin/sh"),538 arguments: ["-c", "printf '%s' \"$MARK\"; printf err >&2; exit 7"],539 environment: ["MARK": "hello"], timeout: .seconds(10), maxOutputBytes: 1024540 )541 #expect(output.exitStatus == 7)542 #expect(String(decoding: output.standardOutput, as: UTF8.self) == "hello")543 #expect(String(decoding: output.standardError, as: UTF8.self) == "err")544 #expect(!output.outputTruncated && !output.timedOut)545 }546547 @Test func cancellationStopsTheProcess() async throws {548 let task = Task {549 try await runProcess(executable: URL(fileURLWithPath: "/bin/sleep"), arguments: ["30"], timeout: .seconds(60), maxOutputBytes: 1024)550 }551 try await Task.sleep(for: .milliseconds(200))552 task.cancel()553 let start = ContinuousClock.now554 await #expect(throws: CancellationError.self) { _ = try await task.value }555 #expect(ContinuousClock.now - start < .seconds(10))556 }557558 @Test func launchFailureIsReported() async {559 await #expect(throws: ProcessRunError.self) {560 _ = try await runProcess(executable: URL(fileURLWithPath: "/nonexistent/tool"), arguments: [], timeout: .seconds(1), maxOutputBytes: 10)561 }562 }563}564