Repository Public
1import Foundation23/// Read-only view of a git work tree.4public struct GitRepository: Sendable, Hashable {5 /// Root directory of the work tree.6 public let rootURL: URL7 /// Runner used for every query.8 public let runner: GitRunner910 /// Wraps a known work tree root (no check is performed).11 public init(rootURL: URL, runner: GitRunner = GitRunner()) {12 self.rootURL = rootURL13 self.runner = runner14 }1516 /// Finds the work tree containing `url` (a directory, or a file whose directory is used).17 /// - Throws: ``GitError/notARepository(_:)`` when `url` is not inside a work tree.18 public static func discover(from url: URL, runner: GitRunner = GitRunner()) async throws -> GitRepository {19 var isDirectory: ObjCBool = false20 guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else {21 throw GitError.notARepository(url.path)22 }23 let directory = isDirectory.boolValue ? url : url.deletingLastPathComponent()24 let output: GitOutput25 do {26 output = try await runner.run(["rev-parse", "--show-toplevel"], in: directory)27 } catch GitError.commandFailed {28 throw GitError.notARepository(url.path)29 }30 let path = output.text.trimmingCharacters(in: .newlines)31 guard path.hasPrefix("/") else { throw GitError.notARepository(url.path) }32 return GitRepository(rootURL: URL(fileURLWithPath: path, isDirectory: true), runner: runner)33 }3435 /// Branch, upstream, ahead/behind and changed paths (`git status --porcelain=v2 -z --branch`).36 public func status() async throws -> GitStatus {37 let output = try await runner.run(["status", "--porcelain=v2", "-z", "--branch"], in: rootURL)38 return GitStatus.parse(porcelainV2: output.standardOutput, truncated: output.truncated)39 }4041 /// The most recent commits reachable from `HEAD`, newest first; empty before the first commit.42 public func recentCommits(limit: Int = 20) async throws -> [GitCommit] {43 guard limit > 0 else { return [] }44 let format = "--format=%H%x1f%h%x1f%an%x1f%ae%x1f%aI%x1f%s%x1e"45 let output: GitOutput46 do {47 output = try await runner.run(["log", "-n", String(min(limit, 10_000)), format], in: rootURL)48 } catch GitError.commandFailed(_, let stderr) where stderr.contains("does not have any commits yet") {49 return []50 }51 let formatter = ISO8601DateFormatter()52 formatter.formatOptions = [.withInternetDateTime]53 var records = output.text.split(separator: "\u{1e}", omittingEmptySubsequences: false)54 // The last element is the remainder after the final record separator (or a cut record).55 if !records.isEmpty { records.removeLast() }56 return records.compactMap { record in57 let fields = record.drop(while: \.isNewline).split(separator: "\u{1f}", maxSplits: 5, omittingEmptySubsequences: false).map(String.init)58 guard fields.count == 6, let date = formatter.date(from: fields[4]) else { return nil }59 return GitCommit(hash: fields[0], shortHash: fields[1], authorName: fields[2], authorEmail: fields[3], date: date, subject: fields[5])60 }61 }6263 /// Unified diff of the work tree against the index, or of the index against `HEAD` when `staged`.64 ///65 /// - Parameters:66 /// - path: optional literal path relative to the root (no pathspec magic or globbing).67 /// - maxBytes: cap on the patch size; a larger diff is cut and flagged `truncated`.68 public func diff(staged: Bool = false, path: String? = nil, maxBytes: Int = 256 * 1024) async throws -> GitDiff {69 var arguments = ["diff", "--no-color"]70 if staged { arguments.append("--cached") }71 if let path {72 guard !path.isEmpty, !path.contains("\0") else { throw GitError.invalidArgument("empty or malformed path") }73 arguments += ["--", ":(literal)" + path]74 }75 let output = try await runner.run(arguments, in: rootURL, maxOutputBytes: max(0, maxBytes))76 return GitDiff(text: output.text, truncated: output.truncated)77 }78}79