adds nice git interface

This commit is contained in:
2026-10-30 13:21:45 +01:00
parent b9c03a7637
commit caec81e762
107 changed files with 6466 additions and 3992 deletions
+68 -98
View File
@@ -6,7 +6,6 @@ public actor GitService: GitServicing {
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.
@@ -19,13 +18,12 @@ public actor GitService: GitServicing {
/// `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,
statusRetryDelay: TimeInterval = 0.12,
maxDiffBytes: Int = FileLimits.maxDiffFileBytes) {
self.root = root
self.runner = runner
self.statusAttempts = statusAttempts
self.statusRetryDelay = statusRetryDelay
self.pushTimeout = pushTimeout
self.maxDiffBytes = maxDiffBytes
}
@@ -50,11 +48,6 @@ public actor GitService: GitServicing {
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),
@@ -64,86 +57,79 @@ public actor GitService: GitServicing {
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"])
/// 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 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)
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)")
}
}
return result
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
}
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)")
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")
}
}
/// 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)
}
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)
}
/// 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
/// 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)>"
}
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
@@ -166,7 +152,8 @@ public actor GitService: GitServicing {
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 })
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.
@@ -279,27 +266,10 @@ public actor GitService: GitServicing {
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 {
/// Which stored copy of a file a blob read takes.
enum GitRevision: Sendable {
case head
case index
+29 -8
View File
@@ -6,15 +6,36 @@ public enum GitError: Error, Equatable {
case commandFailed(arguments: [String], exitCode: Int32, stderr: String)
}
/// What one `execute` run of git ended with.
public struct GitCommandResult: Sendable, Equatable {
public var exitCode: Int32
public var stdout: String
public var stderr: String
public init(exitCode: Int32, stdout: String, stderr: String) {
self.exitCode = exitCode
self.stdout = stdout
self.stderr = stderr
}
public var succeeded: Bool { exitCode == 0 }
}
public protocol GitServicing: Sendable {
/// The working state, or nil when the project is not a git repository.
func load() async throws -> GitSnapshot?
/// Stages modifications, additions and deletions of the paths.
func stage(_ paths: [String]) async throws
func unstage(_ paths: [String]) async throws
func commit(message: String) async throws
/// Never throws: a failed push is a toast, not an error.
func push() async -> PushResult
/// Reverts each path to HEAD; a file HEAD does not have is unstaged and deleted, and a staged rename gets its source back.
func discard(_ paths: [String]) async throws
/// Runs `git <arguments>` in the project and streams every output line; never throws (a launch failure is exit code -1 with the reason on stderr).
func execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?,
onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult
/// Local and origin branches.
func branches() async -> GitBranchList
/// `user.name <user.email>` from git config, nil when unset.
func author() async -> String?
}
extension GitServicing {
/// Runs with literal pathspecs and no timeout.
public func execute(_ arguments: [String], onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult {
await execute(arguments, literalPathspecs: true, timeout: nil, onLine: onLine)
}
}
@@ -1,3 +1,4 @@
import Darwin
import Foundation
public struct ProcessResult: Sendable, Equatable {
@@ -24,9 +25,21 @@ public protocol ProcessRunning: Sendable {
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
/// Like `run`, but hands each output line to `onLine` as it arrives (`isError` for stderr).
func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult
}
extension ProcessRunning {
/// Runs to completion, then emits the stdout lines and after them the stderr lines.
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
let result = try await run(executable, arguments: arguments, in: directory, environment: environment)
for line in OutputLines.split(result.stdout) { onLine(line, false) }
for line in OutputLines.split(result.stderr) { onLine(line, true) }
return result
}
public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult {
try await run(executable, arguments: arguments, in: directory, environment: nil)
}
@@ -40,8 +53,18 @@ public struct ProcessRunner: ProcessRunning {
}
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: nil)
}
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: onLine)
}
private func launch(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment)
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, onLine: onLine)
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
job.start(continuation)
@@ -52,14 +75,55 @@ public struct ProcessRunner: ProcessRunning {
}
}
/// Splits output into lines on "\n" and "\r", so a progress update ends a line too; empty lines are dropped.
enum OutputLines {
static func split(_ text: String) -> [String] {
text.split(omittingEmptySubsequences: true) { $0 == "\n" || $0 == "\r" || $0 == "\r\n" }.map(String.init)
}
}
/// Collects one pipe's bytes and, when streaming, cuts them into lines as they arrive.
private final class LineBuffer {
private(set) var all = Data()
private var pending = Data()
/// Appends a chunk and returns the lines it completed.
func append(_ chunk: Data) -> [String] {
all.append(chunk)
pending.append(chunk)
var lines: [String] = []
while let end = pending.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) {
let line = pending[pending.startIndex..<end]
if !line.isEmpty { lines.append(String(decoding: line, as: UTF8.self)) }
pending.removeSubrange(pending.startIndex...end)
}
return lines
}
/// The last line when the output did not end with a line break.
func finish() -> String? {
defer { pending.removeAll() }
return pending.isEmpty ? nil : String(decoding: pending, as: UTF8.self)
}
}
/// One child process. Both pipes are drained on their own threads, because a child that
/// fills one pipe while we wait on the other would deadlock.
///
/// A cancel resumes at once and signals the child and every descendant: a grandchild such as
/// `ssh` can hold a pipe open long after the child is gone, so waiting for EOF could hang.
private final class Job: @unchecked Sendable {
private let process = Process()
private let lock = NSLock()
private var cancelled = false
private var continuation: CheckedContinuation<ProcessResult, Error>?
private let onLine: (@Sendable (String, Bool) -> Void)?
/// Keeps `onLine` to one call at a time, though both pipes feed it.
private let emitLock = NSLock()
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?) {
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?,
onLine: (@Sendable (String, Bool) -> Void)?) {
self.onLine = onLine
process.executableURL = url
process.arguments = arguments
if let directory { process.currentDirectoryURL = directory }
@@ -80,53 +144,102 @@ private final class Job: @unchecked Sendable {
process.terminationHandler = { _ in group.leave() }
lock.lock()
let alreadyCancelled = cancelled
if cancelled {
lock.unlock()
continuation.resume(throwing: CancellationError())
return
}
do {
if !alreadyCancelled { try process.run() }
try process.run()
} catch {
lock.unlock()
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
return
}
self.continuation = continuation
lock.unlock()
if alreadyCancelled {
continuation.resume(throwing: CancellationError())
return
}
group.enter()
DispatchQueue.global().async {
outData = out.fileHandleForReading.readDataToEndOfFile()
DispatchQueue.global().async { [self] in
outData = drain(out.fileHandleForReading, isError: false)
group.leave()
}
group.enter()
DispatchQueue.global().async {
errData = err.fileHandleForReading.readDataToEndOfFile()
DispatchQueue.global().async { [self] in
errData = drain(err.fileHandleForReading, isError: true)
group.leave()
}
group.notify(queue: .global()) { [self, process] in
if wasCancelled {
continuation.resume(throwing: CancellationError())
return
}
continuation.resume(returning: ProcessResult(
resume(with: .success(ProcessResult(
exitCode: process.terminationStatus,
stdout: String(decoding: outData, as: UTF8.self),
stderr: String(decoding: errData, as: UTF8.self)
))
)))
}
}
private var wasCancelled: Bool {
/// Resumes the caller once; whichever of finish and cancel comes second is dropped.
private func resume(with result: Result<ProcessResult, Error>) {
lock.lock()
defer { lock.unlock() }
return cancelled
let pending = continuation
continuation = nil
lock.unlock()
pending?.resume(with: result)
}
/// Reads a pipe to its end, emitting each line on the way when streaming.
private func drain(_ handle: FileHandle, isError: Bool) -> Data {
guard let onLine else { return handle.readDataToEndOfFile() }
let buffer = LineBuffer()
// `read(upToCount:)` waits for the full count; `availableData` returns each chunk as it lands.
while true {
let chunk = handle.availableData
if chunk.isEmpty { break }
emit(buffer.append(chunk), isError: isError, onLine)
}
if let last = buffer.finish() { emit([last], isError: isError, onLine) }
return buffer.all
}
private func emit(_ lines: [String], isError: Bool, _ onLine: @Sendable (String, Bool) -> Void) {
guard !lines.isEmpty else { return }
emitLock.lock()
defer { emitLock.unlock() }
for line in lines { onLine(line, isError) }
}
func cancel() {
lock.lock()
defer { lock.unlock() }
cancelled = true
if process.isRunning { process.terminate() }
if process.isRunning {
let pid = process.processIdentifier
// Descendants first: once the child is gone its children are reparented and out of reach.
for descendant in ProcessTree.descendants(of: pid).reversed() { kill(descendant, SIGTERM) }
kill(pid, SIGTERM)
}
lock.unlock()
resume(with: .failure(CancellationError()))
}
}
/// The process tree below a pid, read through libproc.
enum ProcessTree {
/// Children before grandchildren.
static func descendants(of pid: pid_t) -> [pid_t] {
var out: [pid_t] = []
var queue = [pid]
while !queue.isEmpty {
let children = Self.children(of: queue.removeFirst())
out += children
queue += children
}
return out
}
private static func children(of pid: pid_t) -> [pid_t] {
var buffer = [pid_t](repeating: 0, count: 64)
let bytes = proc_listchildpids(pid, &buffer, Int32(buffer.count * MemoryLayout<pid_t>.size))
guard bytes > 0 else { return [] }
return buffer.filter { $0 > 0 }
}
}