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
@@ -0,0 +1,43 @@
import HelderCore
import Testing
@Suite struct GitBranchesTests {
@Test("refs split into sorted local and origin branches without origin/HEAD")
func parse() {
let raw = """
refs/heads/main
refs/heads/feature/b
refs/heads/feature/a
refs/remotes/origin/HEAD
refs/remotes/origin/main
refs/remotes/origin/feature/c
refs/remotes/upstream/main
"""
let list = GitBranchParsing.parse(raw)
#expect(list.local == ["feature/a", "feature/b", "main"])
#expect(list.remote == ["origin/feature/c", "origin/main"])
}
@Test("empty output is no branches")
func empty() {
#expect(GitBranchParsing.parse("") == .empty)
}
@Test("a remote branch checks out under its name without the remote", arguments: [
("origin/main", "main"),
("origin/feature/a", "feature/a"),
("main", "main"),
])
func localName(remote: String, local: String) {
#expect(GitBranchList.localName(ofRemote: remote) == local)
}
@Test("a remote branch is tracked when its local name exists")
func tracked() {
let list = GitBranchList(local: ["main", "feature/a"], remote: ["origin/main", "origin/feature/a", "origin/other"])
#expect(list.isTracked("origin/main"))
#expect(list.isTracked("origin/feature/a"))
#expect(!list.isTracked("origin/other"))
}
}
@@ -0,0 +1,122 @@
import HelderCore
import Testing
@Suite struct GitConsoleTests {
// MARK: commandLine
@Test("the echo quotes only what needs quotes", arguments: [
(["status"], "$ git status"),
(["commit", "-m", "fix the bar"], "$ git commit -m \"fix the bar\""),
(["commit", "-m", "say \"hi\""], "$ git commit -m \"say \\\"hi\\\"\""),
(["commit", "-m", "it's"], "$ git commit -m \"it's\""),
(["commit", "-m", ""], "$ git commit -m \"\""),
(["add", "--", "pages/[id].vue"], "$ git add -- pages/[id].vue"),
])
func commandLine(arguments: [String], expected: String) {
#expect(GitConsoleText.commandLine(arguments) == expected)
}
// MARK: parseInput
@Test("typed input splits like a shell", arguments: [
("status", ["status"]),
(" git status ", ["status"]),
("git commit -m \"fix the bar\"", ["commit", "-m", "fix the bar"]),
("commit -m 'it is \"fine\"'", ["commit", "-m", "it is \"fine\""]),
("commit -m \"say \\\"hi\\\"\"", ["commit", "-m", "say \"hi\""]),
("commit -m \"a\\nb\"", ["commit", "-m", "a\\nb"]),
("commit -m \"\"", ["commit", "-m", ""]),
("log --format='%h %s'", ["log", "--format=%h %s"]),
("add my\\ file.txt", ["add", "my file.txt"]),
("commit -m \"unclosed", ["commit", "-m", "unclosed"]),
])
func parseInput(input: String, expected: [String]) {
#expect(GitConsoleText.parseInput(input) == expected)
}
@Test("nothing to run is nil", arguments: ["", " ", "git", " git "])
func parseNothing(input: String) {
#expect(GitConsoleText.parseInput(input) == nil)
}
// MARK: syncLabel
@Test("the sync label names the remote", arguments: [
(0, 2, "origin/main", "2 behind origin"),
(1, 2, "origin/main", "1 ahead · 2 behind origin"),
(1, 0, "origin/main", "1 ahead of origin"),
(0, 0, "origin/feature/x", "in sync with origin"),
(0, 0, "upstream/main", "in sync with upstream"),
(3, 0, nil, "no upstream"),
] as [(Int, Int, String?, String)])
func syncLabel(ahead: Int, behind: Int, upstream: String?, expected: String) {
#expect(GitConsoleText.syncLabel(ahead: ahead, behind: behind, upstream: upstream) == expected)
}
// MARK: classifier
@Test("hints and errors are recognised for any command, whatever the stream", arguments: [
("hint: Updates were rejected", GitLineKind.hint),
("error: failed to push some refs", .error),
("fatal: not a git repository", .error),
(" ! [rejected] main -> main (fetch first)", .error),
(" ! [remote rejected] main -> main (pre-receive hook declined)", .error),
("Aborting", .error),
("Please commit your changes or stash them before you switch branches.", .error),
("Already up to date.", .output),
])
func generic(line: String, kind: GitLineKind) {
var classifier = GitOutputClassifier(arguments: ["pull"])
#expect(classifier.classify(line, isError: true) == kind)
var other = GitOutputClassifier(arguments: ["push"])
#expect(other.classify(line, isError: false) == kind)
}
@Test("stderr progress is plain output")
func progressIsOutput() {
var classifier = GitOutputClassifier(arguments: ["push"])
#expect(classifier.classify("Writing objects: 100% (3/3), 280 bytes | 280.00 KiB/s, done.", isError: true) == .output)
#expect(classifier.classify("To github.com:x/y.git", isError: true) == .output)
}
@Test("a push ref update is a success", arguments: [
" a1b2c3d..e4f5a6b main -> main",
" * [new branch] feature/x -> feature/x",
" + a1b2c3d...e4f5a6b main -> main (forced update)",
])
func pushSuccess(line: String) {
var classifier = GitOutputClassifier(arguments: ["push", "-u", "origin", "main"])
#expect(classifier.classify(line, isError: true) == .success)
}
@Test("a ref update outside push is plain output")
func refUpdateOutsidePush() {
var classifier = GitOutputClassifier(arguments: ["fetch"])
#expect(classifier.classify(" a1b2c3d..e4f5a6b main -> origin/main", isError: true) == .output)
}
@Test("status paths take the kind of their section")
func statusSections() {
var classifier = GitOutputClassifier(arguments: ["-c", "color.ui=never", "status"])
let lines: [(String, GitLineKind)] = [
("On branch main", .output),
("Changes to be committed:", .output),
(" (use \"git restore --staged <file>...\" to unstage)", .output),
("\tmodified: a.txt", .staged),
("Changes not staged for commit:", .output),
("\tmodified: b.txt", .unstaged),
("Untracked files:", .output),
("\tnew.txt", .unstaged),
]
for (line, kind) in lines {
#expect(classifier.classify(line, isError: false) == kind, "\(line)")
}
}
@Test("tab lines outside status are plain output")
func tabLinesOutsideStatus() {
var classifier = GitOutputClassifier(arguments: ["commit"])
_ = classifier.classify("Changes to be committed:", isError: false)
#expect(classifier.classify("\tmodified: a.txt", isError: false) == .output)
}
}
@@ -21,6 +21,15 @@ import Testing
#expect(state.fileDiffs["a.txt"]?.isTooBig == false)
}
@Test("behind and upstream pass through from the snapshot")
func behindAndUpstream() {
let state = GitDerivation.derive(GitSnapshot(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", changes: []))
#expect(state.behind == 2)
#expect(state.upstream == "origin/main")
#expect(GitDerivation.derive(nil).upstream == nil)
#expect(GitDerivation.derive(nil).behind == 0)
}
@Test("no snapshot means not a repository")
func notARepository() {
let state = GitDerivation.derive(nil)
@@ -105,48 +114,8 @@ import Testing
}
@Suite struct SourceControlTextTests {
private func change(_ path: String, staged: Bool = false) -> Change {
Change(path: path, status: .modified, added: 1, removed: 0, staged: staged)
}
@Test("one group per folder, even when git returns the folder in separate runs")
func oneGroupPerFolder() {
let groups = SourceControlText.groupByDir([
change("tests/Feature/AlphaTest.php"), change("app/Models/User.php"), change("tests/Feature/BetaTest.php"),
])
#expect(groups.map(\.dir) == ["tests/Feature", "app/Models"])
#expect(groups[0].rows.map(\.path) == ["tests/Feature/AlphaTest.php", "tests/Feature/BetaTest.php"])
}
@Test("every row is kept, so the keyboard cursor walks the full list")
func keepsEveryRow() {
let list = ["a/one.ts", "b/two.ts", "a/three.ts", "four.ts"].map { change($0) }
let flat = SourceControlText.groupByDir(list).flatMap(\.rows)
#expect(flat.count == list.count)
#expect(Set(flat.map(\.id)).count == list.count)
}
@Test("a project-root file sits in the empty-string group")
func rootGroup() {
#expect(SourceControlText.groupByDir([change("README.md")]) == [ChangeGroup(dir: "", rows: [change("README.md")])])
}
@Test("navigation walks staged groups before unstaged ones")
func navigationOrder() {
let order = SourceControlText.navigationOrder([change("b/x"), change("a/y", staged: true), change("b/z")])
#expect(order.map(\.path) == ["a/y", "b/x", "b/z"])
}
@Test("a dictated commit message becomes one lowercase line")
func commitMessage() {
#expect(SourceControlText.normalizeCommitMessage("Fix The Bug\n In Parser \r\n") == "fix the bug in parser ")
}
@Test("the push tooltip counts commits")
func pushTooltip() {
#expect(SourceControlText.pushTooltip(canPush: false, ahead: 0) == "Nothing to push (⌘P)")
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 1) == "Push 1 commit to remote (⌘P)")
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 3) == "Push 3 commits to remote (⌘P)")
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 0) == "Push the branch to remote (⌘P)")
}
}
@@ -0,0 +1,132 @@
import HelderCore
import Testing
@Suite struct GitSectionsTests {
private func row(_ path: String, _ status: GitStatus, staged: Bool) -> Change {
Change(path: path, status: status, added: 1, removed: 0, staged: staged)
}
// MARK: build
@Test("rows land in the fixed section order, keeping their own order")
func build() {
let rows = [
row("gone.txt", .deleted, staged: false),
row("new.txt", .added, staged: false),
row("b.txt", .modified, staged: false),
row("staged-delete.txt", .deleted, staged: true),
row("a.txt", .modified, staged: false),
row("staged-add.txt", .added, staged: true),
]
let sections = GitSections.build(rows)
#expect(sections.map(\.kind) == [.staged, .changed, .untracked, .deleted])
#expect(sections.map(\.id) == ["staged", "changed", "untracked", "deleted"])
#expect(sections[0].rows.map(\.path) == ["staged-delete.txt", "staged-add.txt"])
#expect(sections[1].rows.map(\.path) == ["b.txt", "a.txt"])
#expect(sections[2].rows.map(\.path) == ["new.txt"])
#expect(sections[3].rows.map(\.path) == ["gone.txt"])
}
@Test("unstaged renames and conflicts count as changed", arguments: [GitStatus.modified, .renamed, .unmerged])
func changed(status: GitStatus) {
#expect(GitSections.build([row("x", status, staged: false)]).map(\.kind) == [.changed])
}
@Test("empty sections are left out")
func emptySections() {
#expect(GitSections.build([]).isEmpty)
#expect(GitSections.build([row("gone", .deleted, staged: false)]).map(\.kind) == [.deleted])
}
@Test("unique paths keep the first occurrence")
func uniquePaths() {
let rows = [row("a", .modified, staged: true), row("b", .added, staged: false), row("a", .modified, staged: false)]
#expect(GitSections.uniquePaths(rows) == ["a", "b"])
}
// MARK: inline diff
private func lines(_ count: Int, changing changed: Int? = nil) -> (String, String) {
let original = (1...count).map { "line \($0)\n" }.joined()
let updated = (1...count).map { $0 == changed ? "line \($0) edited\n" : "line \($0)\n" }.joined()
return (original, updated)
}
@Test("a diff without changes has no rows")
func noChanges() {
let diff = LineDiff.build(original: "a\nb\n", updated: "a\nb\n")
#expect(InlineDiff.rows(from: diff).isEmpty)
}
@Test("unchanged runs beyond the context fold into gaps, leading and trailing included")
func gaps() {
let (original, updated) = lines(20, changing: 10)
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated))
#expect(rows.count == 9)
#expect(rows.first == .gap(6))
#expect(rows.last == .gap(7))
guard case let .line(left, right) = rows[1] else { Issue.record("expected a line"); return }
#expect(left?.number == 7)
#expect(right?.number == 7)
#expect(left?.mark == nil)
}
@Test("a change near the edge keeps every row up to it")
func noLeadingGap() {
let (original, updated) = lines(5, changing: 2)
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated), context: 1)
#expect(rows.count == 4)
#expect(rows.last == .gap(2))
}
@Test("two changes whose context touches share one run")
func mergedContext() {
let original = (1...10).map { "\($0)\n" }.joined()
let updated = original.replacingOccurrences(of: "3\n", with: "x\n").replacingOccurrences(of: "8\n", with: "y\n")
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated), context: 2)
#expect(!rows.contains { if case .gap = $0 { true } else { false } })
#expect(rows.count == 10)
}
@Test("a replaced line highlights the differing middle on both sides")
func highlight() {
let diff = LineDiff.build(original: "let a = 1\n", updated: "let a = 22\n")
let rows = InlineDiff.rows(from: diff)
#expect(rows == [.line(
left: InlineDiffCell(number: 1, text: "let a = 1", mark: .removed, highlight: 8..<9),
right: InlineDiffCell(number: 1, text: "let a = 22", mark: .added, highlight: 8..<10)
)])
}
@Test("an insertion highlights only the side that grew")
func highlightOneSide() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "foo()\n", updated: "foo(bar)\n"))
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
#expect(left?.highlight == nil)
#expect(right?.highlight == 4..<7)
}
@Test("lines with nothing in common get no highlight")
func noCommonPart() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "abc\n", updated: "xyz\n"))
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
#expect(left?.mark == .removed)
#expect(right?.mark == .added)
#expect(left?.highlight == nil)
#expect(right?.highlight == nil)
}
@Test("prefix and suffix never overlap on a repeated character")
func noOverlap() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "aa\n", updated: "aaa\n"))
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
#expect(left?.highlight == nil)
#expect(right?.highlight == 2..<3)
}
@Test("an added line alone has no highlight")
func unpaired() {
let rows = InlineDiff.rows(from: LineDiff.build(original: "a\n", updated: "a\nb\n"))
#expect(rows.last == .line(left: nil, right: InlineDiffCell(number: 2, text: "b", mark: .added)))
}
}
+32 -8
View File
@@ -51,6 +51,30 @@ import Testing
#expect(result.canPush == canPush)
}
@Test("the behind count comes from the header", arguments: [
("main...origin/main [ahead 1, behind 2]", 2),
("main...origin/main [behind 5]", 5),
("main...origin/main [ahead 3]", 0),
("main...origin/main", 0),
("feature/x", 0),
("HEAD (no branch)", 0),
])
func behind(header: String, count: Int) {
#expect(Porcelain.parseBehind(header: header) == count)
}
@Test("the upstream comes from the header", arguments: [
("main...origin/main [ahead 1, behind 2]", "origin/main"),
("feature/x...origin/feature/x", "origin/feature/x"),
("main...origin/main [gone]", "origin/main"),
("main", nil),
("No commits yet on main", nil),
("HEAD (no branch)", nil),
] as [(String, String?)])
func upstream(header: String, name: String?) {
#expect(Porcelain.parseUpstream(header: header) == name)
}
@Test("the branch name comes from the header", arguments: [
("main...origin/main [ahead 1]", "main"),
("main", "main"),
@@ -72,6 +96,8 @@ import Testing
#expect(parsed.branch == "main")
#expect(parsed.ahead == 2)
#expect(parsed.canPush)
#expect(parsed.behind == 0)
#expect(parsed.upstream == "origin/main")
#expect(parsed.entries == [
StatusEntry(index: " ", working: "M", path: "src/a.ts"),
StatusEntry(index: "?", working: "?", path: "new file.txt"),
@@ -107,6 +133,12 @@ import Testing
#expect(parsed.entries.count == 1)
}
@Test("a header ahead and behind carries both counts and the upstream")
func aheadAndBehind() {
let parsed = Porcelain.parseStatus("## main...origin/main [ahead 1, behind 2]\0")
#expect(parsed == ParsedStatus(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", entries: []))
}
@Test("empty output is a clean tree")
func empty() {
#expect(Porcelain.parseStatus("") == ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []))
@@ -120,14 +152,6 @@ import Testing
// MARK: push
@Test("a push toast prefers the ref line, a failure its last line")
func pushSummary() {
let ok = Porcelain.pushSummary(exitCode: 0, stdout: "", stderr: "To github.com:x/y.git\n abc..def main -> main\n")
#expect(ok == PushResult(ok: true, message: "abc..def main -> main"))
let failed = Porcelain.pushSummary(exitCode: 1, stdout: "", stderr: "error: failed to push\nhint: pull first\n")
#expect(failed == PushResult(ok: false, message: "hint: pull first"))
}
@Test("a missing upstream is detected from git's hint")
func needsUpstream() {
#expect(Porcelain.needsUpstream(stderr: "fatal: The current branch x has no upstream branch."))