restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,93 @@
import Foundation
public enum GitDerivation {
/// Turns a snapshot into rows plus per-row and per-file diffs; nil means "not a repository".
///
/// Per file, HEAD comes from the staged row's original and disk from the unstaged row's
/// updated; with one row both come from it. The unstaged row owns the file-level status,
/// 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 wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:]
var tooBig = Set<String>()
for change in snapshot.changes {
var diff = LineDiff.build(original: change.original, updated: change.updated, status: change.status)
diff.isTooBig = change.isTooBig
if change.isTooBig { tooBig.insert(change.path) }
let row = Change(path: change.path, status: change.status, added: diff.added, removed: diff.removed,
staged: change.staged, originalPath: change.originalPath)
state.rowDiffs[row.id] = diff
state.changes.append(row)
if change.staged { state.stagedPaths.insert(change.path) }
if let previous = wholeFile[change.path] {
wholeFile[change.path] = change.staged
? (change.original, previous.disk, previous.status, previous.rows + 1, previous.rowID)
: (previous.head, change.updated, change.status, previous.rows + 1, previous.rowID)
} else {
wholeFile[change.path] = (change.original, change.updated, change.status, 1, row.id)
}
}
for (path, whole) in wholeFile {
var diff = whole.rows == 1
? state.rowDiffs[whole.rowID]
: LineDiff.build(original: whole.head, updated: whole.disk, status: whole.status)
diff?.isTooBig = tooBig.contains(path)
state.fileDiffs[path] = diff
}
return state
}
}
/// 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/")
}
}
+140
View File
@@ -0,0 +1,140 @@
import Foundation
/// The status letter a git row shows. Copies and untracked files read as `A`, conflicts as `M`.
public enum GitStatus: String, Codable, Sendable, CaseIterable {
case added = "A"
case modified = "M"
case deleted = "D"
case renamed = "R"
case unmerged = "U"
}
/// One file half as `git load` reads it: the text on each side of that half.
public struct GitFileChange: Sendable, Equatable {
public var path: String
public var status: GitStatus
/// True for the HEAD→index half, false for the index→disk half.
public var staged: Bool
public var original: String
public var updated: String
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
/// A side was over the diff cap, so both texts are left empty.
public var isTooBig: Bool
public init(path: String, status: GitStatus, staged: Bool, original: String, updated: String, originalPath: String? = nil,
isTooBig: Bool = false) {
self.path = path
self.status = status
self.staged = staged
self.original = original
self.updated = updated
self.originalPath = originalPath
self.isTooBig = isTooBig
}
}
/// What one `git status` read of the working tree returns.
public struct GitSnapshot: Sendable, Equatable {
public var branch: String
/// Commits the remote does not have yet; 0 when unknown.
public var ahead: Int
/// True when a push would send something, including a branch without an upstream.
public var canPush: Bool
public var changes: [GitFileChange]
public init(branch: String, ahead: Int, canPush: Bool, changes: [GitFileChange]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.changes = changes
}
}
/// A row in the Source Control column. A file staged and then edited again has two rows.
public struct Change: Sendable, Equatable, Identifiable {
/// Row identity; the path alone is not unique (see `staged`).
public var id: String
public var path: String
public var status: GitStatus
public var added: Int
public var removed: Int
public var isDeleted: Bool
public var staged: Bool
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
public init(path: String, status: GitStatus, added: Int, removed: Int, staged: Bool, originalPath: String? = nil) {
self.id = Change.rowID(path: path, staged: staged)
self.path = path
self.status = status
self.added = added
self.removed = removed
self.isDeleted = status == .deleted
self.staged = staged
self.originalPath = originalPath
}
/// `s:path` for the staged half, `w:path` for the working-tree half.
public static func rowID(path: String, staged: Bool) -> String {
(staged ? "s:" : "w:") + path
}
}
/// The git slice of the workspace, derived from one snapshot.
public struct GitWorkingState: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var changes: [Change]
/// Per path: HEAD vs disk. Drives the Actual view.
public var fileDiffs: [String: Diff]
/// Per row id: that row's own pair. Drives the Diff overlay.
public var rowDiffs: [String: Diff]
/// Paths that have a staged row.
public var stagedPaths: Set<String>
/// False when the project is not a git repository.
public var isRepository: Bool
public init(
branch: String = "—", ahead: Int = 0, canPush: Bool = false, changes: [Change] = [],
fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:],
stagedPaths: Set<String> = [], isRepository: Bool = false
) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.changes = changes
self.fileDiffs = fileDiffs
self.rowDiffs = rowDiffs
self.stagedPaths = stagedPaths
self.isRepository = isRepository
}
public static let empty = GitWorkingState()
/// Whole-project line counts for the status bar.
public var totals: (added: Int, removed: Int) {
changes.reduce((0, 0)) { ($0.0 + $1.added, $0.1 + $1.removed) }
}
public var stagedCount: Int { changes.filter(\.staged).count }
public var unstagedCount: Int { changes.count - stagedCount }
/// Distinct paths with an unstaged row, in row order: what "stage all" sends to git.
public var unstagedPaths: [String] {
var seen = Set<String>()
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
}
}
+146
View File
@@ -0,0 +1,146 @@
import Foundation
public struct StatusEntry: Sendable, Equatable {
/// The index column of the porcelain XY code (" " when clean).
public var index: Character
/// The working-tree column of the porcelain XY code.
public var working: Character
/// The destination path for renames and copies.
public var path: String
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
public init(index: Character, working: Character, path: String, originalPath: String? = nil) {
self.index = index
self.working = working
self.path = path
self.originalPath = originalPath
}
/// True when the index column records a rename, whose source is gone from the index.
public var isStagedRename: Bool { index == "R" && originalPath != nil }
}
public struct ParsedStatus: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var entries: [StatusEntry]
public init(branch: String, ahead: Int, canPush: Bool, entries: [StatusEntry]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.entries = entries
}
}
/// One row a porcelain entry turns into.
public struct GitRowSpec: Sendable, Equatable {
public var status: GitStatus
public var staged: Bool
public init(status: GitStatus, staged: Bool) {
self.status = status
self.staged = staged
}
}
public enum Porcelain {
/// The arguments `GitService.load` passes to git; `-z` keeps paths unquoted.
public static let statusArguments = ["status", "--porcelain", "-b", "--untracked-files=all", "-z"]
/// Parses `git status --porcelain -b -z`: NUL-separated, the `## ` header first.
///
/// For a rename or copy (R or C in either column) the next NUL field is the source
/// path, not an entry of its own. A missing header leaves the branch at "HEAD".
public static func parseStatus(_ raw: String) -> ParsedStatus {
let parts = raw.split(separator: "\0", omittingEmptySubsequences: false)
var result = ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: [])
var sourceFollows = false
for part in parts {
if sourceFollows {
sourceFollows = false
result.entries[result.entries.count - 1].originalPath = String(part)
continue
}
if part.isEmpty { continue }
if part.hasPrefix("## ") {
let header = String(part.dropFirst(3))
result.branch = parseBranch(header: header)
(result.ahead, result.canPush) = parseAhead(header: header)
continue
}
let chars = Array(part.prefix(2))
let index = chars.first ?? " "
let working = chars.count > 1 ? chars[1] : " "
let path = String(part.dropFirst(3))
if index == "R" || index == "C" || working == "R" || working == "C" { sourceFollows = true }
result.entries.append(StatusEntry(index: index, working: working, path: path))
}
return result
}
/// The display branch of a header such as `main...origin/main [ahead 1]`,
/// `No commits yet on main` (→ "main") or `HEAD (no branch)` (→ "HEAD").
public static func parseBranch(header: String) -> String {
let noCommits = "No commits yet on "
if header.hasPrefix(noCommits) { return header.dropFirst(noCommits.count).trimmingCharacters(in: .whitespaces) }
if header.hasPrefix("HEAD ") { return "HEAD" }
let head = header.range(of: "...").map { header[..<$0.lowerBound] } ?? Substring(header)
let name = head.split(separator: " ", omittingEmptySubsequences: false).first.map(String.init) ?? ""
let trimmed = name.trimmingCharacters(in: .whitespaces)
return trimmed.isEmpty ? "HEAD" : trimmed
}
/// Push state from a header. `[ahead N]` → (N, true); no `...` upstream → (0, true),
/// because a first push still sends every commit; "No commits yet" or detached → (0, false).
public static func parseAhead(header: String) -> (ahead: Int, canPush: Bool) {
if header.hasPrefix("No commits yet on ") || header.hasPrefix("HEAD ") { return (0, false) }
if let match = header.firstMatch(of: /\[[^\]]*\bahead (\d+)/), let count = Int(match.1) { return (count, true) }
return (0, !header.contains("..."))
}
/// Maps one porcelain column letter to the letter the row shows.
public static func status(for code: Character) -> GitStatus {
switch code {
case "A", "C", "?": .added
case "D": .deleted
case "R": .renamed
default: .modified
}
}
/// A merge conflict. Neither half can be staged on its own, so it stays one row.
public static func isConflict(index: Character, working: Character) -> Bool {
index == "U" || working == "U" || (index == "A" && working == "A") || (index == "D" && working == "D")
}
/// Splits an XY pair into rows: "MM" is a staged row plus an unstaged row, never one folded row.
public static func classify(index: Character, working: Character) -> [GitRowSpec] {
if isConflict(index: index, working: working) { return [GitRowSpec(status: .modified, staged: true)] }
var rows: [GitRowSpec] = []
if index != " " && index != "?" { rows.append(GitRowSpec(status: status(for: index), staged: true)) }
if working != " " { rows.append(GitRowSpec(status: status(for: working), staged: false)) }
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
}
}