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:
@@ -42,7 +42,11 @@ public final class SourceControlStore {
|
||||
/// `user.name <user.email>`, read when the view opens.
|
||||
public private(set) var author: String?
|
||||
public private(set) var branches = GitBranchList.empty
|
||||
/// The last 30 commits of HEAD, read with the branches.
|
||||
public private(set) var recentCommits: [GitCommitSummary] = []
|
||||
public private(set) var busy: GitBusy?
|
||||
/// True while the Claude CLI writes a commit message for the staged changes.
|
||||
public private(set) var isGeneratingMessage = false
|
||||
public private(set) var lines: [GitConsoleEntry] = []
|
||||
public var consoleInput = ""
|
||||
public private(set) var history: [String] = []
|
||||
@@ -58,10 +62,11 @@ public final class SourceControlStore {
|
||||
|
||||
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
|
||||
/// Asks for the keyboard in the message field, after git refused an empty message.
|
||||
/// Asks for the keyboard in the message field, after an empty message was refused.
|
||||
@ObservationIgnored public var focusMessage: () -> Void = {}
|
||||
|
||||
@ObservationIgnored private let git: GitServicing
|
||||
@ObservationIgnored private let commitMessages: CommitMessageGenerating?
|
||||
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
|
||||
@ObservationIgnored private var refreshGeneration = 0
|
||||
@ObservationIgnored private var pollTask: Task<Void, Never>?
|
||||
@@ -74,9 +79,12 @@ public final class SourceControlStore {
|
||||
/// The status error already in the console, so a poll that keeps failing logs it once.
|
||||
@ObservationIgnored private var loggedStatusError: String?
|
||||
|
||||
/// `derive` runs off the main actor, since it diffs every changed file.
|
||||
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
||||
/// `derive` runs off the main actor, since it diffs every changed file. Without `commitMessages` the
|
||||
/// generate button stays off.
|
||||
public init(git: GitServicing, commitMessages: CommitMessageGenerating? = nil,
|
||||
derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
||||
self.git = git
|
||||
self.commitMessages = commitMessages
|
||||
self.derive = derive
|
||||
}
|
||||
|
||||
@@ -91,19 +99,37 @@ public final class SourceControlStore {
|
||||
return out
|
||||
}
|
||||
|
||||
/// Any change, staged or not; it locks branch switching.
|
||||
/// Any change, staged or not; it locks branch switching and merging.
|
||||
public var isDirty: Bool { !state.changes.isEmpty }
|
||||
|
||||
/// Distinct changed paths, a file with two rows once.
|
||||
public var changedPathCount: Int { Set(state.changes.map(\.path)).count }
|
||||
|
||||
/// Distinct paths with an unstaged row: what Clean up throws away.
|
||||
public var cleanUpPathCount: Int { Set(state.changes.filter { !$0.staged }.map(\.path)).count }
|
||||
|
||||
/// Off while a push or pull runs, and during a conflict, which only a resolution may touch.
|
||||
public var canCleanUp: Bool {
|
||||
busy == nil && cleanUpPathCount > 0 && !state.changes.contains { $0.status == .unmerged }
|
||||
}
|
||||
|
||||
public var stagedPathCount: Int { GitSections.uniquePaths(state.changes.filter(\.staged)).count }
|
||||
|
||||
/// Off without changes, while a push or pull runs, and during a conflict: staging a conflicted file marks it resolved.
|
||||
public var canStageAllAndCommit: Bool {
|
||||
busy == nil && isDirty && !state.changes.contains { $0.status == .unmerged }
|
||||
}
|
||||
|
||||
/// The ready look of the Commit button; the button itself always runs git.
|
||||
public var canCommitNow: Bool {
|
||||
stagedPathCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
|
||||
}
|
||||
|
||||
/// The Gen. Commit Message button's on state.
|
||||
public var canGenerateMessage: Bool {
|
||||
commitMessages != nil && stagedPathCount > 0 && !isGeneratingMessage
|
||||
}
|
||||
|
||||
public var syncLabel: String {
|
||||
GitConsoleText.syncLabel(ahead: state.ahead, behind: state.behind, upstream: state.upstream)
|
||||
}
|
||||
@@ -144,6 +170,31 @@ public final class SourceControlStore {
|
||||
commitMessage = SourceControlText.normalizeCommitMessage(value)
|
||||
}
|
||||
|
||||
public static let generateFailedTitle = "Couldn't generate a commit message"
|
||||
|
||||
/// Replaces the draft with the message the Claude CLI writes for the staged diff, then focuses the field.
|
||||
/// Ignored while one is being written or nothing is staged.
|
||||
public func generateCommitMessage() async {
|
||||
guard let commitMessages, canGenerateMessage else { return }
|
||||
isGeneratingMessage = true
|
||||
defer { isGeneratingMessage = false }
|
||||
guard let staged = await git.stagedDiff(), !staged.isEmpty else {
|
||||
notify(Self.generateFailedTitle, "no staged diff")
|
||||
return
|
||||
}
|
||||
do {
|
||||
let message = try await commitMessages.generate(prompt: CommitMessagePrompt.make(staged))
|
||||
setCommitMessage(message)
|
||||
focusMessage()
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch let error as CommitMessageError {
|
||||
notify(Self.generateFailedTitle, error.detail)
|
||||
} catch {
|
||||
notify(Self.generateFailedTitle, "\(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Reading git
|
||||
|
||||
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
|
||||
@@ -183,11 +234,16 @@ public final class SourceControlStore {
|
||||
branches = await git.branches()
|
||||
}
|
||||
|
||||
/// The Git view opened: reads the author and the branches, then fetches origin so ahead/behind are honest.
|
||||
public func reloadRecentCommits() async {
|
||||
recentCommits = await git.recentCommits()
|
||||
}
|
||||
|
||||
/// The Git view opened: reads the author, the branches and the recent commits, then fetches origin so ahead/behind are honest.
|
||||
/// Without an origin there is nothing to fetch, so the console stays quiet.
|
||||
public func viewOpened() async {
|
||||
author = await git.author()
|
||||
await reloadBranches()
|
||||
await reloadRecentCommits()
|
||||
await loadIfNeeded()
|
||||
guard !isFetching, state.isRepository, !branches.remote.isEmpty || state.upstream?.hasPrefix("origin/") == true else { return }
|
||||
isFetching = true
|
||||
@@ -199,10 +255,12 @@ public final class SourceControlStore {
|
||||
// MARK: Staging
|
||||
|
||||
/// Always the listed paths, never `add -A`, which would also take files the view has not shown yet.
|
||||
public func stage(_ paths: [String]) async {
|
||||
guard !paths.isEmpty else { return }
|
||||
await run(["add", "--"] + paths)
|
||||
@discardableResult
|
||||
public func stage(_ paths: [String]) async -> Bool {
|
||||
guard !paths.isEmpty else { return true }
|
||||
let result = await run(["add", "--"] + paths)
|
||||
await afterCommand()
|
||||
return result.succeeded
|
||||
}
|
||||
|
||||
/// A staged rename takes its source along, or the old path stays staged as deleted.
|
||||
@@ -232,13 +290,71 @@ public final class SourceControlStore {
|
||||
await afterCommand()
|
||||
}
|
||||
|
||||
/// Reverts unstaged edits to the index and removes untracked files and folders; staged content and ignored files stay.
|
||||
public func cleanUp() async {
|
||||
guard canCleanUp else { return }
|
||||
let unstaged = state.changes.filter { !$0.staged }
|
||||
let count = cleanUpPathCount
|
||||
var failure: (GitCommandResult, [String])?
|
||||
if unstaged.contains(where: { $0.status != .added }) {
|
||||
let arguments = ["restore", "--worktree", "--", "."]
|
||||
let result = await run(arguments)
|
||||
if !result.succeeded { failure = (result, arguments) }
|
||||
}
|
||||
if unstaged.contains(where: { $0.status == .added }) {
|
||||
// No -x: ignored files such as .env, vendor/ and node_modules/ must survive.
|
||||
let arguments = ["clean", "-fd"]
|
||||
let result = await run(arguments)
|
||||
if !result.succeeded && failure == nil { failure = (result, arguments) }
|
||||
}
|
||||
await afterCommand()
|
||||
if case let (result, arguments)? = failure {
|
||||
notify("Clean up failed", Self.failureDetail(of: result, arguments: arguments))
|
||||
} else {
|
||||
notify("Cleaned up \(count) file\(count == 1 ? "" : "s")", nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func unstagedStatus(_ path: String) -> GitStatus? {
|
||||
state.changes.first { !$0.staged && $0.path == path }?.status
|
||||
}
|
||||
|
||||
/// The confirm dialog a discard needs, or nil to run it straight away; restoring deleted files never asks.
|
||||
/// The confirm dialog a discard, clean up or merge needs, or nil to run it straight away; restoring deleted files never asks.
|
||||
/// A merge that `mergeBranch` refuses (dirty tree, current branch) asks nothing, so the refusal toast shows at once.
|
||||
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
||||
guard case let .gitDiscard(paths) = action, config.confirmDiscard, !paths.isEmpty else { return nil }
|
||||
switch action {
|
||||
case let .gitDiscard(paths): discardConfirmation(paths, action: action)
|
||||
case let .mergeBranch(name): mergeConfirmation(name, action: action)
|
||||
case .gitCleanUp: cleanUpConfirmation()
|
||||
default: nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Always asks, whatever `confirmDiscard` says; nil only when `cleanUp` would refuse anyway.
|
||||
private func cleanUpConfirmation() -> ConfirmRequest? {
|
||||
guard canCleanUp else { return nil }
|
||||
let count = cleanUpPathCount
|
||||
return ConfirmRequest(
|
||||
title: "Clean up \(count) file\(count == 1 ? "" : "s")?",
|
||||
body: "New files are removed from disk and unstaged changes are reverted. Staged changes stay. This cannot be undone.",
|
||||
confirmLabel: "Clean up",
|
||||
action: .gitCleanUp
|
||||
)
|
||||
}
|
||||
|
||||
private func mergeConfirmation(_ name: String, action: ContextAction) -> ConfirmRequest? {
|
||||
let current = state.branch
|
||||
guard !isDirty, name != current else { return nil }
|
||||
return ConfirmRequest(
|
||||
title: "Merge \(name) into \(current)?",
|
||||
body: "Git merges the commits of \(name) into \(current). A conflict stops the merge for you to resolve.",
|
||||
confirmLabel: "Merge",
|
||||
action: action
|
||||
)
|
||||
}
|
||||
|
||||
private func discardConfirmation(_ paths: [String], action: ContextAction) -> ConfirmRequest? {
|
||||
guard config.confirmDiscard, !paths.isEmpty else { return nil }
|
||||
let statuses = paths.map(unstagedStatus)
|
||||
let hasNew = statuses.contains(.added)
|
||||
if statuses.allSatisfy({ $0 == .deleted }) { return nil }
|
||||
@@ -272,6 +388,18 @@ public final class SourceControlStore {
|
||||
if andPush { await push() }
|
||||
}
|
||||
|
||||
/// Stages every unstaged path, new files included, then commits without a push.
|
||||
/// An empty message stages nothing, so a refusal never leaves the files half done.
|
||||
public func stageAllAndCommit() async {
|
||||
guard canStageAllAndCommit else { return }
|
||||
guard !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty else {
|
||||
focusMessage()
|
||||
return
|
||||
}
|
||||
guard await stage(state.unstagedPaths) else { return }
|
||||
await commit()
|
||||
}
|
||||
|
||||
/// A branch without an upstream is pushed again with `-u origin <branch>`. Ignored while a push or pull runs.
|
||||
public func push() async {
|
||||
guard busy == nil else { return }
|
||||
@@ -337,6 +465,31 @@ public final class SourceControlStore {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Runs `git merge --no-edit` into the current branch; refuses with a toast while the tree is dirty, without asking git.
|
||||
@discardableResult
|
||||
public func mergeBranch(_ name: String) async -> Bool {
|
||||
if isDirty {
|
||||
let count = changedPathCount
|
||||
notify("— Commit or discard \(count) file\(count == 1 ? "" : "s") before you merge.", nil)
|
||||
return false
|
||||
}
|
||||
let current = state.branch
|
||||
guard name != current else { return false }
|
||||
let arguments = ["merge", "--no-edit", name]
|
||||
let result = await run(arguments)
|
||||
await afterCommand()
|
||||
guard result.succeeded else {
|
||||
if state.changes.contains(where: { $0.status == .unmerged }) {
|
||||
notify("Merge conflict — resolve, then commit", nil)
|
||||
} else {
|
||||
notify("Merge failed", Self.failureDetail(of: result, arguments: arguments))
|
||||
}
|
||||
return false
|
||||
}
|
||||
notify("Merged \(name) into \(current)", nil)
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: Console
|
||||
|
||||
/// Runs what was typed; `clear` empties the log and a bare `log` reads as a short one-line log.
|
||||
@@ -404,6 +557,7 @@ public final class SourceControlStore {
|
||||
private func afterCommand() async {
|
||||
await refresh()
|
||||
await reloadBranches()
|
||||
await reloadRecentCommits()
|
||||
}
|
||||
|
||||
private func log(_ text: String, _ kind: GitLineKind) {
|
||||
|
||||
Reference in New Issue
Block a user