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
@@ -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