adds nice git interface
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user