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
@@ -11,8 +11,6 @@ import Testing
#expect(c.editor.tabSize == 4)
#expect(c.editor.wordWrap == .markdown)
#expect(c.git.confirmDiscard)
#expect(!c.git.confirmStage)
#expect(!c.git.confirmUnstage)
#expect(c.git.defaultDiffMode == .updated)
#expect(c.git.refreshInterval == 10_000)
#expect(c.files.exclude.isEmpty)
@@ -31,13 +29,20 @@ import Testing
}
@Test func anOlderOriginalDefaultDiffModeDecodesAsUpdated() throws {
let json = #"{"git":{"defaultDiffMode":"original","confirmStage":true}}"#
let json = #"{"git":{"defaultDiffMode":"original"}}"#
let c = try JSONDecoder().decode(HelderConfig.self, from: Data(json.utf8))
#expect(c.git.defaultDiffMode == .updated)
#expect(c.git.confirmStage)
#expect(ViewMode(c.git.defaultDiffMode) == .actual)
}
@Test func theRemovedStageConfirmKeysStillDecode() throws {
let json = #"{"git":{"confirmStage":true,"confirmUnstage":true,"confirmDiscard":false,"refreshInterval":5000}}"#
let c = try JSONDecoder().decode(HelderConfig.self, from: Data(json.utf8))
#expect(!c.git.confirmDiscard)
#expect(c.git.refreshInterval == 5000)
#expect(HelderConfig.resolved(overrides: Data(json.utf8)).git.refreshInterval == 5000)
}
@Test func sparseOverridesMergeKeyByKey() {
let json = ##"{"editor":{"tabSize":2},"terminal":{"fontSize":14,"theme":{"red":"#FF0000"}},"files":{"exclude":["*.log"]}}"##
let c = HelderConfig.resolved(overrides: Data(json.utf8))
@@ -58,7 +58,7 @@ import Testing
@Test func fileGitRowAndRootMenusKeepTheirHeader() {
#expect(ContextActions.header(for: .file(path: "src/a.php"), projectName: "app") == "src/a.php")
#expect(ContextActions.header(for: .gitRow(path: "src/a.php", staged: false), projectName: "app") == "src/a.php")
#expect(ContextActions.header(for: .gitRow(path: "src/a.php", isDeleted: false), projectName: "app") == "src/a.php")
#expect(ContextActions.header(for: .projectRoot, projectName: "app") == "app/")
}
@@ -122,15 +122,37 @@ import Testing
.action(.readAloudFile("docs/guide.md"), label: "Read aloud"),
.separator,
])
#expect(readAloud(.gitRow(path: "README.md", staged: true)) == [.action(.readAloudFile("README.md"), label: "Read aloud")])
}
@Test func otherFilesCannot() {
#expect(readAloud(.file(path: "src/app.php")).isEmpty)
#expect(readAloud(.gitRow(path: "src/app.php", staged: false)).isEmpty)
#expect(readAloud(.directory(path: "docs")).isEmpty)
}
@Test func aGitRowOpensInTheEditorThenPassesOnItsPath() {
#expect(ContextActions.entries(for: .gitRow(path: "src/a.php", isDeleted: false)) == [
.action(.openFile("src/a.php"), label: "Open in editor"),
.separator,
.action(.passOnReference("src/a.php", code: nil), label: "Pass on reference"),
.action(.copyReference("src/a.php"), label: "Copy reference"),
])
#expect(ContextActions.entries(for: .gitRow(path: "gone.php", isDeleted: true)) == [
.action(.passOnReference("gone.php", code: nil), label: "Pass on reference"),
.action(.copyReference("gone.php"), label: "Copy reference"),
])
#expect(ContextAction.openFile("src/a.php").isEmphasized)
}
@Test func theCommitMenuOffersCommitAndABoldCommitAndPush() {
#expect(ContextActions.header(for: .commitMenu, projectName: "app") == "")
#expect(ContextActions.entries(for: .commitMenu) == [
.action(.commit(andPush: false), label: "Commit"),
.action(.commit(andPush: true), label: "Commit and push"),
])
#expect(ContextAction.commit(andPush: true).isEmphasized)
#expect(!ContextAction.commit(andPush: false).isEmphasized)
}
@Test func aSelectionCanBeReadAloudAfterCopyReference() {
let reference = AgentReference(path: "src/a.php", startLine: 3, endLine: 4)
#expect(ContextActions.entries(for: .editor(reference: reference, code: "$a = 1;", showDiffLine: 3)) == [
@@ -0,0 +1,43 @@
import HelderCore
import Testing
@Suite struct GitBranchesTests {
@Test("refs split into sorted local and origin branches without origin/HEAD")
func parse() {
let raw = """
refs/heads/main
refs/heads/feature/b
refs/heads/feature/a
refs/remotes/origin/HEAD
refs/remotes/origin/main
refs/remotes/origin/feature/c
refs/remotes/upstream/main
"""
let list = GitBranchParsing.parse(raw)
#expect(list.local == ["feature/a", "feature/b", "main"])
#expect(list.remote == ["origin/feature/c", "origin/main"])
}
@Test("empty output is no branches")
func empty() {
#expect(GitBranchParsing.parse("") == .empty)
}
@Test("a remote branch checks out under its name without the remote", arguments: [
("origin/main", "main"),
("origin/feature/a", "feature/a"),
("main", "main"),
])
func localName(remote: String, local: String) {
#expect(GitBranchList.localName(ofRemote: remote) == local)
}
@Test("a remote branch is tracked when its local name exists")
func tracked() {
let list = GitBranchList(local: ["main", "feature/a"], remote: ["origin/main", "origin/feature/a", "origin/other"])
#expect(list.isTracked("origin/main"))
#expect(list.isTracked("origin/feature/a"))
#expect(!list.isTracked("origin/other"))
}
}
@@ -0,0 +1,122 @@
import HelderCore
import Testing
@Suite struct GitConsoleTests {
// MARK: commandLine
@Test("the echo quotes only what needs quotes", arguments: [
(["status"], "$ git status"),
(["commit", "-m", "fix the bar"], "$ git commit -m \"fix the bar\""),
(["commit", "-m", "say \"hi\""], "$ git commit -m \"say \\\"hi\\\"\""),
(["commit", "-m", "it's"], "$ git commit -m \"it's\""),
(["commit", "-m", ""], "$ git commit -m \"\""),
(["add", "--", "pages/[id].vue"], "$ git add -- pages/[id].vue"),
])
func commandLine(arguments: [String], expected: String) {
#expect(GitConsoleText.commandLine(arguments) == expected)
}
// MARK: parseInput
@Test("typed input splits like a shell", arguments: [
("status", ["status"]),
(" git status ", ["status"]),
("git commit -m \"fix the bar\"", ["commit", "-m", "fix the bar"]),
("commit -m 'it is \"fine\"'", ["commit", "-m", "it is \"fine\""]),
("commit -m \"say \\\"hi\\\"\"", ["commit", "-m", "say \"hi\""]),
("commit -m \"a\\nb\"", ["commit", "-m", "a\\nb"]),
("commit -m \"\"", ["commit", "-m", ""]),
("log --format='%h %s'", ["log", "--format=%h %s"]),
("add my\\ file.txt", ["add", "my file.txt"]),
("commit -m \"unclosed", ["commit", "-m", "unclosed"]),
])
func parseInput(input: String, expected: [String]) {
#expect(GitConsoleText.parseInput(input) == expected)
}
@Test("nothing to run is nil", arguments: ["", " ", "git", " git "])
func parseNothing(input: String) {
#expect(GitConsoleText.parseInput(input) == nil)
}
// MARK: syncLabel
@Test("the sync label names the remote", arguments: [
(0, 2, "origin/main", "2 behind origin"),
(1, 2, "origin/main", "1 ahead · 2 behind origin"),
(1, 0, "origin/main", "1 ahead of origin"),
(0, 0, "origin/feature/x", "in sync with origin"),
(0, 0, "upstream/main", "in sync with upstream"),
(3, 0, nil, "no upstream"),
] as [(Int, Int, String?, String)])
func syncLabel(ahead: Int, behind: Int, upstream: String?, expected: String) {
#expect(GitConsoleText.syncLabel(ahead: ahead, behind: behind, upstream: upstream) == expected)
}
// MARK: classifier
@Test("hints and errors are recognised for any command, whatever the stream", arguments: [
("hint: Updates were rejected", GitLineKind.hint),
("error: failed to push some refs", .error),
("fatal: not a git repository", .error),
(" ! [rejected] main -> main (fetch first)", .error),
(" ! [remote rejected] main -> main (pre-receive hook declined)", .error),
("Aborting", .error),
("Please commit your changes or stash them before you switch branches.", .error),
("Already up to date.", .output),
])
func generic(line: String, kind: GitLineKind) {
var classifier = GitOutputClassifier(arguments: ["pull"])
#expect(classifier.classify(line, isError: true) == kind)
var other = GitOutputClassifier(arguments: ["push"])
#expect(other.classify(line, isError: false) == kind)
}
@Test("stderr progress is plain output")
func progressIsOutput() {
var classifier = GitOutputClassifier(arguments: ["push"])
#expect(classifier.classify("Writing objects: 100% (3/3), 280 bytes | 280.00 KiB/s, done.", isError: true) == .output)
#expect(classifier.classify("To github.com:x/y.git", isError: true) == .output)
}
@Test("a push ref update is a success", arguments: [
" a1b2c3d..e4f5a6b main -> main",
" * [new branch] feature/x -> feature/x",
" + a1b2c3d...e4f5a6b main -> main (forced update)",
])
func pushSuccess(line: String) {
var classifier = GitOutputClassifier(arguments: ["push", "-u", "origin", "main"])
#expect(classifier.classify(line, isError: true) == .success)
}
@Test("a ref update outside push is plain output")
func refUpdateOutsidePush() {
var classifier = GitOutputClassifier(arguments: ["fetch"])
#expect(classifier.classify(" a1b2c3d..e4f5a6b main -> origin/main", isError: true) == .output)
}
@Test("status paths take the kind of their section")
func statusSections() {
var classifier = GitOutputClassifier(arguments: ["-c", "color.ui=never", "status"])
let lines: [(String, GitLineKind)] = [
("On branch main", .output),
("Changes to be committed:", .output),
(" (use \"git restore --staged <file>...\" to unstage)", .output),
("\tmodified: a.txt", .staged),
("Changes not staged for commit:", .output),
("\tmodified: b.txt", .unstaged),
("Untracked files:", .output),
("\tnew.txt", .unstaged),
]
for (line, kind) in lines {
#expect(classifier.classify(line, isError: false) == kind, "\(line)")
}
}
@Test("tab lines outside status are plain output")
func tabLinesOutsideStatus() {
var classifier = GitOutputClassifier(arguments: ["commit"])
_ = classifier.classify("Changes to be committed:", isError: false)
#expect(classifier.classify("\tmodified: a.txt", isError: false) == .output)
}
}
@@ -21,6 +21,15 @@ import Testing
#expect(state.fileDiffs["a.txt"]?.isTooBig == false)
}
@Test("behind and upstream pass through from the snapshot")
func behindAndUpstream() {
let state = GitDerivation.derive(GitSnapshot(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", changes: []))
#expect(state.behind == 2)
#expect(state.upstream == "origin/main")
#expect(GitDerivation.derive(nil).upstream == nil)
#expect(GitDerivation.derive(nil).behind == 0)
}
@Test("no snapshot means not a repository")
func notARepository() {
let state = GitDerivation.derive(nil)
@@ -105,48 +114,8 @@ import Testing
}
@Suite struct SourceControlTextTests {
private func change(_ path: String, staged: Bool = false) -> Change {
Change(path: path, status: .modified, added: 1, removed: 0, staged: staged)
}
@Test("one group per folder, even when git returns the folder in separate runs")
func oneGroupPerFolder() {
let groups = SourceControlText.groupByDir([
change("tests/Feature/AlphaTest.php"), change("app/Models/User.php"), change("tests/Feature/BetaTest.php"),
])
#expect(groups.map(\.dir) == ["tests/Feature", "app/Models"])
#expect(groups[0].rows.map(\.path) == ["tests/Feature/AlphaTest.php", "tests/Feature/BetaTest.php"])
}
@Test("every row is kept, so the keyboard cursor walks the full list")
func keepsEveryRow() {
let list = ["a/one.ts", "b/two.ts", "a/three.ts", "four.ts"].map { change($0) }
let flat = SourceControlText.groupByDir(list).flatMap(\.rows)
#expect(flat.count == list.count)
#expect(Set(flat.map(\.id)).count == list.count)
}
@Test("a project-root file sits in the empty-string group")
func rootGroup() {
#expect(SourceControlText.groupByDir([change("README.md")]) == [ChangeGroup(dir: "", rows: [change("README.md")])])
}
@Test("navigation walks staged groups before unstaged ones")
func navigationOrder() {
let order = SourceControlText.navigationOrder([change("b/x"), change("a/y", staged: true), change("b/z")])
#expect(order.map(\.path) == ["a/y", "b/x", "b/z"])
}
@Test("a dictated commit message becomes one lowercase line")
func commitMessage() {
#expect(SourceControlText.normalizeCommitMessage("Fix The Bug\n In Parser \r\n") == "fix the bug in parser ")
}
@Test("the push tooltip counts commits")
func pushTooltip() {
#expect(SourceControlText.pushTooltip(canPush: false, ahead: 0) == "Nothing to push (⌘P)")
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 1) == "Push 1 commit to remote (⌘P)")
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 3) == "Push 3 commits to remote (⌘P)")
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 0) == "Push the branch to remote (⌘P)")
}
}
@@ -0,0 +1,132 @@
import HelderCore
import Testing
@Suite struct GitSectionsTests {
private func row(_ path: String, _ status: GitStatus, staged: Bool) -> Change {
Change(path: path, status: status, added: 1, removed: 0, staged: staged)
}
// MARK: build
@Test("rows land in the fixed section order, keeping their own order")
func build() {
let rows = [
row("gone.txt", .deleted, staged: false),
row("new.txt", .added, staged: false),
row("b.txt", .modified, staged: false),
row("staged-delete.txt", .deleted, staged: true),
row("a.txt", .modified, staged: false),
row("staged-add.txt", .added, staged: true),
]
let sections = GitSections.build(rows)
#expect(sections.map(\.kind) == [.staged, .changed, .untracked, .deleted])
#expect(sections.map(\.id) == ["staged", "changed", "untracked", "deleted"])
#expect(sections[0].rows.map(\.path) == ["staged-delete.txt", "staged-add.txt"])
#expect(sections[1].rows.map(\.path) == ["b.txt", "a.txt"])
#expect(sections[2].rows.map(\.path) == ["new.txt"])
#expect(sections[3].rows.map(\.path) == ["gone.txt"])
}
@Test("unstaged renames and conflicts count as changed", arguments: [GitStatus.modified, .renamed, .unmerged])
func changed(status: GitStatus) {
#expect(GitSections.build([row("x", status, staged: false)]).map(\.kind) == [.changed])
}
@Test("empty sections are left out")
func emptySections() {
#expect(GitSections.build([]).isEmpty)
#expect(GitSections.build([row("gone", .deleted, staged: false)]).map(\.kind) == [.deleted])
}
@Test("unique paths keep the first occurrence")
func uniquePaths() {
let rows = [row("a", .modified, staged: true), row("b", .added, staged: false), row("a", .modified, staged: false)]
#expect(GitSections.uniquePaths(rows) == ["a", "b"])
}
// MARK: inline diff
private func lines(_ count: Int, changing changed: Int? = nil) -> (String, String) {
let original = (1...count).map { "line \($0)\n" }.joined()
let updated = (1...count).map { $0 == changed ? "line \($0) edited\n" : "line \($0)\n" }.joined()
return (original, updated)
}
@Test("a diff without changes has no rows")
func noChanges() {
let diff = LineDiff.build(original: "a\nb\n", updated: "a\nb\n")
#expect(InlineDiff.rows(from: diff).isEmpty)
}
@Test("unchanged runs beyond the context fold into gaps, leading and trailing included")
func gaps() {
let (original, updated) = lines(20, changing: 10)
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated))
#expect(rows.count == 9)
#expect(rows.first == .gap(6))
#expect(rows.last == .gap(7))
guard case let .line(left, right) = rows[1] else { Issue.record("expected a line"); return }
#expect(left?.number == 7)
#expect(right?.number == 7)
#expect(left?.mark == nil)
}
@Test("a change near the edge keeps every row up to it")
func noLeadingGap() {
let (original, updated) = lines(5, changing: 2)
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated), context: 1)
#expect(rows.count == 4)
#expect(rows.last == .gap(2))
}
@Test("two changes whose context touches share one run")
func mergedContext() {
let original = (1...10).map { "\($0)\n" }.joined()
let updated = original.replacingOccurrences(of: "3\n", with: "x\n").replacingOccurrences(of: "8\n", with: "y\n")
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated), context: 2)
#expect(!rows.contains { if case .gap = $0 { true } else { false } })
#expect(rows.count == 10)
}
@Test("a replaced line highlights the differing middle on both sides")
func highlight() {
let diff = LineDiff.build(original: "let a = 1\n", updated: "let a = 22\n")
let rows = InlineDiff.rows(from: diff)
#expect(rows == [.line(
left: InlineDiffCell(number: 1, text: "let a = 1", mark: .removed, highlight: 8..<9),
right: InlineDiffCell(number: 1, text: "let a = 22", mark: .added, highlight: 8..<10)
)])
}
@Test("an insertion highlights only the side that grew")
func highlightOneSide() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "foo()\n", updated: "foo(bar)\n"))
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
#expect(left?.highlight == nil)
#expect(right?.highlight == 4..<7)
}
@Test("lines with nothing in common get no highlight")
func noCommonPart() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "abc\n", updated: "xyz\n"))
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
#expect(left?.mark == .removed)
#expect(right?.mark == .added)
#expect(left?.highlight == nil)
#expect(right?.highlight == nil)
}
@Test("prefix and suffix never overlap on a repeated character")
func noOverlap() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "aa\n", updated: "aaa\n"))
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
#expect(left?.highlight == nil)
#expect(right?.highlight == 2..<3)
}
@Test("an added line alone has no highlight")
func unpaired() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "a\n", updated: "a\nb\n"))
#expect(rows.last == .line(left: nil, right: InlineDiffCell(number: 2, text: "b", mark: .added)))
}
}
+32 -8
View File
@@ -51,6 +51,30 @@ import Testing
#expect(result.canPush == canPush)
}
@Test("the behind count comes from the header", arguments: [
("main...origin/main [ahead 1, behind 2]", 2),
("main...origin/main [behind 5]", 5),
("main...origin/main [ahead 3]", 0),
("main...origin/main", 0),
("feature/x", 0),
("HEAD (no branch)", 0),
])
func behind(header: String, count: Int) {
#expect(Porcelain.parseBehind(header: header) == count)
}
@Test("the upstream comes from the header", arguments: [
("main...origin/main [ahead 1, behind 2]", "origin/main"),
("feature/x...origin/feature/x", "origin/feature/x"),
("main...origin/main [gone]", "origin/main"),
("main", nil),
("No commits yet on main", nil),
("HEAD (no branch)", nil),
] as [(String, String?)])
func upstream(header: String, name: String?) {
#expect(Porcelain.parseUpstream(header: header) == name)
}
@Test("the branch name comes from the header", arguments: [
("main...origin/main [ahead 1]", "main"),
("main", "main"),
@@ -72,6 +96,8 @@ import Testing
#expect(parsed.branch == "main")
#expect(parsed.ahead == 2)
#expect(parsed.canPush)
#expect(parsed.behind == 0)
#expect(parsed.upstream == "origin/main")
#expect(parsed.entries == [
StatusEntry(index: " ", working: "M", path: "src/a.ts"),
StatusEntry(index: "?", working: "?", path: "new file.txt"),
@@ -107,6 +133,12 @@ import Testing
#expect(parsed.entries.count == 1)
}
@Test("a header ahead and behind carries both counts and the upstream")
func aheadAndBehind() {
let parsed = Porcelain.parseStatus("## main...origin/main [ahead 1, behind 2]\0")
#expect(parsed == ParsedStatus(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", entries: []))
}
@Test("empty output is a clean tree")
func empty() {
#expect(Porcelain.parseStatus("") == ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []))
@@ -120,14 +152,6 @@ import Testing
// MARK: push
@Test("a push toast prefers the ref line, a failure its last line")
func pushSummary() {
let ok = Porcelain.pushSummary(exitCode: 0, stdout: "", stderr: "To github.com:x/y.git\n abc..def main -> main\n")
#expect(ok == PushResult(ok: true, message: "abc..def main -> main"))
let failed = Porcelain.pushSummary(exitCode: 1, stdout: "", stderr: "error: failed to push\nhint: pull first\n")
#expect(failed == PushResult(ok: false, message: "hint: pull first"))
}
@Test("a missing upstream is detected from git's hint")
func needsUpstream() {
#expect(Porcelain.needsUpstream(stderr: "fatal: The current branch x has no upstream branch."))
@@ -4,7 +4,7 @@ import Testing
@Suite struct ColumnLayoutTests {
@Test func roomyWindowUsesTheDesignRatios() {
let w = ColumnLayout.fluid(windowWidth: 1760, focus: .terminal)
#expect(w == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480))
#expect(w == ColumnWidths(explorer: 289, agent: 480))
}
@Test func tightWindowFollowsFocus() {
@@ -13,52 +13,45 @@ import Testing
}
@Test func fittingKeepsTheEditorMinimum() {
let fitted = ColumnLayout.fitted(ColumnWidths(sourceControl: 400, explorer: 400, agent: 400), windowWidth: 1000, visible: .all)
#expect(fitted.sourceControl + fitted.explorer + fitted.agent <= 1000 - 3 - ColumnLayout.minEditorWidth)
}
@Test func aHiddenColumnIsNeitherCountedNorScaled() {
let widths = ColumnWidths(sourceControl: 400, explorer: 400, agent: 400)
let visible = ColumnVisibility(sourceControl: false)
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible)
#expect(fitted.sourceControl == 400)
let fitted = ColumnLayout.fitted(ColumnWidths(explorer: 400, agent: 600), windowWidth: 1000, visible: .all)
#expect(fitted.explorer + fitted.agent <= 1000 - 2 - ColumnLayout.minEditorWidth)
}
@Test func withTheEditorHiddenTheAgentIsTheFlexColumn() {
let widths = ColumnWidths(sourceControl: 400, explorer: 400, agent: 900)
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: ColumnVisibility(editor: false))
#expect(fitted.agent == 900)
#expect(fitted.sourceControl + fitted.explorer <= 1000 - 2 - ColumnLayout.minEditorWidth)
}
@Test func withoutAFlexColumnTheFixedOnesOnlyHaveToFitTheWindow() {
let widths = ColumnWidths(sourceControl: 300, explorer: 300, agent: 480)
let visible = ColumnVisibility(editor: false, agent: false)
#expect(ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible) == widths)
let narrow = ColumnLayout.fitted(widths, windowWidth: 501, visible: visible)
#expect(narrow.sourceControl + narrow.explorer <= 500)
#expect(narrow.agent == 480)
}
@Test func fittingWithOnlyTheAgentBesideTheEditor() {
let widths = ColumnWidths(sourceControl: 300, explorer: 300, agent: 900)
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: ColumnVisibility(sourceControl: false, explorer: false))
#expect(fitted.sourceControl == 300)
@Test func aHiddenColumnIsNeitherCountedNorScaled() {
let widths = ColumnWidths(explorer: 400, agent: 900)
let visible = ColumnVisibility(explorer: false)
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible)
#expect(fitted.explorer == 400)
#expect(fitted.agent <= 1000 - 1 - ColumnLayout.minEditorWidth)
#expect(fitted.agent >= 1000 - 2 - ColumnLayout.minEditorWidth)
}
@Test func withTheEditorHiddenTheAgentIsTheFlexColumn() {
let widths = ColumnWidths(explorer: 900, agent: 900)
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: ColumnVisibility(editor: false))
#expect(fitted.agent == 900)
#expect(fitted.explorer <= 1000 - 1 - ColumnLayout.minEditorWidth)
}
@Test func withoutAFlexColumnTheFixedOnesOnlyHaveToFitTheWindow() {
let widths = ColumnWidths(explorer: 400, agent: 480)
let visible = ColumnVisibility(editor: false, agent: false)
#expect(ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible) == widths)
let narrow = ColumnLayout.fitted(widths, windowWidth: 300, visible: visible)
#expect(narrow.explorer <= 300)
#expect(narrow.agent == 480)
}
@Test func splittersSitOnlyBetweenVisibleColumns() {
#expect(ColumnVisibility.all.splitterCount == 3)
#expect(ColumnVisibility(sourceControl: false, editor: false).splitterCount == 1)
#expect(ColumnVisibility(sourceControl: false, explorer: false, editor: false, agent: false).splitterCount == 0)
#expect(ColumnVisibility.all.splitterCount == 2)
#expect(ColumnVisibility(editor: false).splitterCount == 1)
#expect(ColumnVisibility(explorer: false, editor: false, agent: false).splitterCount == 0)
}
@Test func theAgentLimitCountsOnlyVisibleColumns() {
let widths = ColumnWidths(sourceControl: 300, explorer: 300, agent: 480)
#expect(ColumnLayout.maxAgentWidth(windowWidth: 1600, widths: widths, visible: .all) == 1600 - 3 - 600 - ColumnLayout.minEditorWidth)
let widths = ColumnWidths(explorer: 300, agent: 480)
#expect(ColumnLayout.maxAgentWidth(windowWidth: 1600, widths: widths, visible: .all) == 1600 - 2 - 300 - ColumnLayout.minEditorWidth)
#expect(ColumnLayout.maxAgentWidth(windowWidth: 1600, widths: widths, visible: ColumnVisibility(explorer: false))
== 1600 - 2 - 300 - ColumnLayout.minEditorWidth)
== 1600 - 1 - ColumnLayout.minEditorWidth)
}
}
@@ -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)) }
}
}
@@ -7,26 +7,24 @@ import Testing
@Test func addingActionsAreTeal() {
#expect(ContextMenuOverlay.tint(for: .newFile(inDirectory: "")) == .add)
#expect(ContextMenuOverlay.tint(for: .newFolder(inDirectory: "src")) == .add)
#expect(ContextMenuOverlay.tint(for: .stage("a.php")) == .add)
}
@Test func finderUnstageAndCopyFileNameAreAmberSoft() {
@Test func finderAndCopyFileNameAreAmberSoft() {
#expect(ContextMenuOverlay.tint(for: .revealInFinder("a.php")) == .modify)
#expect(ContextMenuOverlay.tint(for: .unstage("a.php")) == .modify)
#expect(ContextMenuOverlay.tint(for: .copyFileName("a.php")) == .modify)
}
@Test func passOnOpenDiffAndRenameAreGrey() {
@Test func passOnShowDiffAndRenameAreGrey() {
#expect(ContextMenuOverlay.tint(for: .passOnReference("a.php", code: nil)) == .rename)
#expect(ContextMenuOverlay.tint(for: .passOnFileName("a.php")) == .rename)
#expect(ContextMenuOverlay.tint(for: .bouwen("x")) == .rename)
#expect(ContextMenuOverlay.tint(for: .openDiff("a.php")) == .rename)
#expect(ContextMenuOverlay.tint(for: .showDiff("a.php", line: 3)) == .rename)
#expect(ContextMenuOverlay.tint(for: .rename("a.php", isDirectory: false)) == .rename)
}
@Test func showDiffWearsTheOpenDiffIcon() {
#expect(ContextMenuOverlay.symbol(for: .showDiff("a.php", line: 3)) == ContextMenuOverlay.symbol(for: .openDiff("a.php")))
@Test func theGitViewItemsKeepThePlainIcon() {
#expect(ContextMenuOverlay.tint(for: .openFile("a.php")) == .plain)
#expect(ContextMenuOverlay.tint(for: .commit(andPush: true)) == .plain)
}
@Test func copyReferenceKeepsThePlainIconThatTurnsAmberOnHighlight() {
@@ -35,7 +33,7 @@ import Testing
}
@Test func destructiveActionsAreAmberDeep() {
#expect(ContextMenuOverlay.tint(for: .discard("a.php")) == .danger)
#expect(ContextMenuOverlay.tint(for: .gitDiscard(["a.php"])) == .danger)
#expect(ContextMenuOverlay.tint(for: .delete("a", isDirectory: true)) == .danger)
}
}
@@ -13,7 +13,7 @@ import Testing
let listed = Set(ShortcutCatalog.groups.flatMap(\.rows).map { $0.keys.joined() })
let handled = ["⌘F", "⌘↑↓", "↵", "⌘←→", "↑↓", "⇧⌘O", "⌘O", "⌘→", "⌘P",
"⌘C", "⌘↵", "⌘G", "⌘M", "⌘S", "⌘.", "⌘A", "⌘L", "Esc",
"⌘W", "⌘R", "⇧⌘N", "?", "⌘click", "⌘0", "⌘+", "⌘−"]
"⌘W", "⌘R", "⇧⌘N", "?", "⌘click", "⌘0", "⌘+", "⌘−", "⌘1", "⌘2", "⌘3"]
#expect(Set(handled).subtracting(listed).isEmpty)
}
@@ -218,15 +218,17 @@ private func makeModel(results: [String: [ContentGroup]] = [:], delays: [String:
#expect(model.emptyMessage(for: .files) == "No file names match.")
}
@Test func theFocusedColumnTakesSeventyPercentAndTheSidesKeepTheirMinimum() {
let three: [SearchModel.Column] = [.thisFile, .project, .files]
let resting = SearchModel.widths(total: 1000, columns: three, focused: .project)
#expect(resting[.thisFile] == 230)
#expect(resting[.files] == 250)
#expect(resting[.project] == 520)
let files = SearchModel.widths(total: 1000, columns: three, focused: .files)
#expect(files[.files] == 700)
#expect(files[.thisFile] == 180)
#expect(files[.project] == 120)
@Test func withThisFileTheColumnsTakeThirtyFortyFiveAndTwentyFivePercent() {
let widths = SearchModel.widths(total: 1000, columns: [.thisFile, .project, .files])
#expect(widths[.thisFile] == 300)
#expect(widths[.project] == 450)
#expect(widths[.files] == 250)
}
@Test func withoutThisFileTheColumnsTakeSixtyFiveAndThirtyFivePercent() {
let widths = SearchModel.widths(total: 1000, columns: [.project, .files])
#expect(widths[.thisFile] == nil)
#expect(widths[.project] == 650)
#expect(widths[.files] == 350)
}
}
+54 -7
View File
@@ -9,6 +9,7 @@ import Testing
@Test(arguments: [
("p", Command.push), ("s", .save), ("m", .cycleMode), ("g", .toggleGit),
("l", .toggleAutoFit), (".", .toggleHidden), ("w", .closeFileOrWindow),
("1", .togglePane(.explorer)), ("2", .togglePane(.editor)), ("3", .togglePane(.terminal)),
])
func commandLettersMapToTheirCommand(key: String, command: Command) {
#expect(route(cmd(key)) == .perform(command))
@@ -41,9 +42,16 @@ import Testing
#expect(route(cmd("c"), KeyContext(owner: .terminal, hasTextSelection: true)) == .pass)
}
@Test func commandEnterCommitsExceptInTheCommitBoxItself() {
#expect(route(KeyPress(.enter, command: true)) == .perform(.commit))
#expect(route(KeyPress(.enter, command: true), KeyContext(owner: .text(in: .sourceControl))) == .pass)
@Test func commandEnterCommitsOnlyOverTheGitView() {
#expect(route(KeyPress(.enter, command: true)) == .pass)
#expect(route(KeyPress(.enter, command: true), KeyContext(owner: .text(in: .editor))) == .pass)
#expect(route(KeyPress(.enter, command: true), KeyContext(gitViewOpen: true)) == .perform(.commit))
}
@Test func commandEnterInTheGitConsoleStaysWithTheConsole() {
let console = KeyContext(owner: .text(in: nil), gitViewOpen: true, inGitConsole: true)
#expect(route(KeyPress(.enter, command: true), console) == .pass)
#expect(route(cmd("p"), console) == .perform(.push))
}
@Test func arrowsMoveTheRowCursorOnlyInAListWithoutAField() {
@@ -52,12 +60,12 @@ import Testing
#expect(route(KeyPress(.up), list) == .perform(.moveRowCursor(-1)))
#expect(route(KeyPress(.enter), list) == .perform(.openSelectedRow))
#expect(route(KeyPress(.down), KeyContext(activePanel: .editor)) == .pass)
#expect(route(KeyPress(.down), KeyContext(owner: .text(in: .sourceControl), activePanel: .sourceControl)) == .pass)
#expect(route(KeyPress(.down), KeyContext(owner: .text(in: .explorer), activePanel: .explorer)) == .pass)
#expect(route(KeyPress(.enter), KeyContext(owner: .terminal, activePanel: .terminal)) == .pass)
}
@Test func commandRightOpensTheRowMenuPassesASelectionOrMovesFocus() {
#expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .sourceControl)) == .perform(.openRowMenu))
#expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .explorer)) == .perform(.openRowMenu))
let selection = TextSelectionInfo(text: "x", startLine: 3, endLine: 4)
#expect(route(KeyPress(.right, command: true), KeyContext(owner: .text(in: .editor), editorTextSelection: selection))
== .perform(.passSelection(selection)))
@@ -83,7 +91,7 @@ import Testing
@Test func questionMarkOpensHelpButTypesInAField() {
#expect(route(KeyPress(.character("?"), shift: true)) == .perform(.showShortcuts))
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .text(in: .sourceControl))) == .pass)
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .text(in: .editor))) == .pass)
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .terminal)) == .pass)
}
@@ -93,6 +101,45 @@ import Testing
#expect(route(KeyPress(.escape), KeyContext(owner: .terminal)) == .pass)
}
@Test func commandGTogglesTheGitViewFromAnywhere() {
#expect(route(cmd("g")) == .perform(.toggleGit))
#expect(route(cmd("g"), KeyContext(owner: .terminal)) == .perform(.toggleGit))
#expect(route(cmd("g"), KeyContext(owner: .text(in: nil), gitViewOpen: true)) == .perform(.toggleGit))
}
@Test func escapeClosesTheGitViewOnlyWhenNoOverlayIsOpen() {
let git = KeyContext(gitViewOpen: true)
#expect(route(KeyPress(.escape), git) == .perform(.closeGitView))
#expect(route(KeyPress(.escape), KeyContext(owner: .text(in: nil), gitViewOpen: true)) == .perform(.closeGitView))
#expect(route(KeyPress(.escape), KeyContext(overlay: .other, gitViewOpen: true)) == .perform(.dismissOverlay))
#expect(route(KeyPress(.escape), KeyContext(overlay: .diff(busy: false), gitViewOpen: true)) == .perform(.dismissOverlay))
#expect(route(KeyPress(.escape), KeyContext(overlay: .diff(busy: true), gitViewOpen: true)) == .pass)
#expect(route(KeyPress(.escape)) == .pass)
}
@Test func overTheGitViewCommitPushAndSearchWorkFromItsFields() {
let field = KeyContext(owner: .text(in: nil), gitViewOpen: true)
#expect(route(KeyPress(.enter, command: true), field) == .perform(.commit))
#expect(route(cmd("p"), field) == .perform(.push))
#expect(route(cmd("f"), field) == .perform(.showSearch(seed: "")))
#expect(route(cmd("g"), field) == .perform(.toggleGit))
#expect(route(cmd("2"), field) == .perform(.togglePane(.editor)))
}
@Test func overTheGitViewTheColumnKeysRestAndTypingReachesTheField() {
let git = KeyContext(activePanel: .explorer, focusZone: .editor, recentFileCount: 3, gitViewOpen: true)
#expect(route(KeyPress(.down), git) == .pass)
#expect(route(KeyPress(.enter), git) == .pass)
#expect(route(KeyPress(.right, command: true), git) == .pass)
#expect(route(KeyPress(.left, command: true), git) == .pass)
#expect(route(KeyPress(.down, command: true), git) == .pass)
#expect(route(cmd("a"), git) == .pass)
let field = KeyContext(owner: .text(in: nil), gitViewOpen: true)
#expect(route(KeyPress(.character("x")), field) == .pass)
#expect(route(KeyPress(.character("?"), shift: true), field) == .pass)
#expect(route(cmd("c"), KeyContext(owner: .text(in: nil), hasTextSelection: true, gitViewOpen: true)) == .pass)
}
@Test func anOpenOverlayOwnsEveryOtherKey() {
let search = KeyContext(overlay: .other, activePanel: .explorer)
#expect(route(cmd("g"), search) == .pass)
@@ -125,7 +172,7 @@ import Testing
#expect(route(cmd("p"), diff) == .perform(.push))
#expect(route(cmd("s"), diff) == .perform(.save))
#expect(route(cmd("c"), diff) == .perform(.focusCommitMessage))
#expect(route(KeyPress(.enter, command: true), diff) == .perform(.commit))
#expect(route(KeyPress(.enter, command: true), diff) == .pass)
#expect(route(KeyPress(.down, command: true), KeyContext(overlay: .diff(busy: false), focusZone: .editor, recentFileCount: 2))
== .perform(.showRecentFiles(initialSelection: 1)))
#expect(route(KeyPress(.escape), diff) == .perform(.dismissOverlay))
@@ -1,7 +1,7 @@
import Foundation
import HelderCore
import HelderServices
import HelderUI
@testable import HelderUI
import Testing
@MainActor
@@ -13,6 +13,7 @@ import Testing
("src/a.php", .modified, false),
("config/app.json", .modified, true),
("src/c.php", .deleted, false),
("new.txt", .added, false),
])
private func makeStore(_ snapshot: GitSnapshot? = nil) async -> (SourceControlStore, FakeGit, Recorder) {
@@ -24,22 +25,26 @@ import Testing
return (store, git, recorder)
}
private func texts(_ store: SourceControlStore) -> [String] { store.lines.map(\.line.text) }
private func kinds(_ store: SourceControlStore) -> [GitLineKind] { store.lines.map(\.line.kind) }
// MARK: Loading
@Test func refreshDerivesTheRowsFromGit() async {
let (store, _, _) = await makeStore()
#expect(store.hasLoaded)
#expect(store.state.isRepository)
#expect(store.state.stagedCount == 2)
#expect(store.state.unstagedCount == 4)
#expect(store.stagedPathCount == 2)
#expect(store.changedPathCount == 6)
#expect(store.isDirty)
}
@Test func aProjectWithoutGitReadsAsNotARepository() async {
let git = FakeGit(nil)
let store = SourceControlStore(git: git, derive: TestDerivation.derive)
let store = SourceControlStore(git: FakeGit(nil), derive: TestDerivation.derive)
await store.refresh()
#expect(store.hasLoaded)
#expect(!store.state.isRepository)
#expect(!store.isDirty)
}
@Test func anOlderSlowerRefreshCannotOverwriteANewerOne() async {
@@ -62,29 +67,21 @@ import Testing
}
await store.refresh()
#expect(onMain.current == [false])
#expect(store.state.changes.count == 6)
}
@Test(.timeLimit(.minutes(1)))
func aSlowDerivationOvertakenByANewerRefreshIsDropped() async {
let git = FakeGit()
git.queue(snapshot([("old.txt", .modified, false)]), after: .zero)
git.queue(snapshot([("new.txt", .modified, false)]), after: .zero)
let release = DispatchSemaphore(value: 0)
let started = Locked(0)
let store = SourceControlStore(git: git) { snapshot in
if snapshot?.changes.first?.path == "old.txt" {
started.mutate { $0 += 1 }
release.wait()
}
return TestDerivation.derive(snapshot)
}
let slow = Task { await store.refresh() }
#expect(await eventually { started.current == 1 })
@Test func aFailedStatusReadStillLoadsAndLogsItsErrorOnce() async {
struct StatusFailed: Error, CustomStringConvertible { var description: String { "index.lock exists" } }
let git = FakeGit(sample)
git.setLoadError(StatusFailed())
let store = SourceControlStore(git: git, derive: TestDerivation.derive)
await store.refresh()
release.signal()
await slow.value
#expect(store.state.changes.map(\.path) == ["new.txt"])
await store.refresh()
#expect(store.hasLoaded)
#expect(texts(store) == ["status failed: index.lock exists"])
#expect(kinds(store) == [.error])
git.setLoadError(nil)
await store.refresh()
#expect(store.isDirty)
}
@Test func loadIfNeededReadsGitOnlyOnce() async {
@@ -93,24 +90,6 @@ import Testing
#expect(git.loads == 1)
}
// MARK: Grouping and order
@Test func rowsWalkStagedFoldersFirstThenUnstagedFoldersInOrderOfFirstAppearance() async {
let (store, _, _) = await makeStore()
#expect(store.stagedGroups.map(\.dir) == ["src", "config"])
#expect(store.unstagedGroups.map(\.dir) == ["src", ""])
#expect(store.unstagedGroups[0].rows.map(\.path) == ["src/b.php", "src/a.php", "src/c.php"])
#expect(store.rows.map(\.id) == [
"s:src/a.php", "s:config/app.json",
"w:src/b.php", "w:src/a.php", "w:src/c.php", "w:README.md",
])
}
@Test func aFileStagedAndEditedAgainHasTwoRows() async {
let (store, _, _) = await makeStore()
#expect(store.rows.filter { $0.path == "src/a.php" }.map(\.staged) == [true, false])
}
@Test func theExplorerLetterComesFromTheUnstagedRow() async {
let (store, _, _) = await makeStore()
#expect(store.fileStatuses["src/a.php"] == .modified)
@@ -118,91 +97,232 @@ import Testing
#expect(store.fileStatuses["src/c.php"] == .deleted)
}
// MARK: Keyboard cursor
// MARK: Sections and rows
@Test func theCursorStartsAtTheTopClampsAtTheEndsAndFollowsRowIDs() async {
@Test func rowsFallIntoTheFourSectionsStagedFirst() async {
let (store, _, _) = await makeStore()
store.moveSelection(by: 1)
#expect(store.selectedRowID == "s:src/a.php")
store.moveSelection(by: -1)
#expect(store.selectedRowID == "s:src/a.php")
store.moveSelection(by: 100)
#expect(store.selectedRowID == "w:README.md")
#expect(store.selectedRow?.path == "README.md")
#expect(store.sections.map(\.kind) == [.staged, .changed, .untracked, .deleted])
#expect(store.sections[0].rows.map(\.path) == ["src/a.php", "config/app.json"])
#expect(store.sections[1].rows.map(\.path) == ["src/b.php", "README.md", "src/a.php"])
#expect(store.sections[2].rows.map(\.path) == ["new.txt"])
#expect(store.sections[3].rows.map(\.path) == ["src/c.php"])
}
@Test func aCursorWhoseRowVanishedStartsOverAtTheTop() async {
let (store, git, _) = await makeStore()
store.selectedRowID = "w:src/c.php"
git.set(snapshot([("x.txt", .modified, true)]))
@Test func sectionsStartOpenAndRowsStartClosed() async {
let (store, _, _) = await makeStore()
let row = store.sections[1].rows[0]
#expect(!store.isCollapsed(.changed))
store.toggleSection(.changed)
#expect(store.isCollapsed(.changed))
store.toggleSection(.changed)
#expect(!store.isCollapsed(.changed))
#expect(!store.isExpanded(.changed, row))
store.toggleRow(.changed, row)
#expect(store.expandedRows == ["changed:w:src/b.php"])
store.toggleRow(.changed, row)
#expect(store.expandedRows.isEmpty)
}
@Test func anExpandedRowShowsItsOwnHalfOrTooBig() async {
let big = GitFileChange(path: "big.bin", status: .modified, staged: false, original: "", updated: "", isTooBig: true)
let git = FakeGit(GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\n2\n", updated: "1\nX\n"), big,
]))
let store = SourceControlStore(git: git)
await store.refresh()
store.moveSelection(by: 1)
#expect(store.selectedRowID == "s:x.txt")
let rows = store.sections[0].rows
guard case let .rows(lines) = store.detail(for: rows[0]) else {
Issue.record("expected inline rows")
return
}
#expect(!lines.isEmpty)
#expect(store.detail(for: rows[1]) == .tooBig)
}
// MARK: Staging
// MARK: Every action logs the command and streams its output
@Test func stagingAndUnstagingSendTheRowPathAndReload() async {
@Test func stagingLogsTheExactCommandThenItsOutput() async {
let (store, git, _) = await makeStore()
await store.stage("src/b.php")
await store.unstage("config/app.json")
#expect(git.staged == [["src/b.php"]])
#expect(git.unstaged == [["config/app.json"]])
#expect(git.loads == 3)
git.setRun(FakeGitRun(lines: [("warning: LF will be replaced", true)]), forCommand: "add")
await store.stage(["src/b.php"])
#expect(git.executed == [["add", "--", "src/b.php"]])
#expect(texts(store) == ["$ git add -- src/b.php", "warning: LF will be replaced"])
#expect(kinds(store) == [.command, .output])
#expect(git.loads == 2)
}
@Test func stageAllSendsEveryPathWithAnUnstagedRowOnce() async {
@Test func stagingEveryUnstagedPathStillListsThePaths() async {
let (store, git, _) = await makeStore()
await store.stageAll()
#expect(git.staged == [["src/b.php", "README.md", "src/a.php", "src/c.php"]])
let paths = store.state.unstagedPaths
await store.stage(paths)
#expect(git.executed == [["add", "--"] + paths])
#expect(!git.executed.flatMap { $0 }.contains("-A"))
}
@Test func unstageAllSendsEveryStagedPath() async {
@Test func twoQuickActionsRunOneAfterTheOther() async {
let (store, git, _) = await makeStore()
await store.unstageAll()
#expect(git.unstaged == [["src/a.php", "config/app.json"]])
git.setRun(FakeGitRun(delay: .milliseconds(150)), for: ["add", "--", "src/b.php"])
let first = Task { await store.stage(["src/b.php"]) }
let second = Task { await store.stage(["README.md"]) }
await first.value
await second.value
#expect(git.events == ["start add -- src/b.php", "end add -- src/b.php", "start add -- README.md", "end add -- README.md"])
#expect(texts(store) == ["$ git add -- src/b.php", "$ git add -- README.md"])
}
@Test func stageAllWithNothingToStageCallsNoGit() async {
let (store, git, _) = await makeStore(snapshot([("a.txt", .modified, true)]))
await store.stageAll()
#expect(git.staged.isEmpty)
@Test func unstagingARenameTakesItsSourceAlong() async {
let renamed = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
GitFileChange(path: "new.txt", status: .renamed, staged: true, original: "a", updated: "a", originalPath: "old.txt"),
GitFileChange(path: "other.txt", status: .modified, staged: true, original: "a", updated: "b"),
])
let (store, git, _) = await makeStore(renamed)
await store.unstage(["new.txt"])
#expect(git.executed == [["restore", "--staged", "--", "new.txt", "old.txt"]])
}
@Test func discardLeavesAConflictAlone() async {
let (store, git, _) = await makeStore(snapshot([("both.txt", .unmerged, false), ("src/b.php", .modified, false)]))
await store.discard(["both.txt"])
#expect(git.executed.isEmpty)
await store.discard(["both.txt", "src/b.php"])
#expect(git.executed == [["restore", "--", "src/b.php"]])
}
@Test func unstagingLogsRestoreStaged() async {
let (store, git, _) = await makeStore()
await store.unstage(["config/app.json"])
await store.unstage(["src/a.php", "config/app.json"])
#expect(git.executed == [["restore", "--staged", "--", "config/app.json"], ["restore", "--staged", "."]])
}
@Test func withoutCommitsUnstagingFallsBackToRmCached() async {
let (store, git, _) = await makeStore()
git.setRun(FakeGitRun(exitCode: 128, lines: [("fatal: could not resolve HEAD", true)]), forCommand: "restore")
await store.unstage(["config/app.json"])
#expect(git.executed == [["restore", "--staged", "--", "config/app.json"], ["rm", "--cached", "-r", "--", "config/app.json"]])
#expect(texts(store) == [
"$ git restore --staged -- config/app.json", "fatal: could not resolve HEAD", "$ git rm --cached -r -- config/app.json",
])
#expect(kinds(store) == [.command, .error, .command])
}
@Test func outputIsClassifiedPerCommand() async {
let (store, git, _) = await makeStore()
git.setRun(FakeGitRun(lines: [
("Changes to be committed:", false), ("\tmodified: a.php", false),
("Untracked files:", false), ("\tnew.txt", false), ("hint: use git add", false),
]), forCommand: "status")
store.consoleInput = "status"
await store.submitConsoleInput()
#expect(kinds(store) == [.command, .output, .staged, .output, .unstaged, .hint])
}
@Test func linesFromAnotherThreadArriveInOrderBeforeTheActionEnds() async {
let (store, git, _) = await makeStore()
let many = (1...50).map { ("line \($0)", false) }
git.setRun(FakeGitRun(lines: many), forCommand: "log")
store.consoleInput = "log -n 50"
await store.submitConsoleInput()
#expect(texts(store) == ["$ git log -n 50"] + many.map(\.0))
}
// MARK: Discard, delete, restore
@Test func discardingModifiedFilesAsksWithTheRevertCopy() async {
let (store, _, _) = await makeStore()
let one = store.confirmation(for: .gitDiscard(["src/b.php"]))
#expect(one?.title == "Discard changes to src/b.php?")
#expect(one?.body == "This reverts to the last commit and cannot be undone.")
#expect(one?.confirmLabel == "Discard")
#expect(store.confirmation(for: .gitDiscard(["src/b.php", "README.md"]))?.title == "Discard changes to 2 files?")
}
@Test func deletingNewFilesAsksWithTheDeleteCopy() async {
let (store, _, _) = await makeStore()
let request = store.confirmation(for: .gitDiscard(["new.txt"]))
#expect(request?.title == "Delete new.txt?")
#expect(request?.body == "New files are removed from disk. This cannot be undone.")
#expect(request?.confirmLabel == "Delete")
let mixed = store.confirmation(for: .gitDiscard(["new.txt", "src/b.php"]))
#expect(mixed?.title == "Discard changes to 2 files?")
#expect(mixed?.body == "New files are removed from disk. This cannot be undone.")
}
@Test func restoringDeletedFilesNeverAsks() async {
let (store, _, _) = await makeStore()
#expect(store.confirmation(for: .gitDiscard(["src/c.php"])) == nil)
}
@Test func theConfigCanSwitchTheQuestionOff() async {
let (store, _, _) = await makeStore()
store.config.confirmDiscard = false
#expect(store.confirmation(for: .gitDiscard(["src/b.php"])) == nil)
#expect(store.confirmation(for: .copyReference("a")) == nil)
}
@Test func discardRestoresTrackedFilesAndCleansNewOnes() async {
let (store, git, _) = await makeStore()
git.setRun(FakeGitRun(lines: [("Removing new.txt", false)]), forCommand: "clean")
await store.discard(["src/b.php", "new.txt", "src/c.php"])
#expect(git.executed == [["restore", "--", "src/b.php", "src/c.php"], ["clean", "-f", "--", "new.txt"]])
#expect(texts(store) == ["$ git restore -- src/b.php src/c.php", "$ git clean -f -- new.txt", "Removing new.txt"])
}
// MARK: Commit
@Test func commitNeedsAStagedFileAndAMessage() async {
let (store, _, _) = await makeStore()
#expect(!store.canCommit)
store.setCommitMessage(" ")
#expect(!store.canCommit)
@Test func commitAlwaysRunsGitEvenWithNothingStagedOrNoMessage() async {
let (store, git, recorder) = await makeStore(snapshot([("a.txt", .modified, false)]))
git.setRun(FakeGitRun(exitCode: 1, lines: [("no changes added to commit (use \"git add\" and/or \"git commit -a\")", false)]),
forCommand: "commit")
var focused = 0
store.focusMessage = { focused += 1 }
store.setCommitMessage("fix it")
#expect(store.canCommit)
let (clean, git, _) = await makeStore(snapshot([("a.txt", .modified, false)]))
clean.setCommitMessage("fix it")
#expect(!clean.canCommit)
#expect(await clean.commit() == 0)
#expect(git.commits.isEmpty)
await store.commit()
store.setCommitMessage("")
await store.commit()
#expect(git.executed == [["commit", "-m", "fix it"], ["commit", "-m", ""]])
#expect(texts(store).first == "$ git commit -m \"fix it\"")
#expect(texts(store).contains("$ git commit -m \"\""))
#expect(focused == 1)
#expect(recorder.toastTitles == ["Commit failed", "Commit failed"])
}
@Test func commitSendsTheMessageClearsTheDraftAndCountsDistinctFiles() async {
@Test func aSuccessfulCommitClearsTheMessageAndCountsDistinctFiles() async {
let (store, git, recorder) = await makeStore()
store.setCommitMessage("add the payment service ")
let count = await store.commit()
#expect(count == 2)
#expect(git.commits == ["add the payment service"])
#expect(store.canCommitNow)
await store.commit()
#expect(git.executed == [["commit", "-m", "add the payment service"]])
#expect(store.commitMessage.isEmpty)
#expect(recorder.toastTitles == ["Committed 2 files"])
}
@Test func aFailedCommitKeepsTheDraft() async {
let (store, git, recorder) = await makeStore()
git.setFailCommit(true)
@Test func aFailedCommitKeepsTheMessage() async {
let (store, git, _) = await makeStore()
git.setRun(FakeGitRun(exitCode: 1, lines: [("error: hook failed", true)]), forCommand: "commit")
store.setCommitMessage("wip")
#expect(await store.commit() == 0)
await store.commit()
#expect(store.commitMessage == "wip")
#expect(recorder.toastTitles == ["Commit failed"])
}
@Test func theReadyLookNeedsAStagedFileAndAMessage() async {
let (store, _, _) = await makeStore()
#expect(!store.canCommitNow)
store.setCommitMessage(" ")
#expect(!store.canCommitNow)
store.setCommitMessage("fix it")
#expect(store.canCommitNow)
let (clean, _, _) = await makeStore(snapshot([("a.txt", .modified, false)]))
clean.setCommitMessage("fix it")
#expect(!clean.canCommitNow)
}
@Test func theMessageFieldGrowsWithWrappedLinesWithinItsBounds() {
#expect(GitMessageField.height(of: "", width: 800) == GitMetrics.messageMin)
#expect(GitMessageField.height(of: "fix it", width: 800) == GitMetrics.messageMin)
let three = GitMessageField.height(of: String(repeating: "word ", count: 30), width: 300)
#expect(three > GitMetrics.messageMin && three < GitMetrics.messageMax)
#expect(GitMessageField.height(of: String(repeating: "word ", count: 400), width: 300) == GitMetrics.messageMax)
}
@Test func dictatedMessagesBecomeOneLowercaseLine() {
@@ -211,52 +331,180 @@ import Testing
#expect(store.commitMessage == "fix the bug and the test")
}
// MARK: Push
@Test func commitAndPushPushesOnlyAfterASuccessfulCommit() async {
let (store, git, _) = await makeStore()
store.setCommitMessage("ship it")
await store.commit(andPush: true)
#expect(git.executed == [["commit", "-m", "ship it"], ["push"]])
@Test func pushTellsTheOutcomeInAToast() async {
let (failing, failingGit, _) = await makeStore()
failingGit.setRun(FakeGitRun(exitCode: 1, lines: [("error: hook failed", true)]), forCommand: "commit")
failing.setCommitMessage("ship it")
await failing.commit(andPush: true)
#expect(failingGit.executed == [["commit", "-m", "ship it"]])
}
// MARK: Push and pull
@Test func aPushWithoutUpstreamRetriesWithTheBranch() async {
let (store, git, recorder) = await makeStore(snapshot([], branch: "feature"))
git.setRun(FakeGitRun(exitCode: 128, lines: [("fatal: The current branch feature has no upstream branch.", true)]), for: ["push"])
git.setRun(FakeGitRun(lines: [(" * [new branch] feature -> feature", true)]), for: ["push", "-u", "origin", "feature"])
await store.push()
#expect(git.executed == [["push"], ["push", "-u", "origin", "feature"]])
#expect(texts(store).contains("$ git push -u origin feature"))
#expect(kinds(store).last == .success)
#expect(store.busy == nil)
#expect(recorder.toastTitles == ["Pushed to origin/feature"])
}
@Test func aRejectedPushIsAnErrorInTheConsoleAndAToast() async {
let (store, git, recorder) = await makeStore()
git.setPushResult(PushResult(ok: false, message: "rejected"))
let result = await store.push()
#expect(!result.ok)
#expect(!store.isPushing)
#expect(git.pushes == 1)
#expect(recorder.toastTitles == ["Pushing…", "Push failed"])
#expect(recorder.toasts.last?.1 == "rejected")
git.setRun(FakeGitRun(exitCode: 1, lines: [(" ! [rejected] main -> main (fetch first)", true),
("hint: Updates were rejected", true)]), forCommand: "push")
await store.push()
#expect(git.executed == [["push"]])
#expect(kinds(store) == [.command, .error, .hint])
#expect(recorder.toastTitles == ["Push failed"])
}
// MARK: Discard and confirmations
@Test func discardAsksFirstWhileConfirmDiscardIsOn() async {
let (store, _, _) = await makeStore()
let request = store.confirmation(for: .discard("src/b.php"))
#expect(request?.title == "Discard changes to src/b.php?")
#expect(request?.confirmLabel == "Discard")
#expect(request?.action == .discard("src/b.php"))
store.config.confirmDiscard = false
#expect(store.confirmation(for: .discard("src/b.php")) == nil)
}
@Test func stagingAsksOnlyWhenTheConfigSaysSo() async {
let (store, _, _) = await makeStore()
#expect(store.confirmation(for: .stage("a")) == nil)
#expect(store.confirmation(for: .unstage("a")) == nil)
store.config.confirmStage = true
store.config.confirmUnstage = true
#expect(store.confirmation(for: .stage("a"))?.title == "Stage a?")
#expect(store.confirmation(for: .unstage("a"))?.title == "Unstage a?")
#expect(store.confirmation(for: .copyReference("a")) == nil)
}
@Test func performRunsGitActionsAndDeclinesTheRest() async {
@Test func aFailureToastShowsTheErrorLineNotTheTrailingHint() async {
let (store, git, recorder) = await makeStore()
#expect(await store.perform(.discard("src/b.php")))
#expect(git.discarded == [["src/b.php"]])
#expect(recorder.toasts.last?.0 == "Discarded changes")
#expect(await store.perform(.stage("README.md")))
#expect(git.staged == [["README.md"]])
#expect(await !store.perform(.openDiff("README.md")))
#expect(await !store.perform(.copyReference("README.md")))
git.setRun(FakeGitRun(exitCode: 1, lines: [("To origin.git", true),
(" ! [rejected] main -> main (non-fast-forward)", true),
("error: failed to push some refs to 'origin.git'", true),
("hint: See the 'Note about fast-forwards' in 'git push --help' for details.", true)]),
forCommand: "push")
await store.push()
#expect(recorder.toasts.last?.1 == "! [rejected] main -> main (non-fast-forward)")
git.setRun(FakeGitRun(exitCode: 1, lines: [("something went wrong", true), ("hint: try again", true)]), forCommand: "pull")
await store.pull()
#expect(recorder.toasts.last?.0 == "Pull failed")
#expect(recorder.toasts.last?.1 == "something went wrong")
}
@Test func aPullToastsTheCommitsItWasBehind() async {
let behind = GitSnapshot(branch: "main", ahead: 0, canPush: false, behind: 3, upstream: "origin/main", changes: [])
let (store, git, recorder) = await makeStore(behind)
await store.pull()
#expect(git.executed == [["pull", "--no-rebase"]])
#expect(recorder.toastTitles == ["Pulled 3 commits from origin/main"])
}
@Test func aDivergedPullMergesInsteadOfAskingHowToReconcile() async {
let diverged = GitSnapshot(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", changes: [])
let (store, git, recorder) = await makeStore(diverged)
git.setRun(FakeGitRun(lines: [("From origin", true), ("Merge made by the 'ort' strategy.", false)]), forCommand: "pull")
await store.pull()
#expect(texts(store).first == "$ git pull --no-rebase")
#expect(texts(store).contains("Merge made by the 'ort' strategy."))
#expect(recorder.toastTitles == ["Pulled 2 commits from origin/main"])
}
// MARK: Branches
@Test func switchingIsRefusedWhileDirtyWithoutAskingGit() async {
let (store, git, recorder) = await makeStore()
#expect(await !store.switchBranch("develop", remote: false))
#expect(git.executed.isEmpty)
#expect(recorder.toastTitles == ["— Commit or discard 6 files before you switch."])
}
@Test func aCleanTreeSwitchesClearsExpandedRowsAndToasts() async {
let (store, git, recorder) = await makeStore(snapshot([]))
git.setBranches(GitBranchList(local: ["develop", "main"], remote: ["origin/main"]))
#expect(await store.switchBranch("develop", remote: false))
#expect(git.executed == [["switch", "develop"]])
#expect(texts(store).first == "$ git switch develop")
#expect(store.branches.local == ["develop", "main"])
#expect(store.expandedRows.isEmpty)
#expect(recorder.toastTitles == ["Switched to develop"])
}
@Test func aRemoteBranchSwitchesByItsLocalName() async {
let (store, git, _) = await makeStore(snapshot([]))
await store.switchBranch("origin/feature/login", remote: true)
#expect(git.executed == [["switch", "feature/login"]])
}
@Test func theCurrentBranchIsNoSwitch() async {
let (store, git, _) = await makeStore(snapshot([]))
#expect(await !store.switchBranch("main", remote: false))
#expect(await !store.switchBranch("origin/main", remote: true))
#expect(git.executed.isEmpty)
}
// MARK: Console
@Test func clearEmptiesTheLogWithoutGit() async {
let (store, git, _) = await makeStore()
await store.stage(["src/b.php"])
store.consoleInput = "clear"
await store.submitConsoleInput()
#expect(store.lines.isEmpty)
#expect(git.executed == [["add", "--", "src/b.php"]])
}
@Test func aBareLogRunsTheShortLogAndALeadingGitIsOptional() async {
let (store, git, _) = await makeStore()
store.consoleInput = "git log"
await store.submitConsoleInput()
store.consoleInput = "commit -m \"two words\""
await store.submitConsoleInput()
#expect(git.executed == [["log", "--oneline", "--decorate", "-n", "30"], ["commit", "-m", "two words"]])
#expect(texts(store).first == "$ git log --oneline --decorate -n 30")
#expect(store.consoleInput.isEmpty)
}
@Test func upRecallsThePreviousCommands() async {
let (store, _, _) = await makeStore()
store.recallPreviousInput()
#expect(store.consoleInput.isEmpty)
store.consoleInput = "status"
await store.submitConsoleInput()
store.consoleInput = "branch -a"
await store.submitConsoleInput()
store.recallPreviousInput()
#expect(store.consoleInput == "branch -a")
store.recallPreviousInput()
#expect(store.consoleInput == "status")
store.recallPreviousInput()
#expect(store.consoleInput == "status")
}
@Test func theLogKeepsTheLast400Lines() async {
let (store, git, _) = await makeStore()
git.setRun(FakeGitRun(lines: (1...450).map { ("line \($0)", false) }), forCommand: "log")
store.consoleInput = "log"
await store.submitConsoleInput()
#expect(store.lines.count == SourceControlStore.maxConsoleLines)
#expect(store.lines.last?.line.text == "line 450")
#expect(store.lines.first?.line.text == "line 51")
#expect(Set(store.lines.map(\.id)).count == store.lines.count)
}
// MARK: Opening the view
@Test func openingTheViewFetchesOnlyWithAnOrigin() async {
let (store, git, _) = await makeStore(snapshot([]))
git.setAuthor("Jonathan van Rij <jonathan@blijnder.nl>")
await store.viewOpened()
#expect(store.author == "Jonathan van Rij <jonathan@blijnder.nl>")
#expect(git.executed.isEmpty)
git.setBranches(GitBranchList(local: ["main"], remote: ["origin/main"]))
await store.viewOpened()
#expect(git.executed == [["fetch", "origin"]])
#expect(texts(store).first == "$ git fetch origin")
}
@Test func anUpstreamOnOriginIsEnoughToFetch() async {
let tracked = GitSnapshot(branch: "main", ahead: 1, canPush: true, upstream: "origin/main", changes: [])
let (store, git, _) = await makeStore(tracked)
await store.viewOpened()
#expect(git.executed == [["fetch", "origin"]])
#expect(store.syncLabel == "1 ahead of origin")
}
// MARK: Polling
@@ -26,26 +26,26 @@ private struct MemorySession: SessionStoring {
#expect(layout.widths.explorer == 520)
}
@Test func sourceControlDragsStayInsideTheirRange() {
@Test func explorerDragsStayInsideTheirRange() {
let layout = LayoutStore(session: MemorySession())
layout.dragSourceControl(by: -1000)
#expect(layout.widths.sourceControl == 160)
layout.dragSourceControl(by: 5000)
#expect(layout.widths.sourceControl == 460)
layout.dragExplorer(by: -1000)
#expect(layout.widths.explorer == 160)
layout.dragExplorer(by: 5000)
#expect(layout.widths.explorer == 520)
}
@Test func theAgentColumnNeverSqueezesTheEditorBelowItsMinimum() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
layout.dragAgent(by: -5000)
let editor = 1760 - 3 - layout.widths.sourceControl - layout.widths.explorer - layout.widths.agent
let editor = 1760 - 2 - layout.widths.explorer - layout.widths.agent
#expect(editor >= ColumnLayout.minEditorWidth)
}
@Test func roomyWindowsUseTheDesignProportions() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
#expect(layout.widths == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480))
#expect(layout.widths == ColumnWidths(explorer: 289, agent: 480))
}
@Test func focusChangesTheFluidWidthsOnlyBelow1600() {
@@ -75,19 +75,44 @@ private struct MemorySession: SessionStoring {
layout.windowResized(width: 1760)
layout.dragExplorer(by: 0)
layout.windowResized(width: 1100)
let total = layout.widths.sourceControl + layout.widths.explorer + layout.widths.agent
#expect(total <= 1100 - 3 - ColumnLayout.minEditorWidth)
layout.windowResized(width: 900)
let total = layout.widths.explorer + layout.widths.agent
#expect(total <= 900 - 2 - ColumnLayout.minEditorWidth)
}
@Test func hidingGitDropsItsFocus() {
@Test func hidingTheExplorerDropsItsFocus() {
let layout = LayoutStore(session: MemorySession())
layout.focus(.sourceControl)
layout.togglePane(.sourceControl)
layout.focus(.explorer)
layout.togglePane(.explorer)
#expect(layout.activePanel == nil)
layout.focus(.sourceControl)
layout.focus(.explorer)
#expect(layout.activePanel == nil)
}
@Test func theGitViewOpensClosesAndToggles() {
let layout = LayoutStore(session: MemorySession())
#expect(!layout.isGitViewOpen)
layout.openGitView()
#expect(layout.isGitViewOpen)
layout.closeGitView()
#expect(!layout.isGitViewOpen)
layout.toggleGitView()
#expect(layout.isGitViewOpen)
layout.toggleGitView()
#expect(!layout.isGitViewOpen)
}
@Test func theGitViewIsNeitherSavedNorKeptAcrossAProjectSwitch() {
let store = FakeLayouts()
let layout = LayoutStore(session: MemorySession(), persistence: store)
layout.restore(root: "/p")
layout.openGitView()
#expect(store.saved["/p"] == nil)
layout.restore(root: "/q")
#expect(!layout.isGitViewOpen)
#expect(layout.visibility == .all)
}
@Test func aProjectsColumnsSurviveARestart() {
let store = FakeLayouts()
let first = LayoutStore(session: MemorySession(), persistence: store)
@@ -95,13 +120,13 @@ private struct MemorySession: SessionStoring {
first.windowResized(width: 1760)
first.dragExplorer(by: 40)
first.endDrag()
first.togglePane(.sourceControl)
first.togglePane(.terminal)
let second = LayoutStore(session: MemorySession(), persistence: store)
second.windowResized(width: 1760)
second.restore(root: "/p")
#expect(!second.fluid)
#expect(!second.isVisible(.sourceControl))
#expect(!second.isVisible(.terminal))
#expect(second.widths.explorer == first.widths.explorer)
#expect(second.widths.agent == first.widths.agent)
}
@@ -110,11 +135,11 @@ private struct MemorySession: SessionStoring {
let store = FakeLayouts()
let layout = LayoutStore(session: MemorySession(), persistence: store)
layout.restore(root: "/a")
layout.togglePane(.sourceControl)
layout.togglePane(.explorer)
layout.restore(root: "/b")
#expect(layout.isVisible(.sourceControl))
#expect(layout.isVisible(.explorer))
layout.restore(root: "/a")
#expect(!layout.isVisible(.sourceControl))
#expect(!layout.isVisible(.explorer))
}
@Test func dragsSaveOnlyWhenTheyEnd() {
@@ -140,22 +165,22 @@ private struct MemorySession: SessionStoring {
@Test func aWindowXMapsToTheColumnUnderIt() {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
#expect(layout.panel(atX: 10) == .sourceControl)
#expect(layout.panel(atX: 300) == .explorer)
#expect(layout.panel(atX: 10) == .explorer)
#expect(layout.panel(atX: 900) == .editor)
#expect(layout.panel(atX: 1700) == .terminal)
#expect(layout.panel(atX: 236, splitterMargin: 4) == nil)
layout.togglePane(.sourceControl)
#expect(layout.panel(atX: 10) == .explorer)
#expect(layout.panel(atX: 289, splitterMargin: 4) == nil)
layout.togglePane(.explorer)
#expect(layout.panel(atX: 10) == .editor)
}
@Test func neighbourColumnsClampAtTheEdgesAndSkipAHiddenGitColumn() {
@Test func neighbourColumnsClampAtTheEdgesAndSkipAHiddenColumn() {
let layout = LayoutStore(session: MemorySession())
#expect(layout.neighbour(of: nil, step: 1) == .terminal)
#expect(layout.neighbour(of: .terminal, step: 1) == .terminal)
#expect(layout.neighbour(of: .explorer, step: -1) == .sourceControl)
layout.togglePane(.sourceControl)
#expect(layout.neighbour(of: .explorer, step: -1) == .explorer)
#expect(layout.neighbour(of: .editor, step: -1) == .explorer)
layout.togglePane(.explorer)
#expect(layout.neighbour(of: .editor, step: -1) == .editor)
}
@Test func everyPaneStartsShownAndTogglesOnItsOwn() {
@@ -163,8 +188,8 @@ private struct MemorySession: SessionStoring {
#expect(layout.visibility == .all)
layout.togglePane(.explorer)
layout.togglePane(.terminal)
#expect(layout.visibility == ColumnVisibility(sourceControl: true, explorer: false, editor: true, agent: false))
#expect(layout.columns == [.sourceControl, .editor])
#expect(layout.visibility == ColumnVisibility(explorer: false, editor: true, agent: false))
#expect(layout.columns == [.editor])
layout.togglePane(.terminal)
#expect(layout.isVisible(.terminal))
}
@@ -181,7 +206,7 @@ private struct MemorySession: SessionStoring {
#expect(layout.activePanel == .editor)
}
@Test func allFourPaneFlagsSurviveARestart() {
@Test func allThreePaneFlagsSurviveARestart() {
let store = FakeLayouts()
let first = LayoutStore(session: MemorySession(), persistence: store)
first.restore(root: "/p")
@@ -191,20 +216,43 @@ private struct MemorySession: SessionStoring {
let second = LayoutStore(session: MemorySession(), persistence: store)
second.restore(root: "/p")
#expect(second.visibility == ColumnVisibility(sourceControl: true, explorer: false, editor: false, agent: false))
#expect(second.visibility == ColumnVisibility(explorer: false, editor: false, agent: false))
}
@Test func anOlderSnapshotWithOnlyTheGitFlagStillLoads() throws {
let json = #"{"sourceControlWidth":240,"explorerWidth":300,"agentWidth":500,"fluid":false,"gitVisible":false}"#
let snapshot = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: Data(json.utf8))
#expect(snapshot.visibility == ColumnVisibility(sourceControl: false, explorer: true, editor: true, agent: true))
#expect(snapshot.visibility == .all)
#expect(snapshot.explorerWidth == 300)
#expect(snapshot.agentWidth == 500)
#expect(!snapshot.fluid)
}
@Test func aSnapshotFromTheGitColumnDaysKeepsItsPaneFlags() throws {
let json = #"{"sourceControlWidth":240,"explorerWidth":300,"agentWidth":500,"fluid":true,"gitVisible":true,"#
+ #""explorerVisible":false,"fileVisible":true,"claudeVisible":false}"#
let snapshot = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: Data(json.utf8))
#expect(snapshot.visibility == ColumnVisibility(explorer: false, editor: true, agent: false))
#expect(snapshot.fluid)
}
@Test func aSnapshotWithoutTheGitKeysLoads() throws {
let json = #"{"explorerWidth":300,"agentWidth":500,"fluid":false,"explorerVisible":true,"fileVisible":false,"claudeVisible":true}"#
let snapshot = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: Data(json.utf8))
#expect(snapshot.visibility == ColumnVisibility(explorer: true, editor: false, agent: true))
#expect(snapshot.explorerWidth == 300)
}
@Test func aSavedSnapshotNoLongerWritesTheGitKeys() throws {
let data = try JSONEncoder().encode(ColumnLayoutSnapshot(explorerWidth: 288, agentWidth: 480, fluid: true))
let keys = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]).keys
#expect(!keys.contains("sourceControlWidth"))
#expect(!keys.contains("gitVisible"))
}
@Test func aSnapshotRoundTripsItsPaneFlags() throws {
let visibility = ColumnVisibility(sourceControl: true, explorer: false, editor: true, agent: false)
let snapshot = ColumnLayoutSnapshot(sourceControlWidth: 236, explorerWidth: 288, agentWidth: 480, fluid: true, visibility: visibility)
let visibility = ColumnVisibility(explorer: false, editor: true, agent: false)
let snapshot = ColumnLayoutSnapshot(explorerWidth: 288, agentWidth: 480, fluid: true, visibility: visibility)
let decoded = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: JSONEncoder().encode(snapshot))
#expect(decoded == snapshot)
#expect(decoded.visibility == visibility)
@@ -214,9 +262,9 @@ private struct MemorySession: SessionStoring {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
layout.togglePane(.editor)
#expect(layout.columns == [.sourceControl, .explorer, .terminal])
#expect(layout.columns == [.explorer, .terminal])
#expect(layout.span(of: .editor) == nil)
let agentStart = layout.widths.sourceControl + 1 + layout.widths.explorer + 1
let agentStart = layout.widths.explorer + 1
#expect(layout.span(of: .terminal) == agentStart...1760)
#expect(layout.panel(atX: 1000) == .terminal)
}
@@ -225,7 +273,6 @@ private struct MemorySession: SessionStoring {
let layout = LayoutStore(session: MemorySession())
layout.windowResized(width: 1760)
layout.togglePane(.terminal)
layout.togglePane(.sourceControl)
#expect(layout.span(of: .explorer) == 0...layout.widths.explorer)
#expect(layout.span(of: .editor) == (layout.widths.explorer + 1)...1760)
#expect(layout.span(of: .terminal) == nil)
@@ -244,9 +291,8 @@ private struct MemorySession: SessionStoring {
@Test func neighboursSkipEveryHiddenPane() {
let layout = LayoutStore(session: MemorySession())
layout.togglePane(.editor)
layout.togglePane(.explorer)
#expect(layout.neighbour(of: .sourceControl, step: 1) == .terminal)
#expect(layout.neighbour(of: .terminal, step: -1) == .sourceControl)
#expect(layout.neighbour(of: .explorer, step: 1) == .terminal)
#expect(layout.neighbour(of: .terminal, step: -1) == .explorer)
}
@Test func theAgentMayGrowIntoTheRoomAHiddenExplorerLeaves() {
@@ -254,6 +300,6 @@ private struct MemorySession: SessionStoring {
layout.windowResized(width: 1760)
layout.togglePane(.explorer)
layout.dragAgent(by: -5000)
#expect(layout.widths.agent == 1760 - 2 - layout.widths.sourceControl - ColumnLayout.minEditorWidth)
#expect(layout.widths.agent == 1760 - 1 - ColumnLayout.minEditorWidth)
}
}
@@ -56,7 +56,7 @@ import Testing
await harness.model.settle()
let oldEditor = harness.model.editor
let gate = harness.files.holdNextRead("a.php")
harness.model.perform(.context(.discard("a.php")))
harness.model.perform(.context(.gitDiscard(["a.php"])))
harness.model.perform(.confirmPending)
#expect(await eventually { gate.isWaiting })
harness.model.perform(.openRecentProject("/fake/other"))
@@ -61,13 +61,13 @@ import Testing
await harness.start()
var changed = HelderConfig.defaults
changed.ai.command = "other-agent"
changed.git.confirmStage = true
changed.git.confirmDiscard = false
changed.editor.tabSize = 8
harness.config.set(changed)
await harness.model.handle(.config)
#expect(harness.model.config.ai.command == "other-agent")
#expect(harness.model.terminal.config.ai.command == "other-agent")
#expect(harness.model.sourceControl?.config.confirmStage == true)
#expect(harness.model.sourceControl?.config.confirmDiscard == false)
#expect(harness.model.editor?.editorConfig.tabSize == 8)
}
@@ -204,11 +204,11 @@ import Testing
#expect(harness.files.treeLoads == 2)
}
@Test func focusingSourceControlRefreshesGitOnce() async {
@Test func openingTheGitViewRefreshesGitOnce() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.pointerFocused(.sourceControl)
harness.model.pointerFocused(.sourceControl)
harness.model.perform(.toggleGit)
harness.model.perform(.focusCommitMessage)
await harness.model.settle()
#expect(harness.git.loads == 2)
}
@@ -277,36 +277,29 @@ import Testing
}
@Test func discardAsksUnderTheConfigThenReloadsTheFile() async {
let harness = WorkspaceHarness(contents: ["a.php": "edited"])
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false)]), contents: ["a.php": "edited"])
await harness.start()
harness.model.open("a.php")
await harness.model.settle()
await harness.perform(.context(.discard("a.php")))
await harness.perform(.context(.gitDiscard(["a.php"])))
guard case let .confirm(request) = harness.model.overlay.current else {
Issue.record("expected a confirm overlay")
return
}
#expect(request.confirmLabel == "Discard")
#expect(harness.git.executed.isEmpty)
harness.files.set("a.php", "committed")
await harness.perform(.confirmPending)
#expect(harness.git.discarded == [["a.php"]])
#expect(harness.git.executed == [["restore", "--", "a.php"]])
#expect(harness.model.editor?.text(for: "a.php") == "committed")
#expect(harness.toastTitles == ["Discarded changes"])
}
@Test func stagingRunsStraightAwayUnlessTheConfigAsks() async {
let harness = WorkspaceHarness()
@Test func stagingRunsGitStraightAway() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("b.php", .modified, false)]))
await harness.start()
await harness.perform(.context(.stage("a.php")))
#expect(harness.git.staged == [["a.php"]])
var config = HelderConfig.defaults
config.git.confirmStage = true
let asking = WorkspaceHarness(config: config)
await asking.start()
await asking.perform(.context(.stage("a.php")))
#expect(asking.git.staged.isEmpty)
#expect(asking.model.overlay.current != .none)
await harness.perform(.stage(["a.php"]))
#expect(harness.git.executed == [["add", "--", "a.php"]])
#expect(harness.model.overlay.current == .none)
}
@Test func revealInFinderResolvesAgainstTheProject() async {
@@ -354,17 +347,32 @@ import Testing
await harness.start()
harness.model.sourceControl?.setCommitMessage("fix it")
await harness.perform(.commit)
#expect(harness.git.commits == ["fix it"])
#expect(harness.git.executed == [["commit", "-m", "fix it"]])
await harness.perform(.push)
#expect(harness.git.pushes == 1)
#expect(harness.toastTitles == ["Committed 1 file", "Pushing…", "Pushed"])
#expect(harness.git.executed.last == ["push"])
#expect(harness.toastTitles == ["Committed 1 file", "Pushed to origin/main"])
}
@Test func commitWithoutAMessageDoesNothing() async {
@Test func commitWithoutAMessageStillAsksGitThenFocusesTheMessage() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
await harness.start()
harness.git.setRun(FakeGitRun(exitCode: 1, lines: [("Aborting commit due to empty commit message.", true)]), forCommand: "commit")
await harness.perform(.commit)
#expect(harness.git.commits.isEmpty)
#expect(harness.git.executed == [["commit", "-m", ""]])
#expect(harness.model.focusRequest?.target == .commitMessage)
#expect(harness.toastTitles == ["Commit failed"])
}
@Test func theRowMenuOpensTheFileAndClosesTheGitView() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false)]), contents: ["a.php": "<?php"])
await harness.start()
harness.model.perform(.toggleGit)
await harness.model.settle()
harness.model.perform(.showContextMenu(.gitRow(path: "a.php", isDeleted: false), anchor: CGPoint(x: 10, y: 20)))
await harness.perform(.context(.openFile("a.php")))
#expect(!harness.model.layout.isGitViewOpen)
#expect(harness.model.overlay.current == .none)
#expect(harness.model.editor?.activePath == "a.php")
}
@Test func thePassOnPromptInsertsIntoTheAgent() async {
@@ -466,14 +474,49 @@ import Testing
#expect(harness.model.focusRequest?.target == .panel(.editor))
}
@Test func commandCShowsAHiddenGitColumnAndFocusesTheCommitBox() async {
@Test func commandCOpensTheGitViewOnItsMessageField() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.focusCommitMessage)
#expect(harness.model.layout.isGitViewOpen)
#expect(harness.model.focusRequest?.target == .commitMessage)
harness.model.focusTaken(.commitMessage)
harness.model.perform(.focusCommitMessage)
#expect(harness.model.layout.isGitViewOpen)
#expect(harness.model.focusRequest?.target == .commitMessage)
}
@Test func commandGTogglesTheGitViewAndClosingGivesTheKeyboardBack() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.focus(.terminal))
harness.model.perform(.toggleGit)
#expect(harness.model.layout.isGitViewOpen)
#expect(harness.model.focusRequest?.target == .commitMessage)
#expect(harness.model.layout.visibility == .all)
harness.model.perform(.toggleGit)
#expect(!harness.model.layout.isGitViewOpen)
#expect(harness.model.focusRequest?.target == .panel(.terminal))
}
@Test func closingTheGitViewWithNoActiveColumnDropsTheFieldRequest() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.toggleGit)
#expect(!harness.model.layout.isVisible(.sourceControl))
harness.model.perform(.focusCommitMessage)
#expect(harness.model.layout.isVisible(.sourceControl))
#expect(harness.model.focusRequest?.target == .commitMessage)
harness.model.perform(.closeGitView)
#expect(!harness.model.layout.isGitViewOpen)
#expect(harness.model.focusRequest == nil)
harness.model.perform(.closeGitView)
#expect(!harness.model.layout.isGitViewOpen)
}
@Test func paneTogglesLeaveTheGitViewAlone() async {
let harness = WorkspaceHarness()
await harness.start()
harness.model.perform(.toggleGit)
harness.model.perform(.togglePane(.explorer))
#expect(!harness.model.layout.isVisible(.explorer))
#expect(harness.model.layout.isGitViewOpen)
}
@Test func aPaneToggleHidesItsColumnAndAHiddenColumnTakesNoFocus() async {
@@ -491,18 +534,19 @@ import Testing
#expect(harness.model.layout.isVisible(.terminal))
}
@Test func rowCursorKeysDriveTheFocusedList() async {
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("b.php", .added, true)]),
contents: ["a.php": "", "b.php": ""])
@Test func rowCursorKeysDriveOnlyTheExplorer() async {
let harness = WorkspaceHarness(contents: ["README.md": "# hi"])
await harness.start()
harness.model.perform(.focus(.sourceControl))
let before = harness.model.explorer?.selectedPath
harness.model.perform(.focus(.editor))
harness.model.perform(.moveRowCursor(1))
#expect(harness.model.sourceControl?.selectedRow?.path == "b.php")
harness.model.perform(.moveRowCursor(1))
#expect(harness.model.sourceControl?.selectedRow?.path == "a.php")
#expect(harness.model.explorer?.selectedPath == before)
harness.model.perform(.focus(.explorer))
harness.model.perform(.moveRowCursor(10))
harness.model.perform(.moveRowCursor(10))
#expect(harness.model.explorer?.selectedPath == "README.md")
await harness.perform(.openSelectedRow)
#expect(harness.model.editor?.activePath == "a.php")
#expect(harness.model.editor?.sides["a.php"] == .unstaged)
#expect(harness.model.editor?.activePath == "README.md")
}
@Test func commandRightOnARowOpensItsMenuBesideTheColumn() async {
+53 -29
View File
@@ -2,19 +2,38 @@ import Foundation
import HelderCore
import HelderServices
/// A scripted `execute` run: the lines it streams (`isError` for stderr) and its exit code.
struct FakeGitRun {
var exitCode: Int32 = 0
var lines: [(text: String, isError: Bool)] = []
/// How long the run takes after its lines.
var delay: Duration = .zero
static let success = FakeGitRun()
var result: GitCommandResult {
func joined(_ isError: Bool) -> String {
lines.filter { $0.isError == isError }.map { $0.text + "\n" }.joined()
}
return GitCommandResult(exitCode: exitCode, stdout: joined(false), stderr: joined(true))
}
}
/// Records every git call; `load` returns queued snapshots first (each after its delay), then the current one.
///
/// `execute` answers with the run scripted for the full argument list, else for its first argument, else success.
final class FakeGit: GitServicing, @unchecked Sendable {
private struct State {
var loads = 0
var staged: [[String]] = []
var unstaged: [[String]] = []
var commits: [String] = []
var discarded: [[String]] = []
var pushes = 0
var queued: [(GitSnapshot?, Duration)] = []
var current: GitSnapshot?
var failCommit = false
var pushResult = PushResult(ok: true, message: "main -> main")
var executed: [[String]] = []
var events: [String] = []
var loadError: Error?
var runsByArguments: [[String]: FakeGitRun] = [:]
var runsByCommand: [String: FakeGitRun] = [:]
var branches = GitBranchList.empty
var author: String?
}
private let state: Locked<State>
@@ -24,18 +43,25 @@ final class FakeGit: GitServicing, @unchecked Sendable {
}
var loads: Int { state.current.loads }
var staged: [[String]] { state.current.staged }
var unstaged: [[String]] { state.current.unstaged }
var commits: [String] { state.current.commits }
var discarded: [[String]] { state.current.discarded }
var pushes: Int { state.current.pushes }
/// Every `execute` argument list, in call order.
var executed: [[String]] { state.current.executed }
/// `start <args>` and `end <args>` per `execute`, in the order they happened.
var events: [String] { state.current.events }
func set(_ snapshot: GitSnapshot?) { state.mutate { $0.current = snapshot } }
func queue(_ snapshot: GitSnapshot?, after delay: Duration) { state.mutate { $0.queued.append((snapshot, delay)) } }
func setFailCommit(_ value: Bool) { state.mutate { $0.failCommit = value } }
func setPushResult(_ value: PushResult) { state.mutate { $0.pushResult = value } }
func setRun(_ run: FakeGitRun, for arguments: [String]) { state.mutate { $0.runsByArguments[arguments] = run } }
func setRun(_ run: FakeGitRun, forCommand command: String) { state.mutate { $0.runsByCommand[command] = run } }
func setBranches(_ value: GitBranchList) { state.mutate { $0.branches = value } }
func setAuthor(_ value: String?) { state.mutate { $0.author = value } }
/// Makes every `load` throw this error, or read normally again with nil.
func setLoadError(_ error: Error?) { state.mutate { $0.loadError = error } }
func load() async throws -> GitSnapshot? {
if let error = state.current.loadError {
state.mutate { $0.loads += 1 }
throw error
}
let (snapshot, delay): (GitSnapshot?, Duration) = state.mutate { state in
state.loads += 1
return state.queued.isEmpty ? (state.current, .zero) : state.queued.removeFirst()
@@ -44,24 +70,22 @@ final class FakeGit: GitServicing, @unchecked Sendable {
return snapshot
}
func stage(_ paths: [String]) async throws { state.mutate { $0.staged.append(paths) } }
func unstage(_ paths: [String]) async throws { state.mutate { $0.unstaged.append(paths) } }
func commit(message: String) async throws {
try state.mutate { state in
if state.failCommit { throw FakeError() }
state.commits.append(message)
func execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?,
onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult {
let name = arguments.joined(separator: " ")
let run = state.mutate { state in
state.executed.append(arguments)
state.events.append("start \(name)")
return state.runsByArguments[arguments] ?? arguments.first.flatMap { state.runsByCommand[$0] } ?? .success
}
for line in run.lines { onLine(line.text, line.isError) }
if run.delay > .zero { try? await Task.sleep(for: run.delay) }
state.mutate { $0.events.append("end \(name)") }
return run.result
}
func push() async -> PushResult {
state.mutate { state in
state.pushes += 1
return state.pushResult
}
}
func discard(_ paths: [String]) async throws { state.mutate { $0.discarded.append(paths) } }
func branches() async -> GitBranchList { state.current.branches }
func author() async -> String? { state.current.author }
}
/// A snapshot with one change per row: (path, status, staged).
@@ -9,10 +9,10 @@ enum TestDerivation {
guard let snapshot else { return GitWorkingState() }
let changes = snapshot.changes.map {
Change(path: $0.path, status: $0.status, added: $0.updated.isEmpty ? 0 : 1,
removed: $0.original.isEmpty ? 0 : 1, staged: $0.staged)
removed: $0.original.isEmpty ? 0 : 1, staged: $0.staged, originalPath: $0.originalPath)
}
return GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
changes: changes, stagedPaths: Set(changes.filter(\.staged).map(\.path)),
behind: snapshot.behind, upstream: snapshot.upstream, changes: changes, stagedPaths: Set(changes.filter(\.staged).map(\.path)),
isRepository: true)
}
}