import Foundation import HelderCore public actor GitService: GitServicing { public nonisolated let root: URL private let runner: ProcessRunning private let statusAttempts: Int private let statusRetryDelay: TimeInterval private let maxDiffBytes: Int /// Enough overlapping `git show`s to hide process start-up, well under macOS's open-file limit. private static let maxConcurrentReads = 12 private var inFlight: (id: Int, task: Task)? private var trailing: Task? private var readCount = 0 /// Loads that joined the trailing read instead of starting their own. private(set) var coalescedLoads = 0 /// `statusAttempts` and `statusRetryDelay` ride out an external tool holding `.git/index.lock`. public init(root: URL, runner: ProcessRunning = ProcessRunner(), statusAttempts: Int = 6, statusRetryDelay: TimeInterval = 0.12, maxDiffBytes: Int = FileLimits.maxDiffFileBytes) { self.root = root self.runner = runner self.statusAttempts = statusAttempts self.statusRetryDelay = statusRetryDelay self.maxDiffBytes = maxDiffBytes } /// Reads status plus each changed file's text on both sides of its row. /// /// Overlapping calls share one read in flight plus one trailing read, because a branch switch /// fires several watcher pings. Binary files read as ""; a file over `maxDiffBytes` is flagged `isTooBig`. public func load() async throws -> GitSnapshot? { if let trailing { coalescedLoads += 1 return try await trailing.value } if let running = inFlight?.task { let next = Task { () async throws -> GitSnapshot? in _ = try? await running.value return try await self.startRead() } trailing = next coalescedLoads += 1 return try await next.value } return try await startRead() } /// True inside a work tree; falls back to a `.git` on disk so a branch switch mid-probe does not blank the column. public func isRepository() async -> Bool { if let result = try? await Self.run(["rev-parse", "--is-inside-work-tree"], root: root, runner: runner), result.succeeded, result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "true" { return true } return FileManager.default.fileExists(atPath: root.appendingPathComponent(".git").path) } /// Prompts, editors and pagers are switched off, so a run can never wait on input: a commit without `-m` aborts. public func execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?, onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult { var environment = ProcessInfo.processInfo.environment.merging(Self.consoleEnvironment) { _, new in new } environment["GIT_LITERAL_PATHSPECS"] = literalPathspecs ? "1" : nil let runner = self.runner, root = self.root let outcome = await withTaskGroup(of: ExecuteOutcome?.self) { group -> ExecuteOutcome? in group.addTask { do { return .finished(try await runner.stream("git", arguments: arguments, in: root, environment: environment, onLine: onLine)) } catch is CancellationError { return nil } catch let ProcessRunnerError.executableNotFound(name) { return .failed("\(name) not found") } catch let ProcessRunnerError.launchFailed(reason) { return .failed(reason) } catch { return .failed("\(error)") } } if let timeout { group.addTask { try? await Task.sleep(nanoseconds: UInt64(max(0, timeout) * 1_000_000_000)) return Task.isCancelled ? nil : .failed("timed out after \(Self.seconds(timeout))s") } } let first = await group.next() ?? nil group.cancelAll() return first } switch outcome { case let .finished(result): return GitCommandResult(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr) case let .failed(reason): onLine(reason, true) return GitCommandResult(exitCode: -1, stdout: "", stderr: reason) case nil: return GitCommandResult(exitCode: -1, stdout: "", stderr: "cancelled") } } public func branches() async -> GitBranchList { guard let result = try? await Self.run(GitBranchParsing.arguments, root: root, runner: runner), result.succeeded else { return .empty } return GitBranchParsing.parse(result.stdout) } /// The name alone when no email is set. public func author() async -> String? { guard let name = await configValue("user.name") else { return nil } guard let email = await configValue("user.email") else { return name } return "\(name) <\(email)>" } public func recentCommits() async -> [GitCommitSummary] { guard let result = try? await Self.run(GitCommitLogParsing.arguments, root: root, runner: runner), result.succeeded else { return [] } return GitCommitLogParsing.commits(result.stdout) } /// No external diff driver, so the patch is git's own text whatever the user configured. public func stagedDiff() async -> StagedDiff? { async let stat = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff", "--stat"], root: root, runner: runner) async let patch = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff"], root: root, runner: runner) guard let stat = await stat, stat.succeeded, let patch = await patch, patch.succeeded else { return nil } return StagedDiff(stat: stat.stdout, patch: patch.stdout) } private func configValue(_ key: String) async -> String? { guard let result = try? await Self.run(["config", "--get", key], root: root, runner: runner), result.succeeded else { return nil } let value = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) return value.isEmpty ? nil : value } private enum ExecuteOutcome: Sendable { case finished(ProcessResult) case failed(String) } private static let consoleEnvironment = [ "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never", "GIT_EDITOR": "true", "GIT_PAGER": "cat", "PAGER": "cat", ] /// "5" for whole seconds, "0.5" otherwise. private static func seconds(_ value: TimeInterval) -> String { value == value.rounded() ? String(Int(value)) : String(value) } // MARK: - load private func startRead() async throws -> GitSnapshot? { trailing = nil readCount += 1 let id = readCount let task = Task { try await self.read() } inFlight = (id, task) defer { if inFlight?.id == id { inFlight = nil } } return try await task.value } private func read() async throws -> GitSnapshot? { guard await isRepository() else { return nil } let raw = try await statusWithRetry() let parsed = Porcelain.parseStatus(raw) let root = self.root, runner = self.runner, maxBytes = self.maxDiffBytes let perEntry = try await Self.mapLimited(parsed.entries, limit: Self.maxConcurrentReads) { entry in await Self.changes(for: entry, root: root, runner: runner, maxBytes: maxBytes) } return GitSnapshot(branch: parsed.branch, ahead: parsed.ahead, canPush: parsed.canPush, behind: parsed.behind, upstream: parsed.upstream, changes: perEntry.flatMap { $0 }) } /// An external checkout briefly holds `.git/index.lock`; a status landing then fails, so retry. private func statusWithRetry() async throws -> String { var attempt = 0 while true { attempt += 1 let result = try await Self.run(Porcelain.statusArguments, root: root, runner: runner, adding: ["GIT_OPTIONAL_LOCKS": "0"]) if result.succeeded { return result.stdout } if attempt >= statusAttempts { throw GitError.commandFailed(arguments: Porcelain.statusArguments, exitCode: result.exitCode, stderr: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines)) } try await Task.sleep(nanoseconds: UInt64(statusRetryDelay * 1_000_000_000)) } } /// The rows of one porcelain entry, each with the text on both sides of its half. /// /// The index blob is only read when the file has both rows: with one row the index equals /// HEAD (unstaged only) or the disk (staged only), which saves a `git show` per file. private static func changes(for entry: StatusEntry, root: URL, runner: ProcessRunning, maxBytes: Int) async -> [GitFileChange] { let rows = Porcelain.classify(index: entry.index, working: entry.working) let stagedRow = rows.first { $0.staged } let workRow = rows.first { !$0.staged } let both = stagedRow != nil && workRow != nil let path = entry.path let head = { await blob(GitRevision.head.prefix + path, root: root, runner: runner, maxBytes: maxBytes) } let index = both ? await blob(GitRevision.index.prefix + path, root: root, runner: runner, maxBytes: maxBytes) : .text("") var out: [GitFileChange] = [] if let row = stagedRow { let original: Side = row.status == .added ? .text("") : await head() let updated: Side = row.status == .deleted ? .text("") : both ? index : diskText(path, root: root, maxBytes: maxBytes) out.append(change(path, row, staged: true, original, updated, originalPath: entry.originalPath)) } if let row = workRow { let original: Side = entry.index == "?" ? .text("") : both ? index : await head() let updated: Side = row.status == .deleted ? .text("") : diskText(path, root: root, maxBytes: maxBytes) out.append(change(path, row, staged: false, original, updated, originalPath: stagedRow == nil ? entry.originalPath : nil)) } return out } /// One side of a change: its text, or over the cap (and never read into memory as text). private enum Side { case text(String) case tooBig var text: String { if case let .text(value) = self { return value } return "" } } private static func change(_ path: String, _ row: GitRowSpec, staged: Bool, _ original: Side, _ updated: Side, originalPath: String?) -> GitFileChange { let tooBig = if case .tooBig = original { true } else if case .tooBig = updated { true } else { false } return GitFileChange(path: path, status: row.status, staged: staged, original: tooBig ? "" : original.text, updated: tooBig ? "" : updated.text, originalPath: originalPath, isTooBig: tooBig) } private static func blob(_ spec: String, root: URL, runner: ProcessRunning, maxBytes: Int) async -> Side { guard let result = try? await run(["show", spec], root: root, runner: runner), result.succeeded else { return .text("") } guard result.stdout.utf8.count <= maxBytes else { return .tooBig } return .text(result.stdout.prefix(8000).contains("\0") ? "" : result.stdout) } /// The file's text, or "" when it is binary or missing; an oversized file is never read. private static func diskText(_ path: String, root: URL, maxBytes: Int) -> Side { let url = root.appendingPathComponent(path) guard let size = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? NSNumber)?.intValue else { return .text("") } guard size <= maxBytes else { return .tooBig } guard let data = try? Data(contentsOf: url), !FileLimits.looksBinary(data) else { return .text("") } return .text(String(decoding: data, as: UTF8.self)) } /// Maps with at most `limit` operations running at once, keeping the input order. private static func mapLimited(_ items: [T], limit: Int, _ transform: @escaping @Sendable (T) async -> R) async throws -> [R] { var results = [R?](repeating: nil, count: items.count) try await withThrowingTaskGroup(of: (Int, R).self) { group in var next = 0 func launch() { let index = next let item = items[index] group.addTask { (index, await transform(item)) } next += 1 } while next < min(limit, items.count) { launch() } while let (index, value) = try await group.next() { results[index] = value if next < items.count { launch() } } } return results.map { $0! } } /// Paths reach git as literal pathspecs: `pages/[id].vue` must never also match `pages/i.vue`. private static func environment(adding extra: [String: String] = [:]) -> [String: String] { var environment = ProcessInfo.processInfo.environment.merging(extra) { _, new in new } environment["GIT_LITERAL_PATHSPECS"] = "1" return environment } private static func run(_ arguments: [String], root: URL, runner: ProcessRunning, adding extra: [String: String] = [:]) async throws -> ProcessResult { try await runner.run("git", arguments: arguments, in: root, environment: environment(adding: extra)) } } /// Which stored copy of a file a blob read takes. enum GitRevision: Sendable { case head case index var prefix: String { switch self { case .head: "HEAD:" case .index: ":0:" } } }