Sources/OrgPrograms/Git.swift
146 lines · 7559 bytes
9 symbols in this file
1#if os(macOS)
2import Foundation
3
4/// The system git, run as a process that can't prompt for anything and is stopped after a time
5/// limit.
6public struct Git: Sendable {
7 public let executable: URL
8
9 public struct Output: Sendable {
10 public let status: Int32
11 public let stdout: String
12 public let stderr: String
13 public var succeeded: Bool { status == 0 }
14 /// The first line of what git said went wrong.
15 public var problem: String {
16 let lines = (stderr + "\n" + stdout).split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
17 return lines.first { $0.hasPrefix("fatal:") || $0.hasPrefix("error:") } ?? lines.first ?? "git exited with status \(status)"
18 }
19 }
20
21 public struct Failure: Error, CustomStringConvertible {
22 public let description: String
23 }
24
25 public init(executable: URL) {
26 self.executable = executable
27 }
28
29 /// `ORGSTAR_GIT`, the usual install locations, then the `PATH` Babel uses. `/usr/bin/git` only
30 /// when the developer tools are installed: without them it asks to install them.
31 public static func find(environment: [String: String] = ProcessInfo.processInfo.environment) -> Git? {
32 let path = (BabelRunner.environment["PATH"] ?? "").split(separator: ":").map { "\($0)/git" }
33 let candidates = [environment["ORGSTAR_GIT"]].compactMap { $0 } + [
34 "/opt/homebrew/bin/git", "/usr/local/bin/git", "/run/current-system/sw/bin/git",
35 ] + path
36 for candidate in candidates where FileManager.default.isExecutableFile(atPath: candidate) {
37 if candidate == "/usr/bin/git", !developerToolsInstalled { continue }
38 return Git(executable: URL(fileURLWithPath: candidate))
39 }
40 return nil
41 }
42
43 static let developerToolsInstalled: Bool = {
44 let process = Process()
45 process.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select")
46 process.arguments = ["-p"]
47 let out = Pipe()
48 process.standardOutput = out
49 process.standardError = FileHandle.nullDevice
50 guard (try? process.run()) != nil else { return false }
51 let folder = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
52 process.waitUntilExit()
53 return process.terminationStatus == 0 && FileManager.default.isExecutableFile(atPath: folder + "/usr/bin/git")
54 }()
55
56 /// Babel's environment with every way git or ssh could ask for a password or a host key
57 /// turned into a failure, English messages, and no optional index locks.
58 static var environment: [String: String] {
59 var environment = BabelRunner.environment
60 environment["GIT_TERMINAL_PROMPT"] = "0"
61 environment["GIT_ASKPASS"] = "/usr/bin/false"
62 environment["SSH_ASKPASS"] = "/usr/bin/false"
63 environment["SSH_ASKPASS_REQUIRE"] = "force"
64 environment["GIT_OPTIONAL_LOCKS"] = "0"
65 environment["GIT_EDITOR"] = "/usr/bin/false"
66 environment["LC_ALL"] = "C"
67 environment["LANG"] = "C"
68 return environment
69 }
70
71 /// Runs git with `arguments` in `directory`. Output goes through files, so a child that
72 /// keeps a descriptor open can't hold up the result. Throws when the time limit passes.
73 public func run(_ arguments: [String], in directory: URL, timeout: Duration = .seconds(30)) async throws -> Output {
74 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-git-\(UUID().uuidString)")
75 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
76 defer { try? FileManager.default.removeItem(at: folder) }
77 let outURL = folder.appendingPathComponent("out"), errURL = folder.appendingPathComponent("err")
78 FileManager.default.createFile(atPath: outURL.path, contents: nil)
79 FileManager.default.createFile(atPath: errURL.path, contents: nil)
80 let out = try FileHandle(forWritingTo: outURL), err = try FileHandle(forWritingTo: errURL)
81 defer {
82 try? out.close()
83 try? err.close()
84 }
85 let process = Process()
86 process.executableURL = executable
87 process.arguments = ["-c", "core.quotePath=false"] + arguments
88 process.currentDirectoryURL = directory
89 process.environment = Self.environment
90 process.standardInput = FileHandle.nullDevice
91 process.standardOutput = out
92 process.standardError = err
93 try process.run()
94 let deadline = ContinuousClock.now + timeout
95 while process.isRunning {
96 if ContinuousClock.now > deadline {
97 process.terminate()
98 throw Failure(description: "git \(arguments.first ?? "") took longer than \(timeout.components.seconds) seconds and was stopped")
99 }
100 try? await Task.sleep(for: .milliseconds(20))
101 }
102 return Output(
103 status: process.terminationStatus,
104 stdout: String(decoding: (try? Data(contentsOf: outURL)) ?? Data(), as: UTF8.self),
105 stderr: String(decoding: (try? Data(contentsOf: errURL)) ?? Data(), as: UTF8.self)
106 )
107 }
108
109 /// The work tree and git folder holding `directory`, with symbolic links resolved; nil
110 /// outside a repository.
111 public func repository(containing directory: URL) async -> (top: URL, gitDir: URL)? {
112 guard let output = try? await run(["rev-parse", "--show-toplevel", "--absolute-git-dir"], in: directory), output.succeeded else { return nil }
113 let lines = output.stdout.split(separator: "\n").map(String.init)
114 guard lines.count >= 2 else { return nil }
115 return (URL(fileURLWithPath: lines[0]).resolvingSymlinksInPath(), URL(fileURLWithPath: lines[1]).resolvingSymlinksInPath())
116 }
117
118 /// `file` relative to the work tree `top`, after resolving symbolic links.
119 public static func relativePath(_ file: URL, in top: URL) -> String? {
120 let path = file.resolvingSymlinksInPath().path, base = top.resolvingSymlinksInPath().path
121 guard path.hasPrefix(base + "/") else { return nil }
122 return String(path.dropFirst(base.count + 1))
123 }
124
125 /// The operation git is in the middle of in `gitDir`, which a commit or pull would disturb:
126 /// `rebase`, `merge`, `cherry-pick`, `revert`, `bisect`, or `index.lock` while another git
127 /// command holds the index. Nil when there is none.
128 public static func operationInProgress(_ gitDir: URL) -> String? {
129 let marks: [(String, String)] = [
130 ("rebase-merge", "rebase"), ("rebase-apply", "rebase"), ("MERGE_HEAD", "merge"),
131 ("CHERRY_PICK_HEAD", "cherry-pick"), ("REVERT_HEAD", "revert"), ("BISECT_LOG", "bisect"),
132 ("index.lock", "index.lock"),
133 ]
134 return marks.first { FileManager.default.fileExists(atPath: gitDir.appendingPathComponent($0.0).path) }?.1
135 }
136
137 /// Whether git's message says the remote refused or couldn't ask for credentials.
138 public static func isAuthenticationFailure(_ message: String) -> Bool {
139 let signs = [
140 "Authentication failed", "could not read Username", "could not read Password", "terminal prompts disabled",
141 "Permission denied (publickey", "Host key verification failed", "returned error: 403", "returned error: 401",
142 ]
143 return signs.contains { message.localizedCaseInsensitiveContains($0) }
144 }
145}
146#endif