Files
helder/Sources/HelderUI/State/SourceControlStore.swift
T

604 lines
26 KiB
Swift

import Foundation
import HelderCore
import HelderServices
import Observation
/// The long git run the Git view's Pull or Push button is waiting on.
public enum GitBusy: Sendable, Equatable {
case push
case pull
}
/// One console line with an id that stays put while older lines drop off the top.
public struct GitConsoleEntry: Identifiable, Sendable, Equatable {
public let id: Int
public var line: GitConsoleLine
}
/// What an expanded file row shows under it.
public enum GitRowDetail: Equatable {
case rows([InlineDiffRow])
/// The file is over the diff cap, so no text was read.
case tooBig
}
@Observable
@MainActor
public final class SourceControlStore {
public private(set) var state = GitWorkingState.empty {
didSet {
sections = GitSections.build(state.changes)
inlineCache = [:]
}
}
/// False until the first read landed, so the view can tell "loading" from "clean".
public private(set) var hasLoaded = false
public private(set) var sections: [GitSection] = []
public private(set) var collapsedSections: Set<GitSectionKind> = []
/// Keys from `rowKey(_:_:)`.
public private(set) var expandedRows: Set<String> = []
/// The commit message draft; always one lowercase line (see `setCommitMessage`).
public private(set) var commitMessage = ""
/// `user.name <user.email>`, read when the view opens.
public private(set) var author: String?
public private(set) var branches = GitBranchList.empty
/// The last 30 commits of HEAD, read with the branches.
public private(set) var recentCommits: [GitCommitSummary] = []
public private(set) var busy: GitBusy?
/// True while the Claude CLI writes a commit message for the staged changes.
public private(set) var isGeneratingMessage = false
public private(set) var lines: [GitConsoleEntry] = []
public var consoleInput = ""
public private(set) var history: [String] = []
/// The `git` config section: the discard confirmation and the poll interval.
public var config = HelderConfig.Git() {
didSet {
if pollTask != nil && config.refreshInterval != oldValue.refreshInterval { startPolling() }
}
}
public static let maxConsoleLines = 400
public static let remoteTimeout: TimeInterval = 120
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
/// Asks for the keyboard in the message field, after an empty message was refused.
@ObservationIgnored public var focusMessage: () -> Void = {}
@ObservationIgnored private let git: GitServicing
@ObservationIgnored private let commitMessages: CommitMessageGenerating?
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
@ObservationIgnored private var refreshGeneration = 0
@ObservationIgnored private var pollTask: Task<Void, Never>?
@ObservationIgnored private var nextLineID = 0
@ObservationIgnored private var historyCursor: Int?
@ObservationIgnored private var isFetching = false
@ObservationIgnored private var inlineCache: [String: GitRowDetail] = [:]
/// The last git command queued; the next one waits for it, so two never race for `.git/index.lock`.
@ObservationIgnored private var commandTail: Task<Void, Never>?
/// The status error already in the console, so a poll that keeps failing logs it once.
@ObservationIgnored private var loggedStatusError: String?
/// `derive` runs off the main actor, since it diffs every changed file. Without `commitMessages` the
/// generate button stays off.
public init(git: GitServicing, commitMessages: CommitMessageGenerating? = nil,
derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
self.git = git
self.commitMessages = commitMessages
self.derive = derive
}
// MARK: Derived
/// The status letter the Explorer shows per file; the unstaged row wins, as in the file-level diff.
public var fileStatuses: [String: GitStatus] {
var out: [String: GitStatus] = [:]
for change in state.changes where out[change.path] == nil || !change.staged {
out[change.path] = change.status
}
return out
}
/// Any change, staged or not; it locks branch switching and merging.
public var isDirty: Bool { !state.changes.isEmpty }
/// Distinct changed paths, a file with two rows once.
public var changedPathCount: Int { Set(state.changes.map(\.path)).count }
/// Distinct paths with an unstaged row: what Clean up throws away.
public var cleanUpPathCount: Int { Set(state.changes.filter { !$0.staged }.map(\.path)).count }
/// Off while a push or pull runs, and during a conflict, which only a resolution may touch.
public var canCleanUp: Bool {
busy == nil && cleanUpPathCount > 0 && !state.changes.contains { $0.status == .unmerged }
}
public var stagedPathCount: Int { GitSections.uniquePaths(state.changes.filter(\.staged)).count }
/// Off without changes, while a push or pull runs, and during a conflict: staging a conflicted file marks it resolved.
public var canStageAllAndCommit: Bool {
busy == nil && isDirty && !state.changes.contains { $0.status == .unmerged }
}
/// The ready look of the Commit button; the button itself always runs git.
public var canCommitNow: Bool {
stagedPathCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
}
/// The Gen. Commit Message button's on state.
public var canGenerateMessage: Bool {
commitMessages != nil && stagedPathCount > 0 && !isGeneratingMessage
}
public var syncLabel: String {
GitConsoleText.syncLabel(ahead: state.ahead, behind: state.behind, upstream: state.upstream)
}
// MARK: Sections and rows
public static func rowKey(_ kind: GitSectionKind, _ row: Change) -> String {
"\(kind.rawValue):\(row.id)"
}
public func isCollapsed(_ kind: GitSectionKind) -> Bool { collapsedSections.contains(kind) }
public func toggleSection(_ kind: GitSectionKind) {
if !collapsedSections.insert(kind).inserted { collapsedSections.remove(kind) }
}
public func isExpanded(_ kind: GitSectionKind, _ row: Change) -> Bool {
expandedRows.contains(Self.rowKey(kind, row))
}
public func toggleRow(_ kind: GitSectionKind, _ row: Change) {
let key = Self.rowKey(kind, row)
if !expandedRows.insert(key).inserted { expandedRows.remove(key) }
}
/// The inline side-by-side rows of a row's own half; cached until the next status read.
public func detail(for row: Change) -> GitRowDetail {
if let cached = inlineCache[row.id] { return cached }
let diff = state.rowDiffs[row.id]
let detail: GitRowDetail = diff?.isTooBig == true ? .tooBig : .rows(diff.map { InlineDiff.rows(from: $0) } ?? [])
inlineCache[row.id] = detail
return detail
}
// MARK: Commit message
public func setCommitMessage(_ value: String) {
commitMessage = SourceControlText.normalizeCommitMessage(value)
}
public static let generateFailedTitle = "Couldn't generate a commit message"
/// Replaces the draft with the message the Claude CLI writes for the staged diff, then focuses the field.
/// Ignored while one is being written or nothing is staged.
public func generateCommitMessage() async {
guard let commitMessages, canGenerateMessage else { return }
isGeneratingMessage = true
defer { isGeneratingMessage = false }
guard let staged = await git.stagedDiff(), !staged.isEmpty else {
notify(Self.generateFailedTitle, "no staged diff")
return
}
do {
let message = try await commitMessages.generate(prompt: CommitMessagePrompt.make(staged))
setCommitMessage(message)
focusMessage()
} catch is CancellationError {
return
} catch let error as CommitMessageError {
notify(Self.generateFailedTitle, error.detail)
} catch {
notify(Self.generateFailedTitle, "\(error)")
}
}
// MARK: Reading git
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
/// A failed read still counts as loaded, so the view never waits forever; its error lands in the console once.
public func refresh() async {
refreshGeneration += 1
let generation = refreshGeneration
let snapshot: GitSnapshot?
do {
snapshot = try await git.load()
} catch {
guard generation == refreshGeneration else { return }
let message = "status failed: \(error)"
Log.warn("git", message)
if message != loggedStatusError {
loggedStatusError = message
log(message, .error)
}
hasLoaded = true
return
}
guard generation == refreshGeneration else { return }
loggedStatusError = nil
let derive = self.derive
let derived = await Task.detached(priority: .userInitiated) { derive(snapshot) }.value
guard generation == refreshGeneration else { return }
state = derived
hasLoaded = true
}
/// Loads once for a view that appears before `WorkspaceModel` refreshed.
public func loadIfNeeded() async {
if !hasLoaded { await refresh() }
}
public func reloadBranches() async {
branches = await git.branches()
}
public func reloadRecentCommits() async {
recentCommits = await git.recentCommits()
}
/// The Git view opened: reads the author, the branches and the recent commits, then fetches origin so ahead/behind are honest.
/// Without an origin there is nothing to fetch, so the console stays quiet.
public func viewOpened() async {
author = await git.author()
await reloadBranches()
await reloadRecentCommits()
await loadIfNeeded()
guard !isFetching, state.isRepository, !branches.remote.isEmpty || state.upstream?.hasPrefix("origin/") == true else { return }
isFetching = true
defer { isFetching = false }
await run(["fetch", "origin"], timeout: Self.remoteTimeout)
await afterCommand()
}
// MARK: Staging
/// Always the listed paths, never `add -A`, which would also take files the view has not shown yet.
@discardableResult
public func stage(_ paths: [String]) async -> Bool {
guard !paths.isEmpty else { return true }
let result = await run(["add", "--"] + paths)
await afterCommand()
return result.succeeded
}
/// A staged rename takes its source along, or the old path stays staged as deleted.
/// A repository without commits has no HEAD to restore from, so `rm --cached` takes over there.
public func unstage(_ paths: [String]) async {
guard !paths.isEmpty else { return }
let staged = state.changes.filter(\.staged)
let all = Set(paths) == Set(GitSections.uniquePaths(staged))
let sources = staged.filter { $0.status == .renamed && paths.contains($0.path) }.compactMap(\.originalPath)
let withSources = paths + sources.filter { !paths.contains($0) }
let pathspec = all ? ["."] : ["--"] + withSources
let result = await run(["restore", "--staged"] + pathspec)
if !result.succeeded && result.stderr.contains("HEAD") {
await run(["rm", "--cached", "-r"] + pathspec)
}
await afterCommand()
}
/// Modified and deleted files come back with `restore`, new files go with `clean -f`; conflicts are left alone.
public func discard(_ paths: [String]) async {
let paths = paths.filter { unstagedStatus($0) != .unmerged }
guard !paths.isEmpty else { return }
let fresh = paths.filter { unstagedStatus($0) == .added }
let tracked = paths.filter { unstagedStatus($0) != .added }
if !tracked.isEmpty { await run(["restore", "--"] + tracked) }
if !fresh.isEmpty { await run(["clean", "-f", "--"] + fresh) }
await afterCommand()
}
/// Reverts unstaged edits to the index and removes untracked files and folders; staged content and ignored files stay.
public func cleanUp() async {
guard canCleanUp else { return }
let unstaged = state.changes.filter { !$0.staged }
let count = cleanUpPathCount
var failure: (GitCommandResult, [String])?
if unstaged.contains(where: { $0.status != .added }) {
let arguments = ["restore", "--worktree", "--", "."]
let result = await run(arguments)
if !result.succeeded { failure = (result, arguments) }
}
if unstaged.contains(where: { $0.status == .added }) {
// No -x: ignored files such as .env, vendor/ and node_modules/ must survive.
let arguments = ["clean", "-fd"]
let result = await run(arguments)
if !result.succeeded && failure == nil { failure = (result, arguments) }
}
await afterCommand()
if case let (result, arguments)? = failure {
notify("Clean up failed", Self.failureDetail(of: result, arguments: arguments))
} else {
notify("Cleaned up \(count) file\(count == 1 ? "" : "s")", nil)
}
}
private func unstagedStatus(_ path: String) -> GitStatus? {
state.changes.first { !$0.staged && $0.path == path }?.status
}
/// The confirm dialog a discard, clean up or merge needs, or nil to run it straight away; restoring deleted files never asks.
/// A merge that `mergeBranch` refuses (dirty tree, current branch) asks nothing, so the refusal toast shows at once.
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
switch action {
case let .gitDiscard(paths): discardConfirmation(paths, action: action)
case let .mergeBranch(name): mergeConfirmation(name, action: action)
case .gitCleanUp: cleanUpConfirmation()
default: nil
}
}
/// Always asks, whatever `confirmDiscard` says; nil only when `cleanUp` would refuse anyway.
private func cleanUpConfirmation() -> ConfirmRequest? {
guard canCleanUp else { return nil }
let count = cleanUpPathCount
return ConfirmRequest(
title: "Clean up \(count) file\(count == 1 ? "" : "s")?",
body: "New files are removed from disk and unstaged changes are reverted. Staged changes stay. This cannot be undone.",
confirmLabel: "Clean up",
action: .gitCleanUp
)
}
private func mergeConfirmation(_ name: String, action: ContextAction) -> ConfirmRequest? {
let current = state.branch
guard !isDirty, name != current else { return nil }
return ConfirmRequest(
title: "Merge \(name) into \(current)?",
body: "Git merges the commits of \(name) into \(current). A conflict stops the merge for you to resolve.",
confirmLabel: "Merge",
action: action
)
}
private func discardConfirmation(_ paths: [String], action: ContextAction) -> ConfirmRequest? {
guard config.confirmDiscard, !paths.isEmpty else { return nil }
let statuses = paths.map(unstagedStatus)
let hasNew = statuses.contains(.added)
if statuses.allSatisfy({ $0 == .deleted }) { return nil }
let allNew = statuses.allSatisfy { $0 == .added }
let what = paths.count == 1 ? paths[0] : "\(paths.count) files"
return ConfirmRequest(
title: allNew ? "Delete \(what)?" : "Discard changes to \(what)?",
body: hasNew ? "New files are removed from disk. This cannot be undone." : "This reverts to the last commit and cannot be undone.",
confirmLabel: allNew ? "Delete" : "Discard",
action: action
)
}
// MARK: Commit, push, pull
/// Always runs `git commit`, so git's own refusal (nothing staged, empty message) lands in the console.
public func commit(andPush: Bool = false) async {
let message = commitMessage.trimmingCharacters(in: .whitespaces)
let count = stagedPathCount
let arguments = ["commit", "-m", message]
let result = await run(arguments)
await afterCommand()
guard result.succeeded else {
notify("Commit failed", Self.failureDetail(of: result, arguments: arguments))
if message.isEmpty { focusMessage() }
return
}
if commitMessage.trimmingCharacters(in: .whitespaces) == message { commitMessage = "" }
let subject = message.count > 34 ? String(message.prefix(34)) + "…" : message
notify("Committed \(count) file\(count == 1 ? "" : "s")", subject)
if andPush { await push() }
}
/// Stages every unstaged path, new files included, then commits without a push.
/// An empty message stages nothing, so a refusal never leaves the files half done.
public func stageAllAndCommit() async {
guard canStageAllAndCommit else { return }
guard !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty else {
focusMessage()
return
}
guard await stage(state.unstagedPaths) else { return }
await commit()
}
/// A branch without an upstream is pushed again with `-u origin <branch>`. Ignored while a push or pull runs.
public func push() async {
guard busy == nil else { return }
busy = .push
let branch = state.branch
let ahead = state.ahead
var arguments = ["push"]
var result = await run(arguments, timeout: Self.remoteTimeout)
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) && branch != "HEAD" && branch != "—" {
arguments = ["push", "-u", "origin", branch]
result = await run(arguments, timeout: Self.remoteTimeout)
}
busy = nil
await afterCommand()
guard result.succeeded else {
notify("Push failed", Self.failureDetail(of: result, arguments: arguments))
return
}
let commits = ahead > 0 ? "\(ahead) commit\(ahead == 1 ? "" : "s") " : ""
notify("Pushed \(commits)to origin/\(branch)", nil)
}
/// Merges when the branches diverged; a bare `pull` without `pull.rebase` config refuses to choose.
/// Ignored while a push or pull runs.
public func pull() async {
guard busy == nil else { return }
busy = .pull
let branch = state.branch
let behind = state.behind
let arguments = ["pull", "--no-rebase"]
let result = await run(arguments, timeout: Self.remoteTimeout)
busy = nil
await afterCommand()
guard result.succeeded else {
notify("Pull failed", Self.failureDetail(of: result, arguments: arguments))
return
}
if behind > 0 {
notify("Pulled \(behind) commit\(behind == 1 ? "" : "s") from origin/\(branch)", nil)
} else if !result.stdout.contains("Already up to date") {
notify("Pulled from origin/\(branch)", nil)
}
}
// MARK: Branches
/// Refuses with a toast while the tree is dirty, without asking git. A remote branch switches by its local
/// name, which git creates as a tracking branch when it does not exist yet.
@discardableResult
public func switchBranch(_ name: String, remote: Bool) async -> Bool {
if isDirty {
let count = changedPathCount
notify("— Commit or discard \(count) file\(count == 1 ? "" : "s") before you switch.", nil)
return false
}
let local = remote ? GitBranchList.localName(ofRemote: name) : name
guard local != state.branch else { return false }
let result = await run(["switch", local])
await afterCommand()
guard result.succeeded else { return false }
expandedRows = []
notify("Switched to \(local)", nil)
return true
}
/// Runs `git merge --no-edit` into the current branch; refuses with a toast while the tree is dirty, without asking git.
@discardableResult
public func mergeBranch(_ name: String) async -> Bool {
if isDirty {
let count = changedPathCount
notify("— Commit or discard \(count) file\(count == 1 ? "" : "s") before you merge.", nil)
return false
}
let current = state.branch
guard name != current else { return false }
let arguments = ["merge", "--no-edit", name]
let result = await run(arguments)
await afterCommand()
guard result.succeeded else {
if state.changes.contains(where: { $0.status == .unmerged }) {
notify("Merge conflict — resolve, then commit", nil)
} else {
notify("Merge failed", Self.failureDetail(of: result, arguments: arguments))
}
return false
}
notify("Merged \(name) into \(current)", nil)
return true
}
// MARK: Console
/// Runs what was typed; `clear` empties the log and a bare `log` reads as a short one-line log.
public func submitConsoleInput() async {
let typed = consoleInput.trimmingCharacters(in: .whitespaces)
consoleInput = ""
historyCursor = nil
guard let arguments = GitConsoleText.parseInput(typed) else { return }
history.append(typed)
if arguments == ["clear"] {
clearConsole()
return
}
let run = arguments == ["log"] ? ["log", "--oneline", "--decorate", "-n", "30"] : arguments
await self.run(run, literalPathspecs: false, timeout: Self.remoteTimeout)
await afterCommand()
}
/// ↑ in the input: steps back through what was typed, stopping at the oldest.
public func recallPreviousInput() {
guard !history.isEmpty else { return }
let cursor = max(0, (historyCursor ?? history.count) - 1)
historyCursor = cursor
consoleInput = history[cursor]
}
public func clearConsole() {
lines = []
}
// MARK: Running git
/// Queues the command behind the one before it, then runs it; see `runNow`.
@discardableResult
private func run(_ arguments: [String], literalPathspecs: Bool = true, timeout: TimeInterval? = nil) async -> GitCommandResult {
let previous = commandTail
let command = Task { [weak self] () -> GitCommandResult in
await previous?.value
guard let self else { return GitCommandResult(exitCode: -1, stdout: "", stderr: "cancelled") }
return await self.runNow(arguments, literalPathspecs: literalPathspecs, timeout: timeout)
}
commandTail = Task { _ = await command.value }
return await command.value
}
/// Logs the exact command, streams its output classified line by line, and returns how it ended.
/// Lines arrive off the main actor; one consumer keeps them in order and is drained before this returns.
private func runNow(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?) async -> GitCommandResult {
log(GitConsoleText.commandLine(arguments), .command)
let (stream, continuation) = AsyncStream<(String, Bool)>.makeStream()
let consumer = Task { [weak self] in
var classifier = GitOutputClassifier(arguments: arguments)
for await (line, isError) in stream {
self?.log(line, classifier.classify(line, isError: isError))
}
}
let result = await git.execute(arguments, literalPathspecs: literalPathspecs, timeout: timeout) { line, isError in
continuation.yield((line, isError))
}
continuation.finish()
await consumer.value
return result
}
private func afterCommand() async {
await refresh()
await reloadBranches()
await reloadRecentCommits()
}
private func log(_ text: String, _ kind: GitLineKind) {
lines.append(GitConsoleEntry(id: nextLineID, line: GitConsoleLine(text: text, kind: kind)))
nextLineID += 1
if lines.count > Self.maxConsoleLines { lines.removeFirst(lines.count - Self.maxConsoleLines) }
}
/// The toast detail of a failed run: its first error line, else its last line that is not a hint.
private static func failureDetail(of result: GitCommandResult, arguments: [String]) -> String? {
var classifier = GitOutputClassifier(arguments: arguments)
let lines = [(result.stderr, true), (result.stdout, false)].flatMap { text, isError in
text.split(whereSeparator: \.isNewline).map { (String($0), isError) }
}
let classified = lines.map { ($0.0.trimmingCharacters(in: .whitespaces), classifier.classify($0.0, isError: $0.1)) }
.filter { !$0.0.isEmpty }
return classified.first { $0.1 == .error }?.0 ?? classified.last { $0.1 != .hint }?.0
}
// MARK: Polling
/// Re-reads git every `config.refreshInterval` ms as a backstop for a missed watcher event; 0 disables it.
public func startPolling() {
pollTask?.cancel()
pollTask = nil
let interval = config.refreshInterval
guard interval > 0 else { return }
pollTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(interval))
guard !Task.isCancelled, let self else { return }
await self.refresh()
}
}
}
public func stopPolling() {
pollTask?.cancel()
pollTask = nil
}
public var isPolling: Bool { pollTask != nil }
}