From be543fc079eec1890218dd8db6ee4e51fcd4987a Mon Sep 17 00:00:00 2001 From: dommangetnicolas Date: Sun, 15 Nov 2026 17:57:27 +0100 Subject: [PATCH 1/3] Add worktree support Linked worktrees of each project are discovered and listed under it, each with its own status and Commit, WIP, Batch oco and Push buttons; clean ones fold behind a toggle and can be removed from their menu (the branch is kept). Adding a worktree's folder adds its main repository. Batch oco now locks its temporary worktree, and leftovers from a crash are cleaned up on the next refresh. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 + README.md | 4 +- Sources/MagicCommit/Git.swift | 122 ++++++++- Sources/MagicCommit/MenuContentView.swift | 163 ++++++++++-- Sources/MagicCommit/ProjectStore.swift | 272 +++++++++++++++++---- Tests/MagicCommitTests/BatchOcoTests.swift | 41 +++- Tests/MagicCommitTests/FakeOco.swift | 26 ++ Tests/MagicCommitTests/WorktreeTests.swift | 167 +++++++++++++ scripts/screenshot-demo.sh | 27 +- 9 files changed, 741 insertions(+), 91 deletions(-) create mode 100644 Tests/MagicCommitTests/FakeOco.swift create mode 100644 Tests/MagicCommitTests/WorktreeTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bcc778..01d0741 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ and the project uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- Worktree support: linked worktrees of each project are discovered automatically and listed under it, each with its own status and Commit, WIP, Batch oco and Push buttons. Clean worktrees fold behind a toggle. +- **Remove Worktree** in a worktree's menu, for clean worktrees (the branch is kept). + +### Changed + +- Adding a linked worktree's folder adds its main repository; projects saved as worktrees are migrated the same way. +- Batch oco locks its temporary worktree, and temporary worktrees left behind by a crash are cleaned up on the next refresh. + ## [1.0.0] - 2026-11-11 ### Added diff --git a/README.md b/README.md index fcf1d38..be40fa6 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,9 @@ Each project in the panel shows its branch, changed files, WIP commits and ahead - **Batch oco**: gives each unpushed WIP commit a real message generated by `oco` from that commit's own diff. Other commits keep their messages, empty WIP commits are dropped, and original author dates are kept. - **Push**: runs `git push` (or `git push -u ` for a new branch). It warns you first if WIP commits are still in there. -The menu bar icon shows how many projects have something to commit or push. Statuses refresh when you open the panel, every 60 seconds, and after your Mac wakes. +**Worktrees** are picked up automatically: every linked worktree of a project you've added shows under it, labelled with its branch, with the same buttons. Worktrees appear and disappear as you create and remove them, and clean ones fold behind a "clean worktrees" toggle. Adding a worktree's folder adds its repository instead. A clean worktree can be removed from its `…` menu; its branch is kept. + +The menu bar icon shows how many checkouts (projects and worktrees) have something to commit or push. Statuses refresh when you open the panel, every 60 seconds, and after your Mac wakes. ## Requirements diff --git a/Sources/MagicCommit/Git.swift b/Sources/MagicCommit/Git.swift index f640633..fe90be5 100644 --- a/Sources/MagicCommit/Git.swift +++ b/Sources/MagicCommit/Git.swift @@ -1,5 +1,26 @@ import Foundation +/// One checkout of a repository: the main working tree or a linked worktree. +struct Worktree: Identifiable, Hashable { + var path: String + /// Short branch name; nil when detached (or bare). + var branch: String? + var head: String? + var isMain = false + var isBare = false + var isDetached = false + /// Lock reason (possibly empty) when locked. + var lockReason: String? + var isPrunable = false + + var id: String { path } + var name: String { URL(fileURLWithPath: path).lastPathComponent } + var url: URL { URL(fileURLWithPath: path) } + var isLocked: Bool { lockReason != nil } + /// Branch name, or the short commit for a detached worktree. + var label: String { branch ?? head.map { "detached @ \($0.prefix(7))" } ?? "detached" } +} + struct GitStatus: Equatable { var branch: String? var upstream: String? @@ -25,6 +46,98 @@ enum Git { return top.isEmpty ? nil : top } + // MARK: Worktrees + + /// Path of the repository's main working tree (or of the bare repository), + /// from any of its worktrees or subfolders. Nil when `path` isn't in a git repository. + static func mainWorktreePath(of path: String) async -> String? { + if let main = await worktrees(at: path)?.first { return main.path } + return await toplevel(of: path) + } + + /// All worktrees of the repository containing `path`, the main one first. + static func worktrees(at path: String) async -> [Worktree]? { + let r = await Shell.run(["git", "worktree", "list", "--porcelain"], in: path) + guard r.succeeded else { return nil } + let list = parseWorktreeList(r.stdout) + return list.isEmpty ? nil : list + } + + /// Parses `git worktree list --porcelain`: blocks of `worktree `, `HEAD `, + /// `branch refs/heads/`, `detached`, `bare`, `locked [reason]`, `prunable [reason]`. + static func parseWorktreeList(_ output: String) -> [Worktree] { + var result: [Worktree] = [] + var current: Worktree? + func flush() { + if let w = current { result.append(w) } + current = nil + } + for raw in output.split(separator: "\n", omittingEmptySubsequences: false) { + let line = String(raw) + if line.isEmpty { flush(); continue } + let (key, value): (String, String) = { + guard let space = line.firstIndex(of: " ") else { return (line, "") } + return (String(line[.. Bool { + let url = worktree.url + return !worktree.isMain && url.lastPathComponent.hasPrefix("magic-commit-") + && url.deletingLastPathComponent().resolvingSymlinksInPath().path + == tempDirectory.resolvingSymlinksInPath().path + } + + /// PID recorded in a temporary worktree's lock reason. + static func tempWorktreePID(_ worktree: Worktree) -> pid_t? { + guard let reason = worktree.lockReason, reason.hasPrefix("magic-commit pid ") else { return nil } + return pid_t(reason.dropFirst("magic-commit pid ".count)) + } + + /// Removes temporary worktrees left behind by a Batch oco that never finished + /// (app crashed or was killed). Those whose process is still alive are kept. + static func removeStaleTempWorktrees(_ worktrees: [Worktree], repo: String) async { + for w in worktrees where isTempWorktree(w) { + if let pid = tempWorktreePID(w), kill(pid, 0) == 0 || errno == EPERM { continue } + let removed = await Shell.run(["git", "worktree", "remove", "--force", "--force", w.path], in: repo) + if !removed.succeeded { + // Folder already gone: drop the registration. + _ = await Shell.run(["git", "worktree", "unlock", w.path], in: repo) + _ = await Shell.run(["git", "worktree", "prune"], in: repo) + } + } + } + + /// Deletes a linked worktree's folder. Git refuses if it has uncommitted changes. + /// Its branch and commits are kept. + static func removeWorktree(_ worktree: Worktree, repo: String) async -> ShellResult { + await Shell.run(["git", "worktree", "remove", worktree.path], in: repo) + } + + // MARK: Status + static func status(at path: String) async -> GitStatus { guard FileManager.default.fileExists(atPath: path) else { return GitStatus(error: "Folder not found") @@ -191,7 +304,11 @@ enum Git { let worktree = FileManager.default.temporaryDirectory .appendingPathComponent("magic-commit-\(UUID().uuidString)").path - let add = await Shell.run(["git", "worktree", "add", "--detach", worktree, chain[0].parents[0]], in: path) + // Locked with our PID so a later run can tell a leftover (app crashed) from a batch in progress. + let add = await Shell.run( + ["git", "worktree", "add", "--detach", "--lock", "--reason", tempWorktreeLockReason, worktree, chain[0].parents[0]], + in: path + ) guard add.succeeded else { return fail("Couldn't create a temporary worktree.", add) } let result = await replay(chain, in: worktree, progress: progress, fail: fail) @@ -209,7 +326,8 @@ enum Git { if !update.succeeded { outcome = fail("The branch changed while rewriting; nothing was changed.", update) } } } - _ = await Shell.run(["git", "worktree", "remove", "--force", worktree], in: path) + // Twice --force: the worktree is locked. + _ = await Shell.run(["git", "worktree", "remove", "--force", "--force", worktree], in: path) return outcome } diff --git a/Sources/MagicCommit/MenuContentView.swift b/Sources/MagicCommit/MenuContentView.swift index 705d01e..8501e41 100644 --- a/Sources/MagicCommit/MenuContentView.swift +++ b/Sources/MagicCommit/MenuContentView.swift @@ -135,14 +135,16 @@ struct MenuContentView: View { if store.projects.isEmpty { return "Add a project to get started" } let n = store.attentionCount if n == 0 { return "All projects committed & pushed" } - return "\(n) project\(n == 1 ? "" : "s") need\(n == 1 ? "s" : "") attention" + let hasWorktrees = store.projects.contains { !store.linkedWorktrees(of: $0).isEmpty } + let noun = hasWorktrees ? "checkout" : "project" + return "\(n) \(noun)\(n == 1 ? "" : "s") need\(n == 1 ? "s" : "") attention" } @ViewBuilder private var content: some View { if store.projects.isEmpty { emptyState - } else if store.projects.count <= 6 { + } else if rowCount <= 6 { projectList } else { ScrollView { projectList } @@ -150,6 +152,11 @@ struct MenuContentView: View { } } + /// Number of rows shown (fold toggles are too small to count), to decide when the list should scroll. + private var rowCount: Int { + store.projects.reduce(0) { $0 + 1 + store.visibleWorktrees(of: $1).count } + } + private var emptyState: some View { VStack(spacing: 10) { ZStack { @@ -181,7 +188,7 @@ struct MenuContentView: View { private var projectList: some View { VStack(spacing: 2) { ForEach(store.projects) { project in - ProjectRow(project: project) + ProjectGroup(project: project) } } .padding(6) @@ -242,26 +249,81 @@ private struct PanelHeightSync: NSViewRepresentable { } } +// MARK: - Project group + +/// A repository's main checkout followed by its linked worktrees. Clean worktrees +/// are folded behind a toggle unless the project is expanded. +struct ProjectGroup: View { + @EnvironmentObject private var store: ProjectStore + let project: Project + + var body: some View { + let linked = store.linkedWorktrees(of: project) + let isExpanded = store.expanded.contains(project.id) + let shown = store.visibleWorktrees(of: project) + let hidden = linked.count - shown.count + + VStack(alignment: .leading, spacing: 2) { + CheckoutRow(project: project, checkout: store.mainCheckout(of: project)) + ForEach(shown) { worktree in + CheckoutRow(project: project, checkout: worktree) + .padding(.leading, 22) + .overlay(alignment: .leading) { treeLine } + } + if hidden > 0 || (isExpanded && linked.contains { !store.isProminent($0) }) { + Button { + withAnimation(.snappy(duration: 0.25)) { store.toggleExpanded(project) } + } label: { + HStack(spacing: 4) { + Image(systemName: isExpanded ? "chevron.up" : "chevron.down") + .font(.system(size: 8, weight: .bold)) + Text(isExpanded + ? "Hide clean worktrees" + : "\(hidden) clean worktree\(hidden == 1 ? "" : "s")") + } + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(.secondary) + .padding(.vertical, 3) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .padding(.leading, 70) + } + } + .animation(.snappy(duration: 0.25), value: linked) + } + + private var treeLine: some View { + Rectangle() + .fill(Color.primary.opacity(0.12)) + .frame(width: 1.5) + .padding(.leading, 23) + .padding(.vertical, 2) + } +} + // MARK: - Row -struct ProjectRow: View { +/// One checkout: the project's main working tree (titled with the project name) +/// or a linked worktree (titled with its branch). +struct CheckoutRow: View { @EnvironmentObject private var store: ProjectStore let project: Project + let checkout: Worktree @State private var hovering = false @State private var showOutput = false - private var status: GitStatus? { store.statuses[project.id] } - private var activity: Activity? { store.activity[project.id] } - private var log: ActionLog? { store.logs[project.id] } + private var status: GitStatus? { store.statuses[checkout.path] } + private var activity: Activity? { store.activity[checkout.path] } + private var log: ActionLog? { store.logs[checkout.path] } + private var isWorktree: Bool { !checkout.isMain } var body: some View { VStack(alignment: .leading, spacing: 8) { HStack(spacing: 10) { statusIcon VStack(alignment: .leading, spacing: 4) { - Text(project.name) - .font(.system(size: 13, weight: .semibold)) - .lineLimit(1) + title detailLine } Spacer(minLength: 6) @@ -271,7 +333,7 @@ struct ProjectRow: View { if let log { logView(log) } } .padding(.horizontal, 8) - .padding(.vertical, 8) + .padding(.vertical, isWorktree ? 6 : 8) .background( RoundedRectangle(cornerRadius: 9) .fill(Color.primary.opacity(hovering ? 0.06 : 0)) @@ -285,34 +347,68 @@ struct ProjectRow: View { .contextMenu { menuItems } } + @ViewBuilder + private var title: some View { + HStack(spacing: 4) { + if isWorktree { + Image(systemName: "arrow.triangle.branch") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.secondary) + Text(checkout.label) + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + .truncationMode(.middle) + } else { + Text(project.name) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + } + if checkout.isLocked { + Image(systemName: "lock.fill") + .font(.system(size: 9)) + .foregroundStyle(.secondary) + .help(checkout.lockReason.flatMap { $0.isEmpty ? nil : "Locked: \($0)" } ?? "Locked worktree") + } + } + .help(checkout.path) + } + // MARK: Status icon private var statusIcon: some View { let (symbol, tint): (String, Color) = { + if checkout.isBare { return ("shippingbox", .secondary) } guard let status else { return ("circle.dotted", .secondary) } if status.error != nil { return ("exclamationmark.triangle.fill", .red) } if status.hasChanges { return ("pencil", .orange) } if status.canPush { return ("arrow.up", .blue) } return ("checkmark", .green) }() + let size: CGFloat = isWorktree ? 24 : 30 return ZStack { Circle().fill(tint.opacity(0.15)) if activity != nil { - ProgressView().controlSize(.small).scaleEffect(0.8) + ProgressView().controlSize(.small).scaleEffect(isWorktree ? 0.65 : 0.8) } else { Image(systemName: symbol) - .font(.system(size: 12, weight: .bold)) + .font(.system(size: isWorktree ? 10 : 12, weight: .bold)) .foregroundStyle(tint) } } - .frame(width: 30, height: 30) + .frame(width: size, height: size) + .frame(width: 30) } // MARK: Details @ViewBuilder private var detailLine: some View { - if let activity { + if checkout.isBare { + let n = store.linkedWorktrees(of: project).count + Text("Bare repository · \(n) worktree\(n == 1 ? "" : "s")") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } else if let activity { Text(activity.label) .font(.system(size: 11)) .foregroundStyle(.secondary) @@ -324,8 +420,14 @@ struct ProjectRow: View { .lineLimit(1) } else { HStack(spacing: 4) { - Chip(text: status.branch ?? "detached", systemImage: "arrow.triangle.branch", truncates: true) - .help(status.branch ?? "Detached HEAD") + if isWorktree { + // The branch is the title; show where the worktree lives instead. + Chip(text: checkout.name, systemImage: "folder", truncates: true) + .help(checkout.path) + } else { + Chip(text: status.branch ?? "detached", systemImage: "arrow.triangle.branch", truncates: true) + .help(status.branch ?? "Detached HEAD") + } if status.changes > 0 { Chip(text: "\(status.changes)", systemImage: "pencil", tint: .orange) .help("\(status.changes) changed file\(status.changes == 1 ? "" : "s")") @@ -354,7 +456,7 @@ struct ProjectRow: View { // MARK: Actions private var hasActions: Bool { - guard activity == nil, let status, status.error == nil else { return false } + guard !checkout.isBare, activity == nil, let status, status.error == nil else { return false } return status.hasChanges || status.canPush || status.wipCount > 0 } @@ -364,7 +466,7 @@ struct ProjectRow: View { HStack(spacing: 6) { if status.hasChanges { Button { - store.commitWIP(project) + store.commitWIP(checkout, in: project) } label: { Label("WIP", systemImage: "bolt.fill") } @@ -372,7 +474,7 @@ struct ProjectRow: View { .help("Quick commit with a \"WIP\" message (rename later with Batch oco)") Button { - store.commit(project) + store.commit(checkout, in: project) } label: { Label("Commit", systemImage: "sparkles") } @@ -381,7 +483,7 @@ struct ProjectRow: View { } if status.wipCount > 0 { Button { - store.batchOco(project) + store.batchOco(checkout, in: project) } label: { Label("Batch oco · \(status.wipCount)", systemImage: "wand.and.stars") } @@ -390,7 +492,7 @@ struct ProjectRow: View { } if status.canPush { Button { - store.push(project) + store.push(checkout, in: project) } label: { Label("Push", systemImage: "arrow.up") } @@ -420,11 +522,18 @@ struct ProjectRow: View { @ViewBuilder private var menuItems: some View { - Button("Open in Finder") { NSWorkspace.shared.open(project.url) } - Button("Open in Terminal") { openInTerminal() } + Button("Open in Finder") { NSWorkspace.shared.open(checkout.url) } + if !checkout.isBare { + Button("Open in Terminal") { openInTerminal() } + } Button("Refresh") { Task { await store.refresh(project) } } Divider() - Button("Remove Project", role: .destructive) { store.remove(project) } + if isWorktree { + Button("Remove Worktree…", role: .destructive) { store.removeWorktree(checkout, in: project) } + .disabled(!store.canRemove(checkout)) + } else { + Button("Remove Project", role: .destructive) { store.remove(project) } + } } // MARK: Log @@ -444,7 +553,7 @@ struct ProjectRow: View { .buttonStyle(.link) } Button { - store.dismissLog(project) + store.dismissLog(checkout) showOutput = false } label: { Image(systemName: "xmark").font(.system(size: 9, weight: .bold)) @@ -475,7 +584,7 @@ struct ProjectRow: View { private func openInTerminal() { guard let terminal = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") else { return } - NSWorkspace.shared.open([project.url], withApplicationAt: terminal, configuration: NSWorkspace.OpenConfiguration()) + NSWorkspace.shared.open([checkout.url], withApplicationAt: terminal, configuration: NSWorkspace.OpenConfiguration()) } } diff --git a/Sources/MagicCommit/ProjectStore.swift b/Sources/MagicCommit/ProjectStore.swift index 33b3779..5bc73e0 100644 --- a/Sources/MagicCommit/ProjectStore.swift +++ b/Sources/MagicCommit/ProjectStore.swift @@ -10,7 +10,7 @@ struct Project: Identifiable, Codable, Hashable { } enum Activity: Equatable { - case committing, committingWIP, pushing + case committing, committingWIP, pushing, removing case batch(current: Int, total: Int) var label: String { @@ -18,6 +18,7 @@ enum Activity: Equatable { case .committing: return "Writing commit message…" case .committingWIP: return "Committing WIP…" case .pushing: return "Pushing…" + case .removing: return "Removing worktree…" case let .batch(current, total): return current == 0 ? "Preparing batch oco…" : "oco is renaming WIP \(current) of \(total)…" } @@ -30,20 +31,41 @@ struct ActionLog: Equatable { var succeeded: Bool } +/// Whether two paths point at the same folder (git may spell them through symlinks, e.g. /private/var). +func samePath(_ a: String, _ b: String) -> Bool { + a == b || URL(fileURLWithPath: a).resolvingSymlinksInPath().path == URL(fileURLWithPath: b).resolvingSymlinksInPath().path +} + +/// A project's worktrees and their statuses, gathered off the main actor. +private struct Snapshot: Sendable { + /// The repository's main worktree as git reports it (nil when it couldn't be listed). + var mainPath: String? + var worktrees: [Worktree] + var statuses: [String: GitStatus] +} + +/// A stored project is a repository (its main working tree, or a bare repository). +/// Its linked worktrees are discovered on every refresh and never stored, so they +/// appear and disappear on their own. Status, activity and logs are keyed by checkout path. @MainActor final class ProjectStore: ObservableObject { @Published private(set) var projects: [Project] = [] - @Published private(set) var statuses: [UUID: GitStatus] = [:] - @Published private(set) var activity: [UUID: Activity] = [:] - @Published private(set) var logs: [UUID: ActionLog] = [:] + /// Every checkout of each project, the main one first. + @Published private(set) var worktrees: [UUID: [Worktree]] = [:] + @Published private(set) var statuses: [String: GitStatus] = [:] + @Published private(set) var activity: [String: Activity] = [:] + @Published private(set) var logs: [String: ActionLog] = [:] + /// Projects whose clean worktrees are shown. + @Published private(set) var expanded: Set = [] @Published private(set) var isRefreshing = false @Published private(set) var lastRefresh: Date? private let defaultsKey = "projects" private var refreshLoop: Task? + /// Checkouts (main working trees and linked worktrees) with something to commit or push. var attentionCount: Int { - projects.filter { statuses[$0.id]?.needsAttention == true }.count + projects.flatMap(checkouts).filter { statuses[$0.path]?.needsAttention == true }.count } init() { @@ -61,6 +83,37 @@ final class ProjectStore: ObservableObject { } } + // MARK: Checkouts + + func checkouts(of project: Project) -> [Worktree] { + worktrees[project.id] ?? [Worktree(path: project.path, isMain: true)] + } + + func mainCheckout(of project: Project) -> Worktree { + checkouts(of: project).first(where: \.isMain) ?? Worktree(path: project.path, isMain: true) + } + + func linkedWorktrees(of project: Project) -> [Worktree] { + checkouts(of: project).filter { !$0.isMain } + } + + /// Worktrees shown even when the project is folded: anything to do, running or just done. + func isProminent(_ worktree: Worktree) -> Bool { + if activity[worktree.path] != nil || logs[worktree.path] != nil { return true } + guard let status = statuses[worktree.path] else { return false } + return status.needsAttention || status.wipCount > 0 || status.error != nil + } + + /// Linked worktrees shown as rows: all when expanded, only prominent ones otherwise. + func visibleWorktrees(of project: Project) -> [Worktree] { + let linked = linkedWorktrees(of: project) + return expanded.contains(project.id) ? linked : linked.filter(isProminent) + } + + func toggleExpanded(_ project: Project) { + if expanded.contains(project.id) { expanded.remove(project.id) } else { expanded.insert(project.id) } + } + // MARK: Persistence private func load() { @@ -75,6 +128,10 @@ final class ProjectStore: ObservableObject { } } + private func sortProjects() { + projects.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } + } + // MARK: Projects func promptAddProjects() { @@ -83,24 +140,32 @@ final class ProjectStore: ObservableObject { panel.canChooseFiles = false panel.allowsMultipleSelection = true panel.prompt = "Add" - panel.message = "Choose one or more git repositories" + panel.message = "Choose one or more git repositories or worktrees" NSApp.activate(ignoringOtherApps: true) guard panel.runModal() == .OK else { return } let urls = panel.urls Task { await addProjects(urls) } } + /// Adds the repository of each folder. Picking a linked worktree adds its main + /// repository instead (the worktree then shows under it). func addProjects(_ urls: [URL]) async { var rejected: [String] = [] for url in urls { - guard let top = await Git.toplevel(of: url.path) else { + guard let main = await Git.mainWorktreePath(of: url.path) else { rejected.append(url.lastPathComponent) continue } - guard !projects.contains(where: { $0.path == top }) else { continue } - let project = Project(path: top) + let isWorktree = !samePath(main, url.path) + if let existing = projects.first(where: { samePath($0.path, main) }) { + if isWorktree { expanded.insert(existing.id) } + await refresh(existing) + continue + } + let project = Project(path: main) projects.append(project) - projects.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } + if isWorktree { expanded.insert(project.id) } + sortProjects() save() await refresh(project) } @@ -114,9 +179,13 @@ final class ProjectStore: ObservableObject { } func remove(_ project: Project) { + for checkout in checkouts(of: project) { + statuses[checkout.path] = nil + logs[checkout.path] = nil + } projects.removeAll { $0.id == project.id } - statuses[project.id] = nil - logs[project.id] = nil + worktrees[project.id] = nil + expanded.remove(project.id) save() } @@ -127,37 +196,109 @@ final class ProjectStore: ObservableObject { isRefreshing = true defer { isRefreshing = false } let current = projects - let results = await withTaskGroup(of: (UUID, GitStatus).self) { group in + let results = await withTaskGroup(of: (Project, Snapshot).self) { group in for p in current { - group.addTask { (p.id, await Git.status(at: p.path)) } + group.addTask { (p, await Self.snapshot(of: p)) } } - var out: [UUID: GitStatus] = [:] - for await (id, status) in group { out[id] = status } + var out: [(Project, Snapshot)] = [] + for await result in group { out.append(result) } return out } - for (id, status) in results where activity[id] == nil { - statuses[id] = status - } + for (project, snapshot) in results { apply(snapshot, to: project) } + dropStaleState() lastRefresh = Date() } + /// Refreshes a project and all its worktrees. func refresh(_ project: Project) async { - statuses[project.id] = await Git.status(at: project.path) + // The path may have changed (migration) since `project` was captured. + let project = projects.first(where: { $0.id == project.id }) ?? project + apply(await Self.snapshot(of: project), to: project) + dropStaleState() + } + + private nonisolated static func snapshot(of project: Project) async -> Snapshot { + let mainOnly = [Worktree(path: project.path, isMain: true)] + guard FileManager.default.fileExists(atPath: project.path) else { + return Snapshot(mainPath: nil, worktrees: mainOnly, statuses: [project.path: GitStatus(error: "Folder not found")]) + } + let listed = await Git.worktrees(at: project.path) + var list = listed ?? mainOnly + if listed != nil { await Git.removeStaleTempWorktrees(list, repo: project.path) } + let mainPath = listed?.first?.path + + list.removeAll { w in + !w.isMain && (Git.isTempWorktree(w) || w.isPrunable || !FileManager.default.fileExists(atPath: w.path)) + } + // Keep the stored spelling of the main path so its state stays keyed the same. + if let i = list.firstIndex(where: \.isMain), samePath(list[i].path, project.path) { + list[i].path = project.path + } + let main = list.filter(\.isMain) + let linked = list.filter { !$0.isMain } + .sorted { $0.label.localizedStandardCompare($1.label) == .orderedAscending } + list = main + linked + + let checked = list.filter { !$0.isBare } + let statuses = await withTaskGroup(of: (String, GitStatus).self) { group in + for w in checked { + group.addTask { (w.path, await Git.status(at: w.path)) } + } + var out: [String: GitStatus] = [:] + for await (path, status) in group { out[path] = status } + return out + } + return Snapshot(mainPath: mainPath, worktrees: list, statuses: statuses) + } + + private func apply(_ snapshot: Snapshot, to project: Project) { + guard let index = projects.firstIndex(where: { $0.id == project.id }) else { return } + + // A project saved as a linked worktree (or added before worktree support) + // becomes its main repository. + if let main = snapshot.mainPath, !samePath(main, projects[index].path) { + if projects.contains(where: { $0.id != project.id && samePath($0.path, main) }) { + remove(projects[index]) + return + } + projects[index].path = main + expanded.insert(project.id) + sortProjects() + save() + } + + worktrees[project.id] = snapshot.worktrees + for (path, status) in snapshot.statuses where activity[path] == nil { + statuses[path] = status + } + } + + /// Forgets statuses and logs of worktrees that no longer exist. + private func dropStaleState() { + let live = Set(projects.flatMap(checkouts).map(\.path)) + for path in statuses.keys where !live.contains(path) && activity[path] == nil { + statuses[path] = nil + } + for path in logs.keys where !live.contains(path) && activity[path] == nil { + logs[path] = nil + } } // MARK: Actions - /// Runs `work`, showing `activity` meanwhile and a result banner afterwards. + /// Runs `work` on a checkout, showing `activity` meanwhile and a result banner afterwards. private func perform( - _ project: Project, + _ checkout: Worktree, + in project: Project, _ activity: Activity, failureTitle: String, work: @escaping () async -> ShellResult, successTitle: @escaping (ShellResult) async -> String ) { - guard self.activity[project.id] == nil else { return } - self.activity[project.id] = activity - logs[project.id] = nil + let key = checkout.path + guard self.activity[key] == nil else { return } + self.activity[key] = activity + logs[key] = nil Task { let result = await work() var output = result.combinedOutput @@ -168,37 +309,37 @@ final class ProjectStore: ObservableObject { title = failureTitle if output.isEmpty { output = "Exited with status \(result.status)" } } - logs[project.id] = ActionLog(title: title, output: output, succeeded: result.succeeded) - self.activity[project.id] = nil + logs[key] = ActionLog(title: title, output: output, succeeded: result.succeeded) + self.activity[key] = nil await refresh(project) } } - func commit(_ project: Project) { - perform(project, .committing, failureTitle: "Commit failed") { - await Git.commit(at: project.path) + func commit(_ checkout: Worktree, in project: Project) { + perform(checkout, in: project, .committing, failureTitle: "Commit failed") { + await Git.commit(at: checkout.path) } successTitle: { _ in - await Git.lastCommitSubject(at: project.path).map { "Committed: \($0)" } ?? "Committed" + await Git.lastCommitSubject(at: checkout.path).map { "Committed: \($0)" } ?? "Committed" } } - func commitWIP(_ project: Project) { - perform(project, .committingWIP, failureTitle: "WIP commit failed") { - await Git.commitWIP(at: project.path) + func commitWIP(_ checkout: Worktree, in project: Project) { + perform(checkout, in: project, .committingWIP, failureTitle: "WIP commit failed") { + await Git.commitWIP(at: checkout.path) } successTitle: { _ in "Committed WIP" } } - func batchOco(_ project: Project) { - guard let status = statuses[project.id], let branch = status.branch else { return } - let id = project.id - perform(project, .batch(current: 0, total: status.wipCount), failureTitle: "Batch oco failed") { - await Git.batchOco(at: project.path, branch: branch) { current, total in + func batchOco(_ checkout: Worktree, in project: Project) { + guard let status = statuses[checkout.path], let branch = status.branch else { return } + let key = checkout.path + perform(checkout, in: project, .batch(current: 0, total: status.wipCount), failureTitle: "Batch oco failed") { + await Git.batchOco(at: checkout.path, branch: branch) { current, total in Task { @MainActor in // Ignore late updates arriving after the batch finished. - guard case .batch = self.activity[id] else { return } - self.activity[id] = .batch(current: current, total: total) + guard case .batch = self.activity[key] else { return } + self.activity[key] = .batch(current: current, total: total) } } } successTitle: { result in @@ -207,8 +348,8 @@ final class ProjectStore: ObservableObject { } } - func push(_ project: Project) { - guard let status = statuses[project.id] else { return } + func push(_ checkout: Worktree, in project: Project) { + guard let status = statuses[checkout.path] else { return } if status.wipCount > 0 { let alert = NSAlert() alert.messageText = "Push \(status.wipCount) WIP commit\(status.wipCount == 1 ? "" : "s")?" @@ -218,19 +359,54 @@ final class ProjectStore: ObservableObject { alert.addButton(withTitle: "Cancel") NSApp.activate(ignoringOtherApps: true) switch alert.runModal() { - case .alertFirstButtonReturn: batchOco(project); return + case .alertFirstButtonReturn: batchOco(checkout, in: project); return case .alertSecondButtonReturn: break default: return } } - perform(project, .pushing, failureTitle: "Push failed") { - await Git.push(at: project.path, status: status) + perform(checkout, in: project, .pushing, failureTitle: "Push failed") { + await Git.push(at: checkout.path, status: status) } successTitle: { _ in "Pushed" } } - func dismissLog(_ project: Project) { - logs[project.id] = nil + /// Whether a linked worktree can be removed from the panel: clean and unlocked. + func canRemove(_ checkout: Worktree) -> Bool { + guard !checkout.isMain, !checkout.isLocked, activity[checkout.path] == nil, + let status = statuses[checkout.path], status.error == nil else { return false } + return !status.hasChanges + } + + /// Deletes a clean linked worktree's folder after confirmation. Its branch is kept. + func removeWorktree(_ checkout: Worktree, in project: Project) { + guard canRemove(checkout) else { return } + let alert = NSAlert() + alert.messageText = "Remove worktree \(checkout.name)?" + alert.informativeText = "The folder \(checkout.path) is deleted. " + + (checkout.branch.map { "The branch \($0) and its commits are kept." } ?? "Its commit stays reachable from the reflog.") + alert.addButton(withTitle: "Remove") + alert.addButton(withTitle: "Cancel") + alert.buttons[0].hasDestructiveAction = true + NSApp.activate(ignoringOtherApps: true) + guard alert.runModal() == .alertFirstButtonReturn else { return } + + let key = checkout.path + activity[key] = .removing + logs[key] = nil + Task { + let result = await Git.removeWorktree(checkout, repo: project.path) + activity[key] = nil + if result.succeeded { + logs[mainCheckout(of: project).path] = ActionLog(title: "Removed worktree \(checkout.label)", output: "", succeeded: true) + } else { + logs[key] = ActionLog(title: "Couldn't remove worktree", output: result.combinedOutput, succeeded: false) + } + await refresh(project) + } + } + + func dismissLog(_ checkout: Worktree) { + logs[checkout.path] = nil } } diff --git a/Tests/MagicCommitTests/BatchOcoTests.swift b/Tests/MagicCommitTests/BatchOcoTests.swift index 3a598da..0360a44 100644 --- a/Tests/MagicCommitTests/BatchOcoTests.swift +++ b/Tests/MagicCommitTests/BatchOcoTests.swift @@ -8,21 +8,10 @@ final class BatchOcoTests: XCTestCase { private var repo: String { root.appendingPathComponent("repo").path } override func setUpWithError() throws { + FakeOco.install() root = FileManager.default.temporaryDirectory .appendingPathComponent("magic-commit-tests-\(UUID().uuidString)") - let bin = root.appendingPathComponent("bin") - try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) try FileManager.default.createDirectory(atPath: repo, withIntermediateDirectories: true) - - let fakeOco = bin.appendingPathComponent("oco") - try """ - #!/bin/sh - git commit -q -m "feat: generated message" - """.write(to: fakeOco, atomically: true, encoding: .utf8) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: fakeOco.path) - - // Read once by `Shell.environment`, so it must be set before the first command runs. - setenv("MAGIC_COMMIT_EXTRA_PATH", bin.path, 1) } override func tearDownWithError() throws { @@ -71,4 +60,32 @@ final class BatchOcoTests: XCTestCase { let worktrees = try await git("worktree", "list") XCTAssertEqual(worktrees.split(separator: "\n").count, 1, "temporary worktree should be removed") } + + func testRenamesWIPCommitsInLinkedWorktree() async throws { + try await git("init", "-q", "-b", "main") + try await git("config", "user.name", "Test") + try await git("config", "user.email", "test@example.com") + try write("a.txt", "a") + try await git("add", "-A") + try await git("commit", "-q", "-m", "Initial commit") + + let linked = root.appendingPathComponent("repo-feature").path + try await git("worktree", "add", "-q", "-b", "feature", linked) + try "b".write(toFile: (linked as NSString).appendingPathComponent("b.txt"), atomically: true, encoding: .utf8) + let commitWIP = await Git.commitWIP(at: linked) + XCTAssertTrue(commitWIP.succeeded, commitWIP.combinedOutput) + let mainHead = try await git("rev-parse", "main") + + let result = await Git.batchOco(at: linked, branch: "feature") { _, _ in } + XCTAssertTrue(result.succeeded, result.combinedOutput) + + let subjects = try await git("log", "--format=%s", "feature") + XCTAssertEqual(subjects.split(separator: "\n"), ["feat: generated message", "Initial commit"]) + let mainAfter = try await git("rev-parse", "main") + XCTAssertEqual(mainHead, mainAfter, "main must be untouched") + let status = await Git.status(at: linked) + XCTAssertFalse(status.hasChanges, "linked worktree's files and index stay in sync") + let worktrees = try await git("worktree", "list") + XCTAssertEqual(worktrees.split(separator: "\n").count, 2, "temporary worktree should be removed") + } } diff --git a/Tests/MagicCommitTests/FakeOco.swift b/Tests/MagicCommitTests/FakeOco.swift new file mode 100644 index 0000000..f33f527 --- /dev/null +++ b/Tests/MagicCommitTests/FakeOco.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Puts a fake `oco` (commits the staged changes with a fixed message) first on +/// the PATH of every command the tests run. +/// +/// `Shell.environment` reads MAGIC_COMMIT_EXTRA_PATH only once, when the first +/// command runs, so every test class that runs commands calls `install()` in its +/// setUp: whichever runs first, the real `oco` is never reached. +enum FakeOco { + static func install() { _ = bin } + + private static let bin: URL = { + let bin = FileManager.default.temporaryDirectory + .appendingPathComponent("magic-commit-tests-bin-\(getpid())") + try? FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) + let oco = bin.appendingPathComponent("oco") + try? """ + #!/bin/sh + git commit -q -m "feat: generated message" + """.write(to: oco, atomically: true, encoding: .utf8) + try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: oco.path) + setenv("MAGIC_COMMIT_EXTRA_PATH", bin.path, 1) + precondition(FileManager.default.isExecutableFile(atPath: oco.path), "fake oco not installed") + return bin + }() +} diff --git a/Tests/MagicCommitTests/WorktreeTests.swift b/Tests/MagicCommitTests/WorktreeTests.swift new file mode 100644 index 0000000..086875b --- /dev/null +++ b/Tests/MagicCommitTests/WorktreeTests.swift @@ -0,0 +1,167 @@ +import XCTest +@testable import MagicCommit + +final class WorktreeParsingTests: XCTestCase { + func testMainAndLinkedWorktrees() { + let list = Git.parseWorktreeList(""" + worktree /code/app + HEAD 1111111111111111111111111111111111111111 + branch refs/heads/main + + worktree /code/app-feature + HEAD 2222222222222222222222222222222222222222 + branch refs/heads/feature/login + + worktree /code/app-review + HEAD 3333333333333333333333333333333333333333 + detached + + """) + XCTAssertEqual(list.map(\.path), ["/code/app", "/code/app-feature", "/code/app-review"]) + XCTAssertEqual(list.map(\.isMain), [true, false, false]) + XCTAssertEqual(list[1].branch, "feature/login") + XCTAssertEqual(list[1].label, "feature/login") + XCTAssertNil(list[2].branch) + XCTAssertTrue(list[2].isDetached) + XCTAssertEqual(list[2].label, "detached @ 3333333") + } + + func testBareLockedAndPrunable() { + let list = Git.parseWorktreeList(""" + worktree /code/app.git + bare + + worktree /Volumes/USB/app + HEAD 1111111111111111111111111111111111111111 + branch refs/heads/main + locked on a removable drive + + worktree /code/gone + HEAD 2222222222222222222222222222222222222222 + branch refs/heads/old + locked + prunable gitdir file points to non-existent location + """) + XCTAssertEqual(list.count, 3) + XCTAssertTrue(list[0].isBare) + XCTAssertTrue(list[0].isMain) + XCTAssertNil(list[0].branch) + XCTAssertEqual(list[1].lockReason, "on a removable drive") + XCTAssertFalse(list[1].isPrunable) + XCTAssertEqual(list[2].lockReason, "") + XCTAssertTrue(list[2].isLocked) + XCTAssertTrue(list[2].isPrunable) + } + + func testTempWorktreeDetection() { + let tmp = URL(fileURLWithPath: "/tmp/x") + let temp = Worktree(path: "/tmp/x/magic-commit-ABC", isDetached: true, lockReason: "magic-commit pid 42") + XCTAssertTrue(Git.isTempWorktree(temp, tempDirectory: tmp)) + XCTAssertEqual(Git.tempWorktreePID(temp), 42) + XCTAssertFalse(Git.isTempWorktree(Worktree(path: "/code/magic-commit-site"), tempDirectory: tmp)) + XCTAssertFalse(Git.isTempWorktree(Worktree(path: "/tmp/x/magic-commit-ABC", isMain: true), tempDirectory: tmp)) + XCTAssertNil(Git.tempWorktreePID(Worktree(path: "/tmp/x/magic-commit-ABC", lockReason: "someone else"))) + } +} + +/// Worktree discovery and actions against a throwaway repository. +final class WorktreeIntegrationTests: XCTestCase { + private var root: URL! + private var repo: String { root.appendingPathComponent("repo").path } + private var linked: String { root.appendingPathComponent("repo-feature").path } + + override func setUp() async throws { + FakeOco.install() + root = FileManager.default.temporaryDirectory + .appendingPathComponent("magic-commit-tests-\(UUID().uuidString)") + try FileManager.default.createDirectory(atPath: repo, withIntermediateDirectories: true) + try await git(repo, "init", "-q", "-b", "main") + try await git(repo, "config", "user.name", "Test") + try await git(repo, "config", "user.email", "test@example.com") + try await git(repo, "config", "commit.gpgsign", "false") + try await git(repo, "commit", "-q", "--allow-empty", "-m", "Initial commit") + try await git(repo, "worktree", "add", "-q", "-b", "feature", linked) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: root) + } + + @discardableResult + private func git(_ dir: String, _ args: String...) async throws -> String { + let env = [ + "GIT_AUTHOR_NAME": "Test", "GIT_AUTHOR_EMAIL": "test@example.com", + "GIT_COMMITTER_NAME": "Test", "GIT_COMMITTER_EMAIL": "test@example.com", + ] + let r = await Shell.run(["git"] + args, in: dir, extraEnvironment: env) + guard r.succeeded else { throw NSError(domain: "git", code: Int(r.status), userInfo: [NSLocalizedDescriptionKey: r.combinedOutput]) } + return r.stdout.trimmingCharacters(in: .whitespacesAndNewlines) + } + + func testMainWorktreeResolvesFromLinkedWorktreeAndSubfolder() async throws { + let sub = (linked as NSString).appendingPathComponent("src") + try FileManager.default.createDirectory(atPath: sub, withIntermediateDirectories: true) + for path in [repo, linked, sub] { + let main = await Git.mainWorktreePath(of: path) + XCTAssertTrue(main.map { samePath($0, repo) } ?? false, "\(path) → \(main ?? "nil")") + } + let notRepo = await Git.mainWorktreePath(of: root.path) + XCTAssertNil(notRepo) + } + + func testListsWorktreesAndStatusPerCheckout() async throws { + let listed = await Git.worktrees(at: repo) + let list = try XCTUnwrap(listed) + XCTAssertEqual(list.count, 2) + XCTAssertEqual(list[1].branch, "feature") + + try "x".write(toFile: (linked as NSString).appendingPathComponent("x.txt"), atomically: true, encoding: .utf8) + let mainStatus = await Git.status(at: repo) + let linkedStatus = await Git.status(at: linked) + XCTAssertEqual(mainStatus.branch, "main") + XCTAssertFalse(mainStatus.hasChanges) + XCTAssertEqual(linkedStatus.branch, "feature") + XCTAssertEqual(linkedStatus.changes, 1) + } + + func testStaleTempWorktreeIsRemovedButLiveOneKept() async throws { + let tmp = FileManager.default.temporaryDirectory + let stale = tmp.appendingPathComponent("magic-commit-\(UUID().uuidString)").path + let live = tmp.appendingPathComponent("magic-commit-\(UUID().uuidString)").path + defer { + try? FileManager.default.removeItem(atPath: stale) + try? FileManager.default.removeItem(atPath: live) + } + // PID 99999999 can't exist; our own PID is alive. + try await git(repo, "worktree", "add", "-q", "--detach", "--lock", "--reason", "magic-commit pid 99999999", stale, "HEAD") + try await git(repo, "worktree", "add", "-q", "--detach", "--lock", "--reason", Git.tempWorktreeLockReason, live, "HEAD") + + let listedBefore = await Git.worktrees(at: repo) + let before = try XCTUnwrap(listedBefore) + XCTAssertEqual(before.filter { Git.isTempWorktree($0) }.count, 2) + await Git.removeStaleTempWorktrees(before, repo: repo) + + let listedAfter = await Git.worktrees(at: repo) + let after = try XCTUnwrap(listedAfter) + let temps = after.filter { Git.isTempWorktree($0) } + XCTAssertEqual(temps.count, 1) + XCTAssertTrue(samePath(temps[0].path, live)) + XCTAssertFalse(FileManager.default.fileExists(atPath: stale)) + try await git(repo, "worktree", "remove", "--force", "--force", live) + } + + func testRemoveWorktreeKeepsBranchAndRefusesDirty() async throws { + let listed = await Git.worktrees(at: repo) + let worktree = try XCTUnwrap(listed?.last) + try "x".write(toFile: (linked as NSString).appendingPathComponent("x.txt"), atomically: true, encoding: .utf8) + let refused = await Git.removeWorktree(worktree, repo: repo) + XCTAssertFalse(refused.succeeded) + + try FileManager.default.removeItem(atPath: (linked as NSString).appendingPathComponent("x.txt")) + let removed = await Git.removeWorktree(worktree, repo: repo) + XCTAssertTrue(removed.succeeded, removed.combinedOutput) + XCTAssertFalse(FileManager.default.fileExists(atPath: linked)) + let branch = try await git(repo, "branch", "--list", "feature") + XCTAssertFalse(branch.isEmpty) + } +} diff --git a/scripts/screenshot-demo.sh b/scripts/screenshot-demo.sh index d7e1269..04b383e 100755 --- a/scripts/screenshot-demo.sh +++ b/scripts/screenshot-demo.sh @@ -6,13 +6,15 @@ # ./scripts/screenshot-demo.sh setup # build demo repos, back up and swap the project list # ./scripts/screenshot-demo.sh restore # put your project list back # ./scripts/screenshot-demo.sh clean # restore, then delete the demo repos +# +# APP=build/Magic\ Commit.app ./scripts/screenshot-demo.sh setup runs a local build instead. set -euo pipefail DEMO_DIR="${DEMO_DIR:-$HOME/MagicCommitDemo}" REMOTES="$DEMO_DIR/.remotes" BACKUP="$DEMO_DIR/.projects-backup.plist" DOMAIN="local.magic-commit" -APP="/Applications/Magic Commit.app" +APP="${APP:-/Applications/Magic Commit.app}" say() { printf '\033[1;35m›\033[0m %s\n' "$*"; } @@ -112,6 +114,28 @@ build_repos() { base_project docs-site "Docs" } +# Linked worktrees, kept out of the project list: they show under their repository. +build_worktrees() { + local wt="$DEMO_DIR/.worktrees" + [[ -d "$wt" ]] && return + mkdir -p "$wt" + + # Uncommitted changes in a feature worktree: shown with Commit and WIP. + git -C "$DEMO_DIR/pocket-api" worktree add -q -b feature/billing "$wt/pocket-api-billing" main + printf '%s\n' "export const plans = ['free', 'pro'];" > "$wt/pocket-api-billing/src/plans.ts" + printf '%s\n' "export const app = \"Pocket API\"; export const billing = true;" > "$wt/pocket-api-billing/src/index.ts" + + # A real commit waiting to be pushed: Push. + git -C "$DEMO_DIR/pocket-api" worktree add -q -b fix/rate-limit "$wt/pocket-api-hotfix" main + printf '%s\n' "export const limit = 100;" > "$wt/pocket-api-hotfix/src/limit.ts" + git -C "$wt/pocket-api-hotfix" add -A + git -C "$wt/pocket-api-hotfix" commit -q -m "Lower the rate limit to 100 requests per minute" + + # Clean worktrees: folded behind the "clean worktrees" toggle. + git -C "$DEMO_DIR/pocket-api" worktree add -q --detach "$wt/pocket-api-review" main + git -C "$DEMO_DIR/docs-site" worktree add -q -b docs/getting-started "$wt/docs-site-guide" main +} + # --- project list swap ------------------------------------------------------ swap_projects() { @@ -159,6 +183,7 @@ case "${1:-}" in build_repos say "Created demo repos in $DEMO_DIR" fi + build_worktrees swap_projects launch_app say "Magic Commit now shows the demo projects. Run '$0 restore' when you're done." From 227c1c24426498d94c733782a25f64c84e50dbac Mon Sep 17 00:00:00 2001 From: dommangetnicolas Date: Sun, 15 Nov 2026 17:57:52 +0100 Subject: [PATCH 2/3] Add Claude Code as a commit message generator Ollama's free tier is gone, so oco is no longer free to run. A footer menu now picks the message generator: OpenCommit (oco, still the default) or the local Claude Code CLI. Claude mode sends the staged diff and recent commit subjects to `claude -p` (Haiku, no tools, no saved session) on stdin, cleans the reply and commits it, following the repository's commit style. Both Commit and Batch oco use the picked generator, and batch-oco takes --generator claude|oco. Shell.run gains stdin input; the model can be changed with the claudeModel user default. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + README.md | 33 ++++-- Sources/MagicCommit/CLI.swift | 12 +- Sources/MagicCommit/Git.swift | 26 ++-- Sources/MagicCommit/MenuContentView.swift | 29 ++++- Sources/MagicCommit/MessageGenerator.swift | 131 +++++++++++++++++++++ Sources/MagicCommit/ProjectStore.swift | 2 +- Sources/MagicCommit/Shell.swift | 17 ++- Tests/MagicCommitTests/BatchOcoTests.swift | 45 ++++++- Tests/MagicCommitTests/FakeOco.swift | 12 +- 10 files changed, 272 insertions(+), 37 deletions(-) create mode 100644 Sources/MagicCommit/MessageGenerator.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 01d0741..88f9f90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ and the project uses [Semantic Versioning](https://semver.org/). - Worktree support: linked worktrees of each project are discovered automatically and listed under it, each with its own status and Commit, WIP, Batch oco and Push buttons. Clean worktrees fold behind a toggle. - **Remove Worktree** in a worktree's menu, for clean worktrees (the branch is kept). +- Claude Code as a message generator: pick **Claude Code** or **OpenCommit** from the ✨ menu in the panel's footer. Claude mode runs your local `claude` CLI (Haiku by default, override with the `claudeModel` default) and follows your repository's commit style. +- `--generator claude|oco` option for the `batch-oco` command. ### Changed diff --git a/README.md b/README.md index be40fa6..fb597f7 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE) [![Website](https://img.shields.io/badge/website-magic--commit.nicolas--dmg.fr-6d4aff)](https://magic-commit.nicolas-dmg.fr/) -A macOS menu bar app that keeps an eye on your git projects and commits them with AI-written messages from [opencommit](https://github.com/di-sukharev/opencommit) (`oco`), in one click. +A macOS menu bar app that keeps an eye on your git projects and commits them with AI-written messages, in one click. Messages come from your local [Claude Code](https://claude.com/claude-code) CLI (`claude`) or from [opencommit](https://github.com/di-sukharev/opencommit) (`oco`): pick one from the ✨ menu at the bottom of the panel. Commit as often as you like with a quick `WIP`, then let Magic Commit turn every WIP commit into a real, descriptive message before you push. @@ -16,9 +16,9 @@ Commit as often as you like with a quick `WIP`, then let Magic Commit turn every Each project in the panel shows its branch, changed files, WIP commits and ahead/behind counts, plus the actions that make sense right now: -- **Commit**: stages everything (unless you've already staged something) and runs `oco --yes`. +- **Commit**: stages everything (unless you've already staged something) and commits with a generated message. - **WIP**: makes an instant commit with the message `WIP`, with no AI call. -- **Batch oco**: gives each unpushed WIP commit a real message generated by `oco` from that commit's own diff. Other commits keep their messages, empty WIP commits are dropped, and original author dates are kept. +- **Batch oco**: gives each unpushed WIP commit a real message generated from that commit's own diff. Other commits keep their messages, empty WIP commits are dropped, and original author dates are kept. - **Push**: runs `git push` (or `git push -u ` for a new branch). It warns you first if WIP commits are still in there. **Worktrees** are picked up automatically: every linked worktree of a project you've added shows under it, labelled with its branch, with the same buttons. Worktrees appear and disappear as you create and remove them, and clean ones fold behind a "clean worktrees" toggle. Adding a worktree's folder adds its repository instead. A clean worktree can be removed from its `…` menu; its branch is kept. @@ -28,14 +28,21 @@ The menu bar icon shows how many checkouts (projects and worktrees) have somethi ## Requirements - macOS 14 Sonoma or later -- [opencommit](https://github.com/di-sukharev/opencommit) installed and configured: +- One message generator: + - **Claude Code**: the [`claude` CLI](https://claude.com/claude-code), signed in once by running `claude` in a terminal. Magic Commit sends the staged diff and your recent commit subjects to `claude -p` (Haiku by default, with no tools enabled) and commits the reply, matching your repository's commit style. To use another model: - ```bash - npm install -g opencommit - oco config set OCO_API_KEY= - ``` + ```bash + defaults write io.github.dommangetnicolas.MagicCommit claudeModel sonnet + ``` - Magic Commit reads your `PATH` from your login shell, so `oco` installed through nvm, Homebrew or similar is found. + - **opencommit**: installed and configured: + + ```bash + npm install -g opencommit + oco config set OCO_API_KEY= + ``` + + Magic Commit reads your `PATH` from your login shell, so tools installed through nvm, Homebrew or similar are found. ## Installation @@ -73,18 +80,20 @@ Run `./scripts/build-app.sh --help` for all options. Batch oco can also run without the UI: ```bash -"/Applications/Magic Commit.app/Contents/MacOS/MagicCommit" batch-oco ~/path/to/repo +"/Applications/Magic Commit.app/Contents/MacOS/MagicCommit" batch-oco ~/path/to/repo --generator claude ``` +`--generator` is `claude` or `oco`; without it, the generator picked in the menu is used. + ## How Batch oco works Rewriting history is risky, so Batch oco is careful: 1. It takes the commits from the oldest unpushed WIP commit up to `HEAD` and replays them in a temporary `git worktree`. -2. Each WIP commit is re-staged there and `oco --yes` writes its message. Other commits are re-committed unchanged. +2. Each WIP commit is re-staged there and the generator (`claude` or `oco`) writes its message. Other commits are re-committed unchanged. 3. The branch is moved to the rewritten history only if the final content is identical and `HEAD` hasn't moved in the meantime. -Your working tree and staged changes are never touched. If `oco` fails partway through, nothing changes. Commits that are already pushed are never rewritten, and merge commits stop the operation. +Your working tree and staged changes are never touched. If the generator fails partway through, nothing changes. Commits that are already pushed are never rewritten, and merge commits stop the operation. ## Contributing diff --git a/Sources/MagicCommit/CLI.swift b/Sources/MagicCommit/CLI.swift index 447ac7b..e0b497d 100644 --- a/Sources/MagicCommit/CLI.swift +++ b/Sources/MagicCommit/CLI.swift @@ -1,12 +1,20 @@ import Foundation /// Headless commands, e.g. -/// "Magic Commit.app/Contents/MacOS/MagicCommit" batch-oco /path/to/repo +/// "Magic Commit.app/Contents/MacOS/MagicCommit" batch-oco /path/to/repo [--generator oco|claude] enum CLI { static func runIfRequested() { let args = CommandLine.arguments guard args.count >= 3, args[1] == "batch-oco" else { return } let path = (args[2] as NSString).expandingTildeInPath + var generator = MessageGenerator.current + if let i = args.firstIndex(of: "--generator") { + guard i + 1 < args.count, let picked = MessageGenerator(rawValue: args[i + 1]) else { + FileHandle.standardError.write(Data("--generator must be one of: \(MessageGenerator.allCases.map(\.rawValue).joined(separator: ", "))\n".utf8)) + exit(2) + } + generator = picked + } let done = DispatchSemaphore(value: 0) var code: Int32 = 0 @@ -18,7 +26,7 @@ enum CLI { done.signal() return } - let result = await Git.batchOco(at: path, branch: branch) { current, total in + let result = await Git.batchOco(at: path, branch: branch, generator: generator) { current, total in print("Renaming WIP \(current)/\(total)…") } if result.succeeded { diff --git a/Sources/MagicCommit/Git.swift b/Sources/MagicCommit/Git.swift index fe90be5..b5719d7 100644 --- a/Sources/MagicCommit/Git.swift +++ b/Sources/MagicCommit/Git.swift @@ -238,12 +238,10 @@ enum Git { return await Shell.run(["git", "commit", "-m", wipMessage], in: path, timeout: 300) } - /// Stages everything if nothing is staged, then lets `oco` write and create the commit. - static func commit(at path: String) async -> ShellResult { + /// Stages everything if nothing is staged, then lets `generator` write and create the commit. + static func commit(at path: String, generator: MessageGenerator = .current) async -> ShellResult { if let failure = await stageAllIfNothingStaged(at: path) { return failure } - // --yes skips the confirmation prompt; OCO_GITPUSH=false skips the push prompt - // (pushing is a separate button). - return await Shell.run(["oco", "--yes"], in: path, extraEnvironment: ["OCO_GITPUSH": "false"], timeout: 300) + return await generator.commit(at: path) } static func push(at path: String, status: GitStatus) async -> ShellResult { @@ -261,16 +259,17 @@ enum Git { let subject: String } - /// Gives every unpushed WIP commit a real message generated by `oco`. + /// Gives every unpushed WIP commit a real message generated by `generator` (oco or claude). /// /// The commits from the oldest WIP one up to HEAD are replayed in a temporary - /// detached worktree: each WIP commit is re-committed through `oco` (which sees + /// detached worktree: each WIP commit is re-committed through the generator (which sees /// exactly that commit's diff staged), others are re-committed unchanged. The /// branch ref is then swapped atomically, only if HEAD hasn't moved meanwhile. /// The final tree is identical, so the user's working tree and index are untouched. static func batchOco( at path: String, branch: String, + generator: MessageGenerator = .current, progress: @escaping @Sendable (_ current: Int, _ total: Int) -> Void ) async -> ShellResult { func fail(_ message: String, _ result: ShellResult? = nil) -> ShellResult { @@ -311,7 +310,7 @@ enum Git { ) guard add.succeeded else { return fail("Couldn't create a temporary worktree.", add) } - let result = await replay(chain, in: worktree, progress: progress, fail: fail) + let result = await replay(chain, in: worktree, generator: generator, progress: progress, fail: fail) var outcome = result.result if let newHead = result.newHead { let trees = await Shell.run(["git", "rev-parse", "\(oldHead)^{tree}", "\(newHead)^{tree}"], in: path) @@ -334,10 +333,11 @@ enum Git { private static func replay( _ chain: [LogEntry], in worktree: String, + generator: MessageGenerator, progress: @Sendable (Int, Int) -> Void, fail: (String, ShellResult?) -> ShellResult ) async -> (result: ShellResult, newHead: String?) { - // Empty WIP commits carry nothing for oco to describe: they're dropped. + // Empty WIP commits carry nothing to describe: they're dropped. var emptyWIP = Set() for entry in chain where isWIP(entry.subject) { let diff = await Shell.run(["git", "diff", "--quiet", entry.parents[0], entry.hash], in: worktree) @@ -362,16 +362,16 @@ enum Git { let before = await Shell.run(["git", "rev-parse", "HEAD"], in: worktree).stdout let author = await Shell.run(["git", "show", "-s", "--format=%an%x00%ae%x00%aI", entry.hash], in: worktree) let fields = author.stdout.trimmingCharacters(in: .newlines).components(separatedBy: "\0") - var env = ["OCO_GITPUSH": "false"] + var env: [String: String] = [:] if fields.count == 3 { env["GIT_AUTHOR_NAME"] = fields[0] env["GIT_AUTHOR_EMAIL"] = fields[1] env["GIT_AUTHOR_DATE"] = fields[2] } - let oco = await Shell.run(["oco", "--yes"], in: worktree, extraEnvironment: env, timeout: 300) + let generated = await generator.commit(at: worktree, extraEnvironment: env) let after = await Shell.run(["git", "rev-parse", "HEAD"], in: worktree).stdout - guard oco.succeeded, after != before else { - return (fail("oco failed on \(short) (\(current)/\(total)); nothing was changed.", oco), nil) + guard generated.succeeded, after != before else { + return (fail("\(generator.shortName) failed on \(short) (\(current)/\(total)); nothing was changed.", generated), nil) } let subject = await Shell.run(["git", "log", "-1", "--format=%s"], in: worktree).stdout .trimmingCharacters(in: .whitespacesAndNewlines) diff --git a/Sources/MagicCommit/MenuContentView.swift b/Sources/MagicCommit/MenuContentView.swift index 8501e41..212da3a 100644 --- a/Sources/MagicCommit/MenuContentView.swift +++ b/Sources/MagicCommit/MenuContentView.swift @@ -168,7 +168,7 @@ struct MenuContentView: View { .frame(width: 56, height: 56) VStack(spacing: 3) { Text("No projects yet").font(.system(size: 13, weight: .semibold)) - Text("Add git repositories to commit them with oco\nright from the menu bar.") + Text("Add git repositories to commit them with AI\nright from the menu bar.") .font(.system(size: 11)) .foregroundStyle(.secondary) .multilineTextAlignment(.center) @@ -197,6 +197,7 @@ struct MenuContentView: View { private var footer: some View { HStack(spacing: 10) { LaunchAtLoginToggle() + GeneratorPicker() Spacer() if let last = store.lastRefresh { TimelineView(.periodic(from: .now, by: 15)) { _ in @@ -219,6 +220,28 @@ struct MenuContentView: View { } } +// MARK: - Message generator + +/// Picks the tool that writes commit messages (oco or the local Claude Code CLI). +private struct GeneratorPicker: View { + @AppStorage(MessageGenerator.defaultsKey) private var generator: MessageGenerator = .oco + + var body: some View { + Menu { + Picker("Commit messages by", selection: $generator) { + ForEach(MessageGenerator.allCases) { Text($0.displayName).tag($0) } + } + .pickerStyle(.inline) + } label: { + Label(generator.shortName, systemImage: "sparkles") + .font(.system(size: 11)) + } + .menuStyle(.borderlessButton) + .fixedSize() + .help("Tool that writes commit messages") + } +} + // MARK: - Panel sizing private struct ContentHeightKey: PreferenceKey { @@ -479,7 +502,7 @@ struct CheckoutRow: View { Label("Commit", systemImage: "sparkles") } .buttonStyle(PillButtonStyle(fill: Theme.magic)) - .help("Stage all changes and commit with oco") + .help("Stage all changes and commit with \(MessageGenerator.current.shortName)") } if status.wipCount > 0 { Button { @@ -488,7 +511,7 @@ struct CheckoutRow: View { Label("Batch oco · \(status.wipCount)", systemImage: "wand.and.stars") } .buttonStyle(PillButtonStyle(fill: Theme.batch)) - .help("Rename \(status.wipCount) unpushed WIP commit\(status.wipCount == 1 ? "" : "s") with oco-generated messages") + .help("Rename \(status.wipCount) unpushed WIP commit\(status.wipCount == 1 ? "" : "s") with \(MessageGenerator.current.shortName)-generated messages") } if status.canPush { Button { diff --git a/Sources/MagicCommit/MessageGenerator.swift b/Sources/MagicCommit/MessageGenerator.swift new file mode 100644 index 0000000..ef4433d --- /dev/null +++ b/Sources/MagicCommit/MessageGenerator.swift @@ -0,0 +1,131 @@ +import Foundation + +/// The tool that writes commit messages: OpenCommit (`oco`) or the local Claude Code CLI (`claude`). +enum MessageGenerator: String, CaseIterable, Identifiable, Sendable { + case oco + case claude + + static let defaultsKey = "messageGenerator" + + var id: String { rawValue } + + /// The generator picked in the menu (OpenCommit until changed). + static var current: MessageGenerator { + get { UserDefaults.standard.string(forKey: defaultsKey).flatMap(MessageGenerator.init) ?? .oco } + set { UserDefaults.standard.set(newValue.rawValue, forKey: defaultsKey) } + } + + var displayName: String { + switch self { + case .oco: return "OpenCommit (oco)" + case .claude: return "Claude Code (claude)" + } + } + + /// Short name used in progress labels. + var shortName: String { rawValue } + + /// Commits the staged changes with a generated message. + /// `extraEnvironment` is passed to the commit (e.g. GIT_AUTHOR_* when replaying). + func commit(at path: String, extraEnvironment: [String: String] = [:]) async -> ShellResult { + switch self { + case .oco: + // --yes skips the confirmation prompt; OCO_GITPUSH=false skips the push prompt + // (pushing is a separate button). + let env = extraEnvironment.merging(["OCO_GITPUSH": "false"]) { _, new in new } + return Self.explainMissing(await Shell.run(["oco", "--yes"], in: path, extraEnvironment: env, timeout: 300), tool: "oco") + case .claude: + return await Self.claudeCommit(at: path, extraEnvironment: extraEnvironment) + } + } + + // MARK: Claude + + /// Model alias passed to `claude --model`. Override with + /// `defaults write io.github.dommangetnicolas.MagicCommit claudeModel sonnet`. + static var claudeModel: String { + let value = UserDefaults.standard.string(forKey: "claudeModel")?.trimmingCharacters(in: .whitespaces) ?? "" + return value.isEmpty ? "haiku" : value + } + + /// Diffs longer than this are cut (the `--stat` summary above it still lists every file). + static let maxDiffCharacters = 120_000 + + private static func claudeCommit(at path: String, extraEnvironment: [String: String]) async -> ShellResult { + let stat = await Shell.run(["git", "diff", "--cached", "--no-color", "--stat"], in: path) + guard stat.succeeded else { return stat } + guard !stat.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return ShellResult(status: 1, stdout: "", stderr: "Nothing staged to commit.") + } + let patch = await Shell.run(["git", "diff", "--cached", "--no-color", "--no-ext-diff"], in: path) + guard patch.succeeded else { return patch } + var diff = patch.stdout + if diff.count > maxDiffCharacters { + diff = String(diff.prefix(maxDiffCharacters)) + "\n[… diff truncated …]\n" + } + + let log = await Shell.run(["git", "log", "-15", "--no-merges", "--format=%s"], in: path) + let recent = log.stdout.split(separator: "\n").map(String.init).filter { !Git.isWIP($0) }.prefix(10) + + let input = """ + Recent commit subjects in this repository: + \(recent.isEmpty ? "(none)" : recent.map { "- \($0)" }.joined(separator: "\n")) + + Staged changes (summary): + \(stat.stdout) + Staged changes (diff): + \(diff) + """ + + let generated = await Shell.run( + ["claude", "-p", prompt, + "--model", claudeModel, + "--tools", "", + "--no-session-persistence", + "--output-format", "text"], + in: path, + input: input, + timeout: 300 + ) + guard generated.succeeded else { return explainMissing(generated, tool: "claude") } + guard let message = cleanMessage(generated.stdout) else { + return ShellResult(status: 1, stdout: "", stderr: "claude returned an empty commit message.\n\n\(generated.combinedOutput)") + } + return await Shell.run(["git", "commit", "-F", "-"], in: path, extraEnvironment: extraEnvironment, input: message, timeout: 300) + } + + static let prompt = """ + You write git commit messages. The input on stdin lists recent commit subjects \ + from the repository, then the staged changes. Write the commit message for the \ + staged changes. + + Rules: + - If the recent subjects follow a consistent style (e.g. Conventional Commits, \ + capitalized imperative sentences, a ticket prefix), follow that style. Otherwise \ + use Conventional Commits (feat:, fix:, refactor:, docs:, chore:, test:…). + - Subject line: imperative mood, at most 72 characters, no trailing period. + - Add a body (after a blank line) only when the change needs explaining; wrap it \ + at 72 characters and say why, not just what. + - Output only the commit message: no preamble, no quotes, no code fences. + """ + + /// Strips code fences, surrounding quotes and blank lines from the model's answer. + static func cleanMessage(_ raw: String) -> String? { + var lines = Shell.stripANSI(raw).components(separatedBy: .newlines) + lines.removeAll { $0.trimmingCharacters(in: .whitespaces).hasPrefix("```") } + var text = lines.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + if text.count >= 2, let first = text.first, first == text.last, first == "\"" || first == "`" { + text = String(text.dropFirst().dropLast()).trimmingCharacters(in: .whitespacesAndNewlines) + } + return text.isEmpty ? nil : text + "\n" + } + + /// `/usr/bin/env` exits with 127 when the tool isn't on the PATH. + private static func explainMissing(_ result: ShellResult, tool: String) -> ShellResult { + guard result.status == 127 else { return result } + let hint = tool == "claude" + ? "Install Claude Code (https://claude.com/claude-code) and sign in once with `claude` in a terminal." + : "Install OpenCommit with `npm install -g opencommit`, or switch to Claude Code in the menu." + return ShellResult(status: 127, stdout: "", stderr: "`\(tool)` wasn't found on your PATH. \(hint)") + } +} diff --git a/Sources/MagicCommit/ProjectStore.swift b/Sources/MagicCommit/ProjectStore.swift index 5bc73e0..04d1a9d 100644 --- a/Sources/MagicCommit/ProjectStore.swift +++ b/Sources/MagicCommit/ProjectStore.swift @@ -20,7 +20,7 @@ enum Activity: Equatable { case .pushing: return "Pushing…" case .removing: return "Removing worktree…" case let .batch(current, total): - return current == 0 ? "Preparing batch oco…" : "oco is renaming WIP \(current) of \(total)…" + return current == 0 ? "Preparing batch oco…" : "\(MessageGenerator.current.shortName) is renaming WIP \(current) of \(total)…" } } } diff --git a/Sources/MagicCommit/Shell.swift b/Sources/MagicCommit/Shell.swift index c3d7047..620e9db 100644 --- a/Sources/MagicCommit/Shell.swift +++ b/Sources/MagicCommit/Shell.swift @@ -62,11 +62,12 @@ enum Shell { return path.isEmpty ? nil : path } - /// Runs `arguments` (resolved via PATH) in `directory`. + /// Runs `arguments` (resolved via PATH) in `directory`, feeding `input` to stdin if given. static func run( _ arguments: [String], in directory: String, extraEnvironment: [String: String] = [:], + input: String? = nil, timeout: TimeInterval? = nil ) async -> ShellResult { await withCheckedContinuation { continuation in @@ -77,6 +78,7 @@ enum Shell { arguments: arguments, directory: directory, environment: env, + input: input, timeout: timeout ) continuation.resume(returning: result) @@ -89,6 +91,7 @@ enum Shell { arguments: [String], directory: String?, environment: [String: String], + input: String? = nil, timeout: TimeInterval? ) -> ShellResult { let process = Process() @@ -101,7 +104,8 @@ enum Shell { let errPipe = Pipe() process.standardOutput = outPipe process.standardError = errPipe - process.standardInput = FileHandle.nullDevice + let inPipe = input.map { _ in Pipe() } + process.standardInput = inPipe ?? FileHandle.nullDevice do { try process.run() @@ -115,6 +119,15 @@ enum Shell { } } + if let inPipe, let input { + // Written off-thread: a large input could fill the pipe before the child reads it. + DispatchQueue.global().async { + let handle = inPipe.fileHandleForWriting + try? handle.write(contentsOf: Data(input.utf8)) + try? handle.close() + } + } + // Drain stderr concurrently so a full pipe can't deadlock the child. var errData = Data() let group = DispatchGroup() diff --git a/Tests/MagicCommitTests/BatchOcoTests.swift b/Tests/MagicCommitTests/BatchOcoTests.swift index 0360a44..66bcda3 100644 --- a/Tests/MagicCommitTests/BatchOcoTests.swift +++ b/Tests/MagicCommitTests/BatchOcoTests.swift @@ -50,7 +50,7 @@ final class BatchOcoTests: XCTestCase { try await git("commit", "-q", "--allow-empty", "-m", "WIP") let treeBefore = try await git("rev-parse", "HEAD^{tree}") - let result = await Git.batchOco(at: repo, branch: "main") { _, _ in } + let result = await Git.batchOco(at: repo, branch: "main", generator: .oco) { _, _ in } XCTAssertTrue(result.succeeded, result.combinedOutput) let subjects = try await git("log", "--format=%s") @@ -76,7 +76,7 @@ final class BatchOcoTests: XCTestCase { XCTAssertTrue(commitWIP.succeeded, commitWIP.combinedOutput) let mainHead = try await git("rev-parse", "main") - let result = await Git.batchOco(at: linked, branch: "feature") { _, _ in } + let result = await Git.batchOco(at: linked, branch: "feature", generator: .oco) { _, _ in } XCTAssertTrue(result.succeeded, result.combinedOutput) let subjects = try await git("log", "--format=%s", "feature") @@ -88,4 +88,45 @@ final class BatchOcoTests: XCTestCase { let worktrees = try await git("worktree", "list") XCTAssertEqual(worktrees.split(separator: "\n").count, 2, "temporary worktree should be removed") } + + func testClaudeGeneratorCommitsCleanedMessageAndKeepsAuthor() async throws { + try await git("init", "-q", "-b", "main") + try await git("config", "user.name", "Test") + try await git("config", "user.email", "test@example.com") + try write("a.txt", "a") + try await git("add", "-A") + try await git("commit", "-q", "-m", "Initial commit") + + try write("b.txt", "hello from b") + try await git("add", "-A") + try await git("commit", "-q", "-m", "WIP", "--author", "Someone Else ") + + let result = await Git.batchOco(at: repo, branch: "main", generator: .claude) { _, _ in } + XCTAssertTrue(result.succeeded, result.combinedOutput) + + let message = try await git("log", "-1", "--format=%B") + XCTAssertEqual(message, "feat: claude message\n\nBody line.") + let author = try await git("log", "-1", "--format=%an <%ae>") + XCTAssertEqual(author, "Someone Else ") + let stdin = try String(contentsOfFile: "\(repo)/.git/fake-claude-stdin", encoding: .utf8) + XCTAssertTrue(stdin.contains("+hello from b"), "claude should receive the WIP commit's diff") + XCTAssertTrue(stdin.contains("- Initial commit"), "claude should see recent subjects") + } + + func testClaudeGeneratorCommitsWorkingChanges() async throws { + try await git("init", "-q", "-b", "main") + try await git("config", "user.name", "Test") + try await git("config", "user.email", "test@example.com") + try write("a.txt", "a") + let result = await Git.commit(at: repo, generator: .claude) + XCTAssertTrue(result.succeeded, result.combinedOutput) + let subject = try await git("log", "-1", "--format=%s") + XCTAssertEqual(subject, "feat: claude message") + } + + func testCleanMessage() { + XCTAssertEqual(MessageGenerator.cleanMessage("```\nfix: x\n```"), "fix: x\n") + XCTAssertEqual(MessageGenerator.cleanMessage(" \"fix: y\" \n"), "fix: y\n") + XCTAssertNil(MessageGenerator.cleanMessage("```\n```")) + } } diff --git a/Tests/MagicCommitTests/FakeOco.swift b/Tests/MagicCommitTests/FakeOco.swift index f33f527..17a665a 100644 --- a/Tests/MagicCommitTests/FakeOco.swift +++ b/Tests/MagicCommitTests/FakeOco.swift @@ -1,7 +1,8 @@ import Foundation -/// Puts a fake `oco` (commits the staged changes with a fixed message) first on -/// the PATH of every command the tests run. +/// Puts a fake `oco` (commits the staged changes with a fixed message) and a fake +/// `claude` (prints a fenced message, saving its stdin) first on the PATH of every +/// command the tests run. /// /// `Shell.environment` reads MAGIC_COMMIT_EXTRA_PATH only once, when the first /// command runs, so every test class that runs commands calls `install()` in its @@ -19,6 +20,13 @@ enum FakeOco { git commit -q -m "feat: generated message" """.write(to: oco, atomically: true, encoding: .utf8) try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: oco.path) + let claude = bin.appendingPathComponent("claude") + try? """ + #!/bin/sh + cat > "$(git rev-parse --git-common-dir)/fake-claude-stdin" + printf '```\\nfeat: claude message\\n\\nBody line.\\n```\\n' + """.write(to: claude, atomically: true, encoding: .utf8) + try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: claude.path) setenv("MAGIC_COMMIT_EXTRA_PATH", bin.path, 1) precondition(FileManager.default.isExecutableFile(atPath: oco.path), "fake oco not installed") return bin From 4c12d2a0ba27e6efa48092cca26fad4d97fbcb6a Mon Sep 17 00:00:00 2001 From: dommangetnicolas Date: Sun, 15 Nov 2026 18:06:13 +0100 Subject: [PATCH 3/3] Release 1.1.0 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88f9f90..89d4acd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ and the project uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [1.1.0] - 2026-11-15 + ### Added - Worktree support: linked worktrees of each project are discovered automatically and listed under it, each with its own status and Commit, WIP, Batch oco and Push buttons. Clean worktrees fold behind a toggle. @@ -30,5 +32,6 @@ and the project uses [Semantic Versioning](https://semver.org/). - `batch-oco` command-line mode. - Launch at login. -[Unreleased]: https://github.com/dommangetnicolas/magic-commit/compare/v1.0.0...HEAD +[Unreleased]: https://github.com/dommangetnicolas/magic-commit/compare/v1.1.0...HEAD +[1.1.0]: https://github.com/dommangetnicolas/magic-commit/compare/v1.0.0...v1.1.0 [1.0.0]: https://github.com/dommangetnicolas/magic-commit/releases/tag/v1.0.0