LocalGit.swift (4306B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 #if os(macOS) 3 import Foundation 4 import GitLite 5 6 /// Local git repository driven by the `git` command, to check GitLite against the real git. 7 public struct LocalGit: Sendable { 8 public let directory: URL 9 10 public init(directory: URL) { 11 self.directory = directory 12 } 13 14 public static func temporaryDirectory(_ name: String = "repo") throws -> URL { 15 let url = FileManager.default.temporaryDirectory 16 .appendingPathComponent("divekit-\(UUID().uuidString)").appendingPathComponent(name) 17 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) 18 return url 19 } 20 21 public static func create(bare: Bool = false, name: String = "repo") throws -> LocalGit { 22 let repo = LocalGit(directory: try temporaryDirectory(name)) 23 try repo.git(["init", "-q", "-b", "main"] + (bare ? ["--bare"] : [])) 24 try repo.git(["config", "user.name", "Test"]) 25 try repo.git(["config", "user.email", "test@example.com"]) 26 try repo.git(["config", "uploadpack.allowAnySHA1InWant", "true"]) 27 return repo 28 } 29 30 @discardableResult 31 public func git(_ arguments: [String], input: [UInt8]? = nil) throws -> [UInt8] { 32 try Self.run(arguments, in: directory, input: input) 33 } 34 35 public func text(_ arguments: [String]) throws -> String { 36 String(decoding: try git(arguments), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) 37 } 38 39 public func write(_ path: String, _ content: String) throws { 40 let url = directory.appendingPathComponent(path) 41 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) 42 try Data(content.utf8).write(to: url) 43 } 44 45 @discardableResult 46 public func commitAll(_ message: String) throws -> ObjectID { 47 try git(["add", "-A"]) 48 try git(["commit", "-q", "--allow-empty", "-m", message]) 49 return ObjectID(hex: try text(["rev-parse", "HEAD"]))! 50 } 51 52 public static func run(_ arguments: [String], in directory: URL, input: [UInt8]? = nil) throws -> [UInt8] { 53 let process = Process() 54 process.executableURL = URL(fileURLWithPath: "/usr/bin/env") 55 process.arguments = ["git"] + arguments 56 process.currentDirectoryURL = directory 57 let stdout = Pipe(), stderr = Pipe(), stdin = Pipe() 58 process.standardOutput = stdout 59 process.standardError = stderr 60 process.standardInput = stdin 61 try process.run() 62 let writer = Thread { 63 if let input { stdin.fileHandleForWriting.write(Data(input)) } 64 try? stdin.fileHandleForWriting.close() 65 } 66 writer.start() 67 var errorData = Data() 68 let errorReader = Thread { errorData = stderr.fileHandleForReading.readDataToEndOfFile() } 69 errorReader.start() 70 let output = stdout.fileHandleForReading.readDataToEndOfFile() 71 process.waitUntilExit() 72 while !errorReader.isFinished { usleep(1000) } 73 guard process.terminationStatus == 0 else { 74 throw GitError.remote("git \(arguments.joined(separator: " ")): \(String(decoding: errorData, as: UTF8.self))") 75 } 76 return Array(output) 77 } 78 } 79 80 /// Transport that talks to the real `git upload-pack` / `git receive-pack` in stateless mode, as an HTTP server would. 81 public struct LocalProcessTransport: GitTransport { 82 public let repository: URL 83 84 public init(repository: URL) { 85 self.repository = repository 86 } 87 88 private func command(_ service: GitService) -> String { 89 service == .uploadPack ? "upload-pack" : "receive-pack" 90 } 91 92 public func advertisement(_ service: GitService) async throws -> [UInt8] { 93 let refs = try LocalGit.run([command(service), "--stateless-rpc", "--advertise-refs", repository.path], in: repository) 94 let header = "# service=\(service.rawValue)\n" 95 return Array(String(format: "%04x", header.utf8.count + 4).utf8) + Array(header.utf8) + Array("0000".utf8) + refs 96 } 97 98 public func rpc(_ service: GitService, body: [UInt8]) async throws -> [UInt8] { 99 try LocalGit.run([command(service), "--stateless-rpc", repository.path], in: repository, input: body) 100 } 101 } 102 #endif