adds claude-generated commit messages and a recent commits panel to the git view - adds log tailing in the explorer, branch merging and a clean up button

This commit is contained in:
2026-11-04 10:07:52 +01:00
parent 600d4874d2
commit cc6651c08a
49 changed files with 1944 additions and 180 deletions
@@ -0,0 +1,87 @@
import Foundation
import HelderCore
/// Why no commit message came back; `detail` is the toast's mono line.
public enum CommitMessageError: Error, Equatable {
case notFound
case timedOut
/// The CLI could not start or exited non-zero; the first stderr line, else the exit code.
case failed(String)
/// The CLI answered with nothing usable.
case empty
public var detail: String {
switch self {
case .notFound: "claude not found"
case .timedOut: "timed out"
case let .failed(reason): reason
case .empty: "claude returned no message"
}
}
}
/// Writes a commit message for a prompt built by `CommitMessagePrompt`.
public protocol CommitMessageGenerating: Sendable {
/// The cleaned one-line message; throws `CommitMessageError`, or `CancellationError` when the caller went away.
func generate(prompt: String) async throws -> String
}
/// Runs the Claude CLI in print mode, with no tools, in the project root.
public struct ClaudeCommitMessageService: CommitMessageGenerating {
public let root: URL
private let runner: ProcessRunning
private let locator: ExecutableLocator
private let timeout: TimeInterval
/// No `--model`: the CLI's own default model writes the message.
public static let arguments = [
"-p", "--output-format", "text", "--no-session-persistence", "--strict-mcp-config", "--disable-slash-commands",
"--tools", "",
]
public init(root: URL, runner: ProcessRunning = ProcessRunner(), locator: ExecutableLocator = .agent, timeout: TimeInterval = 90) {
self.root = root
self.runner = runner
self.locator = locator
self.timeout = timeout
}
/// The found binary's folder goes first on the child's PATH, so the CLI finds its own helpers.
public func generate(prompt: String) async throws -> String {
guard let binary = locator.locate("claude") else { throw CommitMessageError.notFound }
var environment = ProcessInfo.processInfo.environment
let folder = binary.deletingLastPathComponent().path
environment["PATH"] = [folder, environment["PATH"]].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ":")
let runner = self.runner, root = self.root, timeout = self.timeout
let outcome = try await withThrowingTaskGroup(of: ProcessResult?.self) { group -> ProcessResult? in
group.addTask {
do {
return try await runner.run(binary.path, arguments: Self.arguments, in: root, environment: environment, input: prompt)
} catch ProcessRunnerError.executableNotFound {
throw CommitMessageError.notFound
} catch let ProcessRunnerError.launchFailed(reason) {
throw CommitMessageError.failed(reason)
}
}
group.addTask {
try await Task.sleep(nanoseconds: UInt64(max(0, timeout) * 1_000_000_000))
return nil
}
defer { group.cancelAll() }
return try await group.next() ?? nil
}
guard let result = outcome else { throw CommitMessageError.timedOut }
guard result.succeeded else {
throw CommitMessageError.failed(Self.reason(stderr: result.stderr) ?? "claude exited with code \(result.exitCode)")
}
guard let message = CommitMessagePrompt.clean(result.stdout) else { throw CommitMessageError.empty }
return message
}
/// The first stderr line; the CLI prints notices such as a sign-in expiry as "Warning: …" before the real error.
static func reason(stderr: String) -> String? {
let lines = stderr.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
return lines.first { !$0.hasPrefix("Warning:") } ?? lines.first
}
}
@@ -112,6 +112,21 @@ public actor GitService: GitServicing {
return "\(name) <\(email)>"
}
public func recentCommits() async -> [GitCommitSummary] {
guard let result = try? await Self.run(GitCommitLogParsing.arguments, root: root, runner: runner), result.succeeded else {
return []
}
return GitCommitLogParsing.commits(result.stdout)
}
/// No external diff driver, so the patch is git's own text whatever the user configured.
public func stagedDiff() async -> StagedDiff? {
async let stat = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff", "--stat"], root: root, runner: runner)
async let patch = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff"], root: root, runner: runner)
guard let stat = await stat, stat.succeeded, let patch = await patch, patch.succeeded else { return nil }
return StagedDiff(stat: stat.stdout, patch: patch.stdout)
}
private func configValue(_ key: String) async -> String? {
guard let result = try? await Self.run(["config", "--get", key], root: root, runner: runner), result.succeeded else { return nil }
let value = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -31,6 +31,10 @@ public protocol GitServicing: Sendable {
func branches() async -> GitBranchList
/// `user.name <user.email>` from git config, nil when unset.
func author() async -> String?
/// The last 30 commits of HEAD, newest first; empty without commits or outside a repository.
func recentCommits() async -> [GitCommitSummary]
/// `git diff --cached` as stat and patch; nil when git fails, e.g. outside a repository.
func stagedDiff() async -> StagedDiff?
}
extension GitServicing {
@@ -20,6 +20,16 @@ public struct ExecutableLocator: Sendable {
return ExecutableLocator(directories: dirs.filter { seen.insert($0).inserted })
}
/// `standard` plus the folders the Claude CLI installs itself into, which a GUI app's PATH never holds.
public static var agent: ExecutableLocator {
let home = FileManager.default.homeDirectoryForCurrentUser.path
var locator = standard
for dir in ["\(home)/.local/bin", "\(home)/.claude/local"] where !locator.directories.contains(dir) {
locator.directories.append(dir)
}
return locator
}
/// The first executable file called `name`, or nil. A name with a slash is checked as given.
public func locate(_ name: String) -> URL? {
let fm = FileManager.default
@@ -25,12 +25,21 @@ public protocol ProcessRunning: Sendable {
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
/// Like `run`, with `input` written to the child's stdin, which is then closed.
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
input: String) async throws -> ProcessResult
/// Like `run`, but hands each output line to `onLine` as it arrives (`isError` for stderr).
func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult
}
extension ProcessRunning {
/// Refuses, so a runner that cannot feed stdin never runs a child that would wait on it.
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
input: String) async throws -> ProcessResult {
throw ProcessRunnerError.launchFailed("stdin is not supported by \(type(of: self))")
}
/// Runs to completion, then emits the stdout lines and after them the stderr lines.
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
@@ -53,18 +62,23 @@ public struct ProcessRunner: ProcessRunning {
}
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: nil)
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: nil, onLine: nil)
}
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
input: String) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: Data(input.utf8), onLine: nil)
}
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: onLine)
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: nil, onLine: onLine)
}
private func launch(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
input: Data?, onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, onLine: onLine)
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, input: input, onLine: onLine)
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
job.start(continuation)
@@ -118,12 +132,14 @@ private final class Job: @unchecked Sendable {
private var cancelled = false
private var continuation: CheckedContinuation<ProcessResult, Error>?
private let onLine: (@Sendable (String, Bool) -> Void)?
private let input: Data?
/// Keeps `onLine` to one call at a time, though both pipes feed it.
private let emitLock = NSLock()
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?,
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?, input: Data?,
onLine: (@Sendable (String, Bool) -> Void)?) {
self.onLine = onLine
self.input = input
process.executableURL = url
process.arguments = arguments
if let directory { process.currentDirectoryURL = directory }
@@ -136,6 +152,8 @@ private final class Job: @unchecked Sendable {
let err = Pipe()
process.standardOutput = out
process.standardError = err
let stdin = input.map { _ in Pipe() }
if let stdin { process.standardInput = stdin }
let group = DispatchGroup()
var outData = Data()
@@ -159,6 +177,10 @@ private final class Job: @unchecked Sendable {
self.continuation = continuation
lock.unlock()
if let stdin, let input {
DispatchQueue.global().async { Self.write(input, to: stdin.fileHandleForWriting) }
}
group.enter()
DispatchQueue.global().async { [self] in
outData = drain(out.fileHandleForReading, isError: false)
@@ -178,6 +200,14 @@ private final class Job: @unchecked Sendable {
}
}
/// Writes on its own thread, since a child that stops reading would block it. A child that exits
/// early makes the write fail instead of raising SIGPIPE, which would end the app.
private static func write(_ data: Data, to handle: FileHandle) {
_ = fcntl(handle.fileDescriptor, F_SETNOSIGPIPE, 1)
try? handle.write(contentsOf: data)
try? handle.close()
}
/// Resumes the caller once; whichever of finish and cancel comes second is dropped.
private func resume(with result: Result<ProcessResult, Error>) {
lock.lock()