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