Files
helder/Sources/HelderServices/Git/GitService.swift
T

313 lines
15 KiB
Swift

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 pushTimeout: 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<GitSnapshot?, Error>)?
private var trailing: Task<GitSnapshot?, Error>?
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, pushTimeout: TimeInterval = 120,
maxDiffBytes: Int = FileLimits.maxDiffFileBytes) {
self.root = root
self.runner = runner
self.statusAttempts = statusAttempts
self.statusRetryDelay = statusRetryDelay
self.pushTimeout = pushTimeout
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()
}
/// The text of `path` in HEAD or in the index; "" when that side has no such file or it is binary.
public func contents(of path: String, at revision: GitRevision) async -> String {
await Self.blob(revision.prefix + path, root: root, runner: runner, maxBytes: .max).text
}
/// 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)
}
public func stage(_ paths: [String]) async throws {
guard !paths.isEmpty else { return }
try await git(["add", "--"] + paths)
}
public func unstage(_ paths: [String]) async throws {
guard !paths.isEmpty else { return }
let reset = try await Self.run(["reset", "--"] + paths, root: root, runner: runner)
if !reset.succeeded {
// A repository without commits has no HEAD to reset to.
try await git(["rm", "--cached", "-r", "--"] + paths)
}
}
public func commit(message: String) async throws {
try await git(["commit", "-m", message])
}
/// Pushes; retries once with `-u origin <branch>` when the branch has no upstream.
/// Credential prompts are switched off and the whole push gives up after `pushTimeout`.
public func push() async -> PushResult {
let environment = Self.environment(adding: ["GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"])
let runner = self.runner, root = self.root
let attempt = Task { () async throws -> ProcessResult in
var result = try await runner.run("git", arguments: ["push"], in: root, environment: environment)
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) {
let head = try await runner.run("git", arguments: ["rev-parse", "--abbrev-ref", "HEAD"], in: root, environment: environment)
let branch = head.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
if !branch.isEmpty && branch != "HEAD" {
result = try await runner.run("git", arguments: ["push", "-u", "origin", branch], in: root, environment: environment)
}
}
return result
}
let timeout = Task {
try await Task.sleep(nanoseconds: UInt64(pushTimeout * 1_000_000_000))
attempt.cancel()
}
defer { timeout.cancel() }
do {
let result = try await attempt.value
return Porcelain.pushSummary(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr)
} catch is CancellationError {
return PushResult(ok: false, message: "push timed out")
} catch {
return PushResult(ok: false, message: "\(error)")
}
}
/// A path HEAD has is checked out from HEAD (index and disk); any other path is unstaged
/// and its file deleted. A staged rename also gets its source back. Folders are never deleted.
public func discard(_ paths: [String]) async throws {
let renames = paths.isEmpty ? [:] : try await stagedRenameSources()
for path in paths {
if let source = renames[path] {
_ = try await Self.run(["reset", "-q", "HEAD", "--", source, path], root: root, runner: runner)
try await git(["checkout", "HEAD", "--", source])
}
let known = try await Self.run(["cat-file", "-e", "HEAD:" + path], root: root, runner: runner)
if known.succeeded {
try await git(["checkout", "HEAD", "--", path])
continue
}
_ = try await Self.run(["reset", "-q", "HEAD", "--", path], root: root, runner: runner)
guard let url = fileURL(path) else { continue }
var isDirectory: ObjCBool = false
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), !isDirectory.boolValue {
try FileManager.default.removeItem(at: url)
}
}
}
/// Rename target → source for every rename in the index.
private func stagedRenameSources() async throws -> [String: String] {
let parsed = Porcelain.parseStatus(try await statusWithRetry())
var sources: [String: String] = [:]
for entry in parsed.entries where entry.isStagedRename {
sources[entry.path] = entry.originalPath
}
return sources
}
// 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, 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<T: Sendable, R: Sendable>(_ 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))
}
/// The file for a repository path, or nil for the root itself or a path that escapes it.
private func fileURL(_ path: String) -> URL? {
let base = root.standardizedFileURL.path
let url = root.appendingPathComponent(path).standardizedFileURL
return url.path.hasPrefix(base + "/") ? url : nil
}
@discardableResult
private func git(_ arguments: [String]) async throws -> String {
let result = try await Self.run(arguments, root: root, runner: runner)
guard result.succeeded else {
throw GitError.commandFailed(arguments: arguments, exitCode: result.exitCode,
stderr: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))
}
return result.stdout
}
}
/// Which stored copy of a file `GitService.contents(of:at:)` reads.
public enum GitRevision: Sendable {
case head
case index
var prefix: String {
switch self {
case .head: "HEAD:"
case .index: ":0:"
}
}
}