Repository Public
1import Foundation2internal import SPProcess34/// Errors thrown by GitKit.5public enum GitError: Error, Sendable, Equatable, LocalizedError {6 /// The arguments are not on the read-only allowlist; nothing was executed.7 case commandNotAllowed(String)8 /// The location is not inside a git work tree.9 case notARepository(String)10 case commandFailed(exitStatus: Int32, stderr: String)11 case timedOut12 case launchFailed(String)13 case invalidArgument(String)1415 public var errorDescription: String? {16 switch self {17 case .commandNotAllowed(let reason): return "Git command refused (read-only allowlist): \(reason)"18 case .notARepository(let path): return "Not inside a git work tree: \(path)"19 case .commandFailed(let status, let stderr): return "git exited with status \(status): \(stderr)"20 case .timedOut: return "git timed out."21 case .launchFailed(let reason): return "git could not be launched: \(reason)"22 case .invalidArgument(let reason): return "Invalid argument: \(reason)"23 }24 }25}2627/// Captured output of a successful git invocation.28public struct GitOutput: Sendable, Hashable {29 public var standardOutput: Data30 public var standardError: String31 /// `true` when stdout hit the size cap: git was stopped and `standardOutput` is cut at the cap.32 public var truncated: Bool3334 /// stdout decoded as UTF-8 (invalid sequences are replaced).35 public var text: String { String(decoding: standardOutput, as: UTF8.self) }36}3738/// Runs `/usr/bin/git` for read-only queries only.39///40/// Every invocation is checked against an allowlist before anything is spawned, uses41/// `--no-optional-locks`, a scrubbed environment (`GIT_TERMINAL_PROMPT=0`, `GIT_OPTIONAL_LOCKS=0`),42/// a timeout and a cap on captured output.43public struct GitRunner: Sendable, Hashable {44 /// Path of the git executable.45 public var executable: String46 /// Wall-clock limit per invocation.47 public var timeout: Duration48 /// Default cap on captured stdout, in bytes.49 public var maxOutputBytes: Int5051 public init(executable: String = "/usr/bin/git", timeout: Duration = .seconds(10), maxOutputBytes: Int = 4 << 20) {52 self.executable = executable53 self.timeout = timeout54 self.maxOutputBytes = maxOutputBytes55 }5657 /// Subcommands that may be run (some with further restrictions, see ``validate(_:)``).58 public static let allowedSubcommands: [String] = ["branch", "diff", "log", "remote", "rev-parse", "show", "status", "worktree"]5960 /// Options placed before the subcommand on every invocation.61 public static let globalArguments: [String] = [62 "--no-optional-locks", "--no-pager",63 "-c", "core.fsmonitor=false",64 "-c", "log.showSignature=false",65 "-c", "gpg.program=/usr/bin/false",66 "-c", "gpg.ssh.program=/usr/bin/false",67 "-c", "gpg.x509.program=/usr/bin/false",68 ]6970 /// Environment variables forced on every invocation (the rest of the environment is reduced to71 /// `PATH`, `HOME`, `USER`, `LOGNAME`, `TMPDIR` and `DEVELOPER_DIR`, so no inherited `GIT_*` applies).72 public static let environmentOverrides: [String: String] = [73 "GIT_TERMINAL_PROMPT": "0",74 "GIT_OPTIONAL_LOCKS": "0",75 "GIT_PAGER": "cat",76 "LC_ALL": "C",77 ]7879 /// Runs an allowlisted read-only git command in `directory`.80 ///81 /// - Parameters:82 /// - arguments: subcommand first, e.g. `["status", "--porcelain=v2"]`; global options are refused.83 /// - maxOutputBytes: overrides the runner's cap for this call.84 /// - Throws: ``GitError/commandNotAllowed(_:)`` before spawning anything when the command is not85 /// read-only; ``GitError/commandFailed(exitStatus:stderr:)`` on a non-zero exit.86 public func run(_ arguments: [String], in directory: URL, maxOutputBytes: Int? = nil) async throws -> GitOutput {87 let argv = try Self.commandLine(for: arguments)88 var environment: [String: String] = [:]89 let inherited = ProcessInfo.processInfo.environment90 for key in ["PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "DEVELOPER_DIR"] {91 environment[key] = inherited[key]92 }93 environment.merge(Self.environmentOverrides) { _, forced in forced }9495 let output: ProcessOutput96 do {97 output = try await runProcess(98 executable: URL(fileURLWithPath: executable),99 arguments: argv,100 environment: environment,101 currentDirectory: directory,102 timeout: timeout,103 maxOutputBytes: maxOutputBytes ?? self.maxOutputBytes104 )105 } catch let error as ProcessRunError {106 switch error {107 case .launchFailed(let reason): throw GitError.launchFailed(reason)108 }109 }110 let stderr = String(decoding: output.standardError, as: UTF8.self)111 if output.timedOut { throw GitError.timedOut }112 if output.outputTruncated {113 return GitOutput(standardOutput: output.standardOutput, standardError: stderr, truncated: true)114 }115 guard output.exitStatus == 0 else {116 throw GitError.commandFailed(exitStatus: output.exitStatus, stderr: stderr.trimmingCharacters(in: .whitespacesAndNewlines))117 }118 return GitOutput(standardOutput: output.standardOutput, standardError: stderr, truncated: false)119 }120121 /// The full argv (without the executable) that ``run(_:in:maxOutputBytes:)`` would spawn.122 public static func commandLine(for arguments: [String]) throws -> [String] {123 try validate(arguments)124 var argv = globalArguments125 argv.append(arguments[0])126 if ["diff", "log", "show"].contains(arguments[0]) {127 // Never run external diff drivers or textconv filters configured in the repository.128 argv += ["--no-ext-diff", "--no-textconv"]129 }130 argv += arguments.dropFirst()131 return argv132 }133134 /// Checks arguments against the read-only allowlist; throws ``GitError/commandNotAllowed(_:)``.135 ///136 /// Allowed: `rev-parse`, `status`, `log`, `diff`, `show` (without options that write files or run137 /// programs), `branch` in listing mode only, `worktree list`, `remote` / `remote -v` /138 /// `remote get-url`. The first argument must be the subcommand.139 public static func validate(_ arguments: [String]) throws {140 func refuse(_ reason: String) -> GitError { .commandNotAllowed(reason) }141 guard let subcommand = arguments.first else { throw refuse("no subcommand") }142 guard !arguments.contains(where: { $0.contains("\0") }) else { throw refuse("NUL byte in argument") }143 guard !subcommand.hasPrefix("-") else { throw refuse("global option \(subcommand)") }144 guard allowedSubcommands.contains(subcommand) else { throw refuse(subcommand) }145146 let rest = Array(arguments.dropFirst())147 let options = rest.prefix { $0 != "--" }.filter { $0.hasPrefix("-") }148 for option in options {149 let name = String(option.prefix { $0 != "=" })150 if name == "--text" { continue }151 // git accepts unambiguous abbreviations of long options, so match prefixes both ways.152 for forbidden in ["--output", "--ext-diff", "--textconv", "--no-index", "--show-signature"]153 where name.count > 2 && (forbidden.hasPrefix(name) || name.hasPrefix(forbidden)) {154 throw refuse("\(subcommand) \(option)")155 }156 }157158 switch subcommand {159 case "branch":160 let listing: Set<String> = ["--list", "-a", "--all", "-r", "--remotes", "--show-current"]161 let neutral: Set<String> = ["-v", "-vv", "--verbose", "--no-color", "--no-column", "--no-abbrev", "-i", "--ignore-case"]162 let valued = ["--format=", "--sort=", "--contains=", "--no-contains=", "--merged=", "--no-merged=", "--points-at=", "--color=", "--abbrev="]163 var isListing = false164 var hasPositional = false165 var afterSeparator = false166 for argument in rest {167 if afterSeparator || !argument.hasPrefix("-") {168 hasPositional = true169 } else if argument == "--" {170 afterSeparator = true171 } else if listing.contains(argument) {172 isListing = true173 } else if !neutral.contains(argument) && !valued.contains(where: argument.hasPrefix) {174 throw refuse("branch \(argument)")175 }176 }177 guard isListing else { throw refuse("branch without a listing option") }178 guard !hasPositional || rest.contains("--list") else { throw refuse("branch pattern without --list") }179 case "worktree":180 guard rest.first == "list" else { throw refuse("worktree \(rest.first ?? "")") }181 let allowed: Set<String> = ["--porcelain", "-v", "--verbose", "-z"]182 if let bad = rest.dropFirst().first(where: { !allowed.contains($0) }) { throw refuse("worktree list \(bad)") }183 case "remote":184 if rest.isEmpty || rest == ["-v"] || rest == ["--verbose"] { break }185 guard rest.first == "get-url" else { throw refuse("remote \(rest.joined(separator: " "))") }186 let tail = rest.dropFirst()187 let names = tail.filter { !$0.hasPrefix("-") }188 let flags = tail.filter { $0.hasPrefix("-") }189 guard names.count == 1, flags.allSatisfy({ $0 == "--push" || $0 == "--all" }) else {190 throw refuse("remote \(rest.joined(separator: " "))")191 }192 default:193 break194 }195 }196}197