import Foundation import HelderCore import HelderServices @testable import HelderUI import Testing @MainActor @Suite struct SourceControlStoreTests { private let sample = snapshot([ ("src/b.php", .modified, false), ("src/a.php", .added, true), ("README.md", .modified, false), ("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) { let git = FakeGit(snapshot ?? sample) let store = SourceControlStore(git: git, derive: TestDerivation.derive) let recorder = Recorder() store.notify = recorder.notify await store.refresh() 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.stagedPathCount == 2) #expect(store.changedPathCount == 6) #expect(store.isDirty) } @Test func aProjectWithoutGitReadsAsNotARepository() async { 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 { let git = FakeGit() let store = SourceControlStore(git: git, derive: TestDerivation.derive) git.queue(snapshot([("old.txt", .modified, false)]), after: .milliseconds(150)) git.queue(snapshot([("new.txt", .modified, false)]), after: .zero) let slow = Task { await store.refresh() } #expect(await eventually { git.loads == 1 }) await store.refresh() await slow.value #expect(store.state.changes.map(\.path) == ["new.txt"]) } @Test func theDerivationRunsOffTheMainThread() async { let onMain = Locked<[Bool]>([]) let store = SourceControlStore(git: FakeGit(sample)) { snapshot in onMain.mutate { $0.append(Thread.isMainThread) } return TestDerivation.derive(snapshot) } await store.refresh() #expect(onMain.current == [false]) } @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() 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 { let (store, git, _) = await makeStore() await store.loadIfNeeded() #expect(git.loads == 1) } @Test func theExplorerLetterComesFromTheUnstagedRow() async { let (store, _, _) = await makeStore() #expect(store.fileStatuses["src/a.php"] == .modified) #expect(store.fileStatuses["config/app.json"] == .modified) #expect(store.fileStatuses["src/c.php"] == .deleted) } // MARK: Sections and rows @Test func rowsFallIntoTheFourSectionsStagedFirst() async { let (store, _, _) = await makeStore() #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 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() 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: Every action logs the command and streams its output @Test func stagingLogsTheExactCommandThenItsOutput() async { let (store, git, _) = await makeStore() 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 stagingEveryUnstagedPathStillListsThePaths() async { let (store, git, _) = await makeStore() let paths = store.state.unstagedPaths await store.stage(paths) #expect(git.executed == [["add", "--"] + paths]) #expect(!git.executed.flatMap { $0 }.contains("-A")) } @Test func twoQuickActionsRunOneAfterTheOther() async { let (store, git, _) = await makeStore() 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 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 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") 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 aSuccessfulCommitClearsTheMessageAndCountsDistinctFiles() async { let (store, git, recorder) = await makeStore() store.setCommitMessage("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 aFailedCommitKeepsTheMessage() async { let (store, git, _) = await makeStore() git.setRun(FakeGitRun(exitCode: 1, lines: [("error: hook failed", true)]), forCommand: "commit") store.setCommitMessage("wip") await store.commit() #expect(store.commitMessage == "wip") } @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() { let store = SourceControlStore(git: FakeGit(), derive: TestDerivation.derive) store.setCommitMessage("Fix The Bug\n And The Test") #expect(store.commitMessage == "fix the bug and the test") } @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"]]) 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.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"]) } @Test func aFailureToastShowsTheErrorLineNotTheTrailingHint() async { let (store, git, recorder) = await makeStore() 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 ") await store.viewOpened() #expect(store.author == "Jonathan van Rij ") #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 @Test func pollingReReadsGitOnTheIntervalUntilStopped() async throws { let (store, git, _) = await makeStore() store.config.refreshInterval = 20 store.startPolling() #expect(store.isPolling) #expect(await eventually { git.loads >= 3 }) store.stopPolling() #expect(!store.isPolling) let loads = git.loads try await Task.sleep(for: .milliseconds(100)) // One read may already have been in flight when polling stopped. #expect(git.loads <= loads + 1) } @Test func aZeroIntervalDisablesPolling() async { let (store, _, _) = await makeStore() store.config.refreshInterval = 0 store.startPolling() #expect(!store.isPolling) } }