import Foundation import HelderCore import HelderServices import Observation @Observable @MainActor public final class SourceControlStore { public private(set) var state = GitWorkingState.empty /// False until the first read landed, so the column can tell "loading" from "clean". public private(set) var hasLoaded = false /// The commit box draft; always one lowercase line (see `setCommitMessage`). public private(set) var commitMessage = "" /// The keyboard cursor, kept as a row id because the list reorders under it. public var selectedRowID: String? public private(set) var isPushing = false /// The `git` config section: confirmations and the poll interval. public var config = HelderConfig.Git() { didSet { if pollTask != nil && config.refreshInterval != oldValue.refreshInterval { startPolling() } } } /// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`. @ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in } @ObservationIgnored private let git: GitServicing @ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState @ObservationIgnored private var refreshGeneration = 0 @ObservationIgnored private var pollTask: Task? /// `derive` runs off the main actor, since it diffs every changed file. public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) { self.git = git self.derive = derive } // MARK: Rows /// Rows in list order: staged folder groups, then unstaged ones. public var rows: [Change] { SourceControlText.navigationOrder(state.changes) } public var stagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter(\.staged)) } public var unstagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter { !$0.staged }) } public var selectedRow: Change? { state.changes.first { $0.id == selectedRowID } } /// Paths with a staged row, in row order: what "unstage all" sends to git. public var stagedPaths: [String] { var seen = Set() return state.changes.filter { $0.staged && seen.insert($0.path).inserted }.map(\.path) } /// 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 } /// Moves the cursor; a cursor whose row vanished starts over at the top. public func moveSelection(by step: Int) { let list = rows guard !list.isEmpty else { return } guard let index = list.firstIndex(where: { $0.id == selectedRowID }) else { selectedRowID = list[0].id return } selectedRowID = list[min(max(index + step, 0), list.count - 1)].id } // MARK: Commit box public var canCommit: Bool { state.stagedCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty } public func setCommitMessage(_ value: String) { commitMessage = SourceControlText.normalizeCommitMessage(value) } // MARK: Git /// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped. public func refresh() async { refreshGeneration += 1 let generation = refreshGeneration let snapshot: GitSnapshot? do { snapshot = try await git.load() } catch { Log.warn("git", "status failed: \(error)") return } guard generation == refreshGeneration else { return } 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 column that appears before `WorkspaceModel` refreshed. public func loadIfNeeded() async { if !hasLoaded { await refresh() } } public func stage(_ path: String) async { await run("Stage failed", detail: path) { try await self.git.stage([path]) } } public func unstage(_ path: String) async { await run("Unstage failed", detail: path) { try await self.git.unstage([path]) } } /// Stages every path with an unstaged row, including ones that also have a staged row. public func stageAll() async { let paths = state.unstagedPaths guard !paths.isEmpty else { return } await run("Stage failed", detail: nil) { try await self.git.stage(paths) } } public func unstageAll() async { let paths = stagedPaths guard !paths.isEmpty else { return } await run("Unstage failed", detail: nil) { try await self.git.unstage(paths) } } /// Commits the staged files with the draft, clears it, and returns how many files went in (0 when nothing did). public func commit() async -> Int { let message = commitMessage.trimmingCharacters(in: .whitespaces) guard !message.isEmpty, state.stagedCount > 0 else { return 0 } let count = Set(state.changes.filter(\.staged).map(\.path)).count commitMessage = "" do { try await git.commit(message: message) } catch { Log.error("git", "commit failed: \(error)") if commitMessage.isEmpty { commitMessage = message } notify("Commit failed", Self.failureDetail(error)) return 0 } await refresh() let subject = message.count > 34 ? String(message.prefix(34)) + "…" : message notify("Committed \(count) file\(count == 1 ? "" : "s")", subject) return count } public func push() async -> PushResult { guard !isPushing else { return PushResult(ok: false, message: "A push is already running") } isPushing = true notify("Pushing…", nil) let result = await git.push() isPushing = false await refresh() notify(result.ok ? "Pushed" : "Push failed", result.message) return result } public func discard(_ path: String) async { do { try await git.discard([path]) } catch { Log.error("git", "discard failed: \(error)") notify("Discard failed", path) await refresh() return } await refresh() notify("Discarded changes", path) } // MARK: Actions /// The confirm dialog an action needs first under the config, or nil to run it straight away. public func confirmation(for action: ContextAction) -> ConfirmRequest? { switch action { case let .discard(path) where config.confirmDiscard: ConfirmRequest(title: "Discard changes to \(path)?", body: "This reverts the file to the last commit and cannot be undone.", confirmLabel: "Discard", action: action) case let .stage(path) where config.confirmStage: ConfirmRequest(title: "Stage \(path)?", confirmLabel: "Stage", action: action) case let .unstage(path) where config.confirmUnstage: ConfirmRequest(title: "Unstage \(path)?", confirmLabel: "Unstage", action: action) default: nil } } /// Runs a git action that is already confirmed; false for actions this store does not own. @discardableResult public func perform(_ action: ContextAction) async -> Bool { switch action { case let .stage(path): await stage(path) case let .unstage(path): await unstage(path) case let .discard(path): await discard(path) default: return false } return true } // 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 } private func run(_ failure: String, detail: String?, _ operation: () async throws -> Void) async { do { try await operation() } catch { Log.error("git", "\(failure): \(error)") notify(failure, detail ?? Self.failureDetail(error)) } await refresh() } private static func failureDetail(_ error: Error) -> String { if case let GitError.commandFailed(_, _, stderr) = error, !stderr.isEmpty { return stderr } return String(describing: error) } }