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
+48
View File
@@ -0,0 +1,48 @@
import Foundation
/// The branches a checkout can pick from: local ones and the ones on "origin".
public struct GitBranchList: Sendable, Equatable {
/// Sorted local branch names.
public var local: [String]
/// Sorted "origin/x" names; "origin/HEAD" is left out.
public var remote: [String]
public init(local: [String] = [], remote: [String] = []) {
self.local = local
self.remote = remote
}
public static let empty = GitBranchList()
/// True when `remote` ("origin/x") already has a local branch "x".
public func isTracked(_ remote: String) -> Bool {
local.contains(Self.localName(ofRemote: remote))
}
/// The local name a remote branch checks out as: "origin/feature/a" → "feature/a".
public static func localName(ofRemote remote: String) -> String {
guard let slash = remote.firstIndex(of: "/") else { return remote }
return String(remote[remote.index(after: slash)...])
}
}
public enum GitBranchParsing {
public static let arguments = ["for-each-ref", "--format=%(refname)", "refs/heads", "refs/remotes/origin"]
/// Reads one full ref name per line, as `arguments` prints them.
public static func parse(_ raw: String) -> GitBranchList {
var list = GitBranchList()
for line in raw.split(whereSeparator: \.isNewline) {
let ref = line.trimmingCharacters(in: .whitespaces)
if ref.hasPrefix("refs/heads/") {
list.local.append(String(ref.dropFirst("refs/heads/".count)))
} else if ref.hasPrefix("refs/remotes/origin/") {
let name = String(ref.dropFirst("refs/remotes/".count))
if name != "origin/HEAD" { list.remote.append(name) }
}
}
list.local.sort()
list.remote.sort()
return list
}
}
+164
View File
@@ -0,0 +1,164 @@
import Foundation
/// How a line in the git console is painted.
public enum GitLineKind: String, Sendable, Equatable {
case command
case output
case error
case hint
case staged
case unstaged
case success
}
public struct GitConsoleLine: Sendable, Equatable {
public var text: String
public var kind: GitLineKind
public init(text: String, kind: GitLineKind) {
self.text = text
self.kind = kind
}
}
public enum GitConsoleText {
/// The echo of a run, such as `$ git commit -m "fix the bar"`.
public static func commandLine(_ arguments: [String]) -> String {
(["$ git"] + arguments.map(quoted)).joined(separator: " ")
}
private static func quoted(_ argument: String) -> String {
let needsQuotes = argument.isEmpty || argument.contains { $0.isWhitespace || $0 == "\"" || $0 == "'" }
guard needsQuotes else { return argument }
return "\"" + argument.replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
/// Splits what the user typed into git arguments; a leading `git` is dropped and nil means nothing is left.
///
/// Quoting follows the shell: '…' is literal, "…" honours `\"` and `\\`, and an unclosed quote ends at the end.
public static func parseInput(_ input: String) -> [String]? {
var arguments: [String] = []
var current = ""
var hasToken = false
var quote: Character?
var escaping = false
for char in input {
if escaping {
if quote == "\"" && char != "\"" && char != "\\" { current.append("\\") }
current.append(char)
escaping = false
continue
}
switch (quote, char) {
case ("'", "'"), ("\"", "\""):
quote = nil
case ("'", _):
current.append(char)
case (_, "\\"):
escaping = true
hasToken = true
case (nil, "'"), (nil, "\""):
quote = char
hasToken = true
case (nil, _) where char.isWhitespace:
if hasToken { arguments.append(current) }
current = ""
hasToken = false
default:
current.append(char)
hasToken = true
}
}
if escaping { current.append("\\") }
if hasToken { arguments.append(current) }
if arguments.first == "git" { arguments.removeFirst() }
return arguments.isEmpty ? nil : arguments
}
/// The branch's place against its upstream, such as `1 ahead · 2 behind origin`.
public static func syncLabel(ahead: Int, behind: Int, upstream: String?) -> String {
guard let upstream else { return "no upstream" }
let remote = upstream.split(separator: "/", maxSplits: 1).first.map(String.init) ?? upstream
switch (ahead > 0, behind > 0) {
case (true, true): return "\(ahead) ahead · \(behind) behind \(remote)"
case (false, true): return "\(behind) behind \(remote)"
case (true, false): return "\(ahead) ahead of \(remote)"
case (false, false): return "in sync with \(remote)"
}
}
}
/// Paints the output lines of one git command. Keep one per run: `status` sections carry over between lines.
///
/// Git writes progress to stderr, so a stderr line alone is not an error.
public struct GitOutputClassifier: Sendable {
private enum StatusSection {
case staged
case unstaged
case other
}
private let subcommand: String?
private var section = StatusSection.other
public init(arguments: [String]) {
subcommand = Self.subcommand(of: arguments)
}
public mutating func classify(_ line: String, isError: Bool) -> GitLineKind {
let trimmed = line.drop { $0 == " " || $0 == "\t" }
if trimmed.hasPrefix("hint:") { return .hint }
if Self.errorPrefixes.contains(where: { trimmed.hasPrefix($0) }) { return .error }
switch subcommand {
case "push":
if Self.isRefUpdate(trimmed) { return .success }
case "status":
if let next = Self.sections[String(trimmed)] {
section = next
return .output
}
if line.hasPrefix("\t") {
switch section {
case .staged: return .staged
case .unstaged: return .unstaged
case .other: break
}
}
default:
break
}
return .output
}
private static let errorPrefixes = [
"error:", "fatal:", "! [rejected]", "! [remote rejected]", "Aborting", "Please commit your changes",
]
/// `a1b2c3d..e4f5a6b main -> main`, a forced `+ a...b`, or `* [new branch] x -> x`.
private static func isRefUpdate(_ line: Substring) -> Bool {
line.contains(" -> ")
&& line.wholeMatch(of: /(?:\+\s*)?(?:[0-9a-f]+\.\.\.?[0-9a-f]+|\*\s+\[new [a-z ]+\])\s+.+ -> .+/) != nil
}
private static let sections: [String: StatusSection] = [
"Changes to be committed:": .staged,
"Changes not staged for commit:": .unstaged,
"Untracked files:": .unstaged,
"Unmerged paths:": .other,
]
/// The first argument that is not an option; `-c` and `-C` take a value.
private static func subcommand(of arguments: [String]) -> String? {
var skipNext = false
for argument in arguments {
if skipNext {
skipNext = false
} else if argument == "-c" || argument == "-C" {
skipNext = true
} else if !argument.hasPrefix("-") {
return argument
}
}
return nil
}
}
+2 -47
View File
@@ -8,7 +8,8 @@ public enum GitDerivation {
/// so a file staged as modified but deleted on disk reads as deleted.
public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
guard let snapshot else { return .empty }
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush, isRepository: true)
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
behind: snapshot.behind, upstream: snapshot.upstream, isRepository: true)
var wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:]
var tooBig = Set<String>()
for change in snapshot.changes {
@@ -39,55 +40,9 @@ public enum GitDerivation {
}
}
/// Rows of one folder in the Source Control list.
public struct ChangeGroup: Sendable, Equatable {
/// Folder path; "" is the project root.
public var dir: String
public var rows: [Change]
public init(dir: String, rows: [Change]) {
self.dir = dir
self.rows = rows
}
}
public enum SourceControlText {
/// Groups rows by folder in order of first appearance; keyboard navigation walks this same order.
public static func groupByDir(_ list: [Change]) -> [ChangeGroup] {
var groups: [ChangeGroup] = []
var indexByDir: [String: Int] = [:]
for change in list {
let dir = PathUtils.dirname(change.path)
if let index = indexByDir[dir] {
groups[index].rows.append(change)
} else {
indexByDir[dir] = groups.count
groups.append(ChangeGroup(dir: dir, rows: [change]))
}
}
return groups
}
/// The row order of the list: staged groups first, then unstaged, each folder by folder.
public static func navigationOrder(_ changes: [Change]) -> [Change] {
let staged = groupByDir(changes.filter(\.staged)).flatMap(\.rows)
let unstaged = groupByDir(changes.filter { !$0.staged }).flatMap(\.rows)
return staged + unstaged
}
/// Dictation tools capitalise and add line breaks; a commit subject is one lowercase line.
public static func normalizeCommitMessage(_ value: String) -> String {
value.lowercased().replacingOccurrences(of: "[ \\t]*[\\r\\n]+[ \\t]*", with: " ", options: .regularExpression)
}
public static func pushTooltip(canPush: Bool, ahead: Int) -> String {
if !canPush { return "Nothing to push (⌘P)" }
if ahead > 0 { return "Push \(ahead) commit\(ahead > 1 ? "s" : "") to remote (⌘P)" }
return "Push the branch to remote (⌘P)"
}
/// Git rows under `tests/` or `cypress/` render dimmed.
public static func isTestFile(_ path: String) -> Bool {
path.hasPrefix("tests/") || path.hasPrefix("cypress/")
}
}
+15 -13
View File
@@ -41,12 +41,18 @@ public struct GitSnapshot: Sendable, Equatable {
public var ahead: Int
/// True when a push would send something, including a branch without an upstream.
public var canPush: Bool
/// Commits the remote has that the branch does not; 0 when unknown.
public var behind: Int
/// The tracked branch, such as "origin/main"; nil without one.
public var upstream: String?
public var changes: [GitFileChange]
public init(branch: String, ahead: Int, canPush: Bool, changes: [GitFileChange]) {
public init(branch: String, ahead: Int, canPush: Bool, behind: Int = 0, upstream: String? = nil, changes: [GitFileChange]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.behind = behind
self.upstream = upstream
self.changes = changes
}
}
@@ -86,6 +92,10 @@ public struct GitWorkingState: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
/// Commits the remote has that the branch does not; 0 when unknown.
public var behind: Int
/// The tracked branch, such as "origin/main"; nil without one.
public var upstream: String?
public var changes: [Change]
/// Per path: HEAD vs disk. Drives the Actual view.
public var fileDiffs: [String: Diff]
@@ -97,13 +107,16 @@ public struct GitWorkingState: Sendable, Equatable {
public var isRepository: Bool
public init(
branch: String = "—", ahead: Int = 0, canPush: Bool = false, changes: [Change] = [],
branch: String = "—", ahead: Int = 0, canPush: Bool = false, behind: Int = 0, upstream: String? = nil,
changes: [Change] = [],
fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:],
stagedPaths: Set<String> = [], isRepository: Bool = false
) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.behind = behind
self.upstream = upstream
self.changes = changes
self.fileDiffs = fileDiffs
self.rowDiffs = rowDiffs
@@ -127,14 +140,3 @@ public struct GitWorkingState: Sendable, Equatable {
return changes.filter { !$0.staged && seen.insert($0.path).inserted }.map(\.path)
}
}
/// The outcome of a push, shown in a toast.
public struct PushResult: Sendable, Equatable {
public var ok: Bool
public var message: String
public init(ok: Bool, message: String) {
self.ok = ok
self.message = message
}
}
+126
View File
@@ -0,0 +1,126 @@
import Foundation
/// A group in the Git view's change list, in the order the list shows them.
public enum GitSectionKind: String, CaseIterable, Sendable {
case staged
case changed
case untracked
case deleted
}
public struct GitSection: Sendable, Equatable, Identifiable {
public var kind: GitSectionKind
public var rows: [Change]
public init(kind: GitSectionKind, rows: [Change]) {
self.kind = kind
self.rows = rows
}
public var id: String { kind.rawValue }
}
public enum GitSections {
/// Sorts rows into their sections; only non-empty sections come back and rows keep their order.
///
/// Every staged row is staged, whatever its status; an unstaged rename or conflict counts as changed.
public static func build(_ changes: [Change]) -> [GitSection] {
var byKind: [GitSectionKind: [Change]] = [:]
for change in changes {
byKind[kind(of: change), default: []].append(change)
}
return GitSectionKind.allCases.compactMap { kind in
byKind[kind].map { GitSection(kind: kind, rows: $0) }
}
}
/// Distinct paths of the rows, in order.
public static func uniquePaths(_ rows: [Change]) -> [String] {
var seen = Set<String>()
return rows.compactMap { seen.insert($0.path).inserted ? $0.path : nil }
}
private static func kind(of change: Change) -> GitSectionKind {
if change.staged { return .staged }
switch change.status {
case .added: return .untracked
case .deleted: return .deleted
case .modified, .renamed, .unmerged: return .changed
}
}
}
/// One side of an inline diff line.
public struct InlineDiffCell: Sendable, Equatable {
public var number: Int
public var text: String
public var mark: LineMark?
/// Character offsets of the part that differs from the other side; nil when the whole line counts.
public var highlight: Range<Int>?
public init(number: Int, text: String, mark: LineMark? = nil, highlight: Range<Int>? = nil) {
self.number = number
self.text = text
self.mark = mark
self.highlight = highlight
}
}
public enum InlineDiffRow: Sendable, Equatable {
case line(left: InlineDiffCell?, right: InlineDiffCell?)
/// A run of unchanged rows folded away.
case gap(Int)
}
public enum InlineDiff {
/// The rows of `diff.split` with `context` unchanged rows kept around each change; other unchanged runs fold into a gap.
public static func rows(from diff: Diff, context: Int = 3) -> [InlineDiffRow] {
let split = diff.split
let changed = split.map { $0.left?.mark != nil || $0.right?.mark != nil }
guard changed.contains(true) else { return [] }
var keep = [Bool](repeating: false, count: split.count)
for (index, isChanged) in changed.enumerated() where isChanged {
let low = max(0, index - context), high = min(split.count - 1, index + context)
for kept in low...high { keep[kept] = true }
}
var rows: [InlineDiffRow] = []
var folded = 0
for (index, row) in split.enumerated() {
guard keep[index] else {
folded += 1
continue
}
if folded > 0 { rows.append(.gap(folded)) }
folded = 0
rows.append(line(row))
}
if folded > 0 { rows.append(.gap(folded)) }
return rows
}
private static func line(_ row: SplitRow) -> InlineDiffRow {
var left = row.left.map { InlineDiffCell(number: $0.no, text: $0.text, mark: $0.mark) }
var right = row.right.map { InlineDiffCell(number: $0.no, text: $0.text, mark: $0.mark) }
if let old = left, let new = right, old.mark == .removed, new.mark == .added {
let ranges = highlights(old.text, new.text)
left?.highlight = ranges.left
right?.highlight = ranges.right
}
return .line(left: left, right: right)
}
/// The middle between the common prefix and the common suffix, per side; nil when nothing is shared or a middle is empty.
static func highlights(_ old: String, _ new: String) -> (left: Range<Int>?, right: Range<Int>?) {
let a = Array(old), b = Array(new)
var prefix = 0
while prefix < a.count && prefix < b.count && a[prefix] == b[prefix] { prefix += 1 }
var suffix = 0
while suffix < a.count - prefix && suffix < b.count - prefix && a[a.count - 1 - suffix] == b[b.count - 1 - suffix] {
suffix += 1
}
guard prefix > 0 || suffix > 0 else { return (nil, nil) }
let left = prefix..<(a.count - suffix)
let right = prefix..<(b.count - suffix)
return (left.isEmpty ? nil : left, right.isEmpty ? nil : right)
}
}
+21 -15
View File
@@ -25,12 +25,16 @@ public struct ParsedStatus: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var behind: Int
public var upstream: String?
public var entries: [StatusEntry]
public init(branch: String, ahead: Int, canPush: Bool, entries: [StatusEntry]) {
public init(branch: String, ahead: Int, canPush: Bool, behind: Int = 0, upstream: String? = nil, entries: [StatusEntry]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.behind = behind
self.upstream = upstream
self.entries = entries
}
}
@@ -69,6 +73,8 @@ public enum Porcelain {
let header = String(part.dropFirst(3))
result.branch = parseBranch(header: header)
(result.ahead, result.canPush) = parseAhead(header: header)
result.behind = parseBehind(header: header)
result.upstream = parseUpstream(header: header)
continue
}
let chars = Array(part.prefix(2))
@@ -101,6 +107,20 @@ public enum Porcelain {
return (0, !header.contains("..."))
}
/// The `[behind N]` count of a header; 0 without one.
public static func parseBehind(header: String) -> Int {
guard let match = header.firstMatch(of: /\[[^\]]*\bbehind (\d+)/) else { return 0 }
return Int(match.1) ?? 0
}
/// The tracked branch after `...` in a header (`main...origin/main [ahead 1]` → "origin/main"); nil without one.
public static func parseUpstream(header: String) -> String? {
if header.hasPrefix("HEAD ") { return nil }
guard let range = header.range(of: "...") else { return nil }
let name = header[range.upperBound...].split(separator: " ").first.map(String.init) ?? ""
return name.isEmpty ? nil : name
}
/// Maps one porcelain column letter to the letter the row shows.
public static func status(for code: Character) -> GitStatus {
switch code {
@@ -125,20 +145,6 @@ public enum Porcelain {
return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows
}
/// The toast line for a push: git reports on stderr, so the summary is pulled from there.
public static func pushSummary(exitCode: Int32, stdout: String, stderr: String) -> PushResult {
let source = stderr.isEmpty ? stdout : stderr
var lines = source.split(whereSeparator: \.isNewline)
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
if exitCode != 0 { return PushResult(ok: false, message: lines.popLast() ?? "push failed") }
let summary = lines.first { line in
line.contains("->") || line.localizedCaseInsensitiveContains("up-to-date")
|| line.localizedCaseInsensitiveContains("new branch")
}
return PushResult(ok: true, message: summary ?? lines.popLast() ?? "Pushed")
}
/// True when a failed `git push` only needs `-u origin <branch>`.
public static func needsUpstream(stderr: String) -> Bool {
stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil