Repository Public
1import Foundation23public enum GitSafetyError: Error, LocalizedError, Sendable, Equatable {4 case worktreeHasUncommittedChanges(String)5 case refusingDestructiveOperation(String)6 case invalidBranchName(String)7 case pathExists(String)89 public var errorDescription: String? {10 switch self {11 case .worktreeHasUncommittedChanges(let p): return "The worktree at \(p) has uncommitted changes. Commit or stash them first."12 case .refusingDestructiveOperation(let what): return "NEXTERM never performs \(what) automatically."13 case .invalidBranchName(let n): return "\"\(n)\" is not a valid branch name."14 case .pathExists(let p): return "\(p) already exists."15 }16 }17}1819/// Read-mostly Git facade for one repository. Mutating operations are limited to worktree20/// creation and the removal of *clean* worktrees; merges, resets, force pushes, `clean` and branch21/// deletion are deliberately not offered.22public actor GitRepository {23 public let path: String2425 public init(path: String) { self.path = path }2627 /// Resolves the repository root for a directory (nil when not inside a repo).28 public static func discover(from directory: String) async -> String? {29 guard let out = try? await GitRunner.check(["rev-parse", "--show-toplevel"], in: directory, timeout: 10) else { return nil }30 let root = out.trimmingCharacters(in: .whitespacesAndNewlines)31 return root.isEmpty ? nil : root32 }3334 public func status() async throws -> GitStatus {35 GitParsers.parseStatus(try await GitRunner.check(["status", "--porcelain=v2", "--branch", "-z"], in: path))36 }3738 public func log(limit: Int = 50) async throws -> [GitCommit] {39 let out = try await GitRunner.run(["log", "--format=%H%x1f%an%x1f%at%x1f%s", "-n", String(max(1, limit))], in: path)40 return out.succeeded ? GitParsers.parseLog(out.stdout) : [] // empty repo → no commits41 }4243 public func diff(path file: String? = nil, staged: Bool = false, contextLines: Int = 3) async throws -> String {44 var args = ["diff", "--no-ext-diff", "-U\(contextLines)"]45 if staged { args.append("--cached") }46 if let file { args += ["--", file] }47 return try await GitRunner.check(args, in: path, timeout: 60)48 }4950 public func worktrees() async throws -> [GitWorktree] {51 GitParsers.parseWorktrees(try await GitRunner.check(["worktree", "list", "--porcelain"], in: path))52 }5354 public func branches() async throws -> [String] {55 try await GitRunner.check(["for-each-ref", "--format=%(refname:short)", "refs/heads"], in: path)56 .split(whereSeparator: \.isNewline).map(String.init)57 }5859 public static func isValidBranchName(_ name: String) -> Bool {60 guard !name.isEmpty, !name.hasPrefix("-"), !name.hasSuffix("/"), !name.hasSuffix(".lock"), !name.contains("..") else { return false }61 return name.unicodeScalars.allSatisfy { $0.value > 0x20 && $0.value != 0x7f && !"~^:?*[\\".unicodeScalars.contains($0) }62 }6364 /// Creates a worktree at `destination`. With `createBranch` the branch is created from `startPoint` (default HEAD).65 public func addWorktree(at destination: String, branch: String, createBranch: Bool, startPoint: String? = nil) async throws {66 guard Self.isValidBranchName(branch) else { throw GitSafetyError.invalidBranchName(branch) }67 guard !FileManager.default.fileExists(atPath: destination) else { throw GitSafetyError.pathExists(destination) }68 var args = ["worktree", "add"]69 if createBranch { args += ["-b", branch, "--", destination]; if let startPoint { args.append(startPoint) } }70 else { args += ["--", destination, branch] }71 try await GitRunner.check(args, in: path, timeout: 120)72 }7374 /// True when the worktree has staged, unstaged or untracked (non-ignored) changes.75 public func isDirty(worktree: String) async throws -> Bool {76 let s = GitParsers.parseStatus(try await GitRunner.check(["status", "--porcelain=v2", "-z"], in: worktree))77 return !s.isClean78 }7980 /// Removes a worktree only if it is clean. There is intentionally no `force` parameter.81 public func removeCleanWorktree(at worktree: String) async throws {82 if try await isDirty(worktree: worktree) { throw GitSafetyError.worktreeHasUncommittedChanges(worktree) }83 try await GitRunner.check(["worktree", "remove", "--", worktree], in: path, timeout: 60)84 }85}86