Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ 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.
- **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

- 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
Expand All @@ -18,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
37 changes: 24 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -16,24 +16,33 @@ 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 <remote> <branch>` 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

- 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
defaults write io.github.dommangetnicolas.MagicCommit claudeModel sonnet
```

```bash
npm install -g opencommit
oco config set OCO_API_KEY=<your key>
```
- **opencommit**: installed and configured:

Magic Commit reads your `PATH` from your login shell, so `oco` installed through nvm, Homebrew or similar is found.
```bash
npm install -g opencommit
oco config set OCO_API_KEY=<your key>
```

Magic Commit reads your `PATH` from your login shell, so tools installed through nvm, Homebrew or similar are found.

## Installation

Expand Down Expand Up @@ -71,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

Expand Down
12 changes: 10 additions & 2 deletions Sources/MagicCommit/CLI.swift
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 {
Expand Down
148 changes: 133 additions & 15 deletions Sources/MagicCommit/Git.swift
Original file line number Diff line number Diff line change
@@ -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?
Expand All @@ -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 <path>`, `HEAD <sha>`,
/// `branch refs/heads/<name>`, `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[..<space]), String(line[line.index(after: space)...]))
}()
if key == "worktree" {
flush()
current = Worktree(path: value, isMain: result.isEmpty)
continue
}
guard current != nil else { continue }
switch key {
case "HEAD": current?.head = value
case "branch":
current?.branch = value.hasPrefix("refs/heads/") ? String(value.dropFirst("refs/heads/".count)) : value
case "detached": current?.isDetached = true
case "bare": current?.isBare = true
case "locked": current?.lockReason = value
case "prunable": current?.isPrunable = true
default: break
}
}
flush()
return result
}

static var tempWorktreeLockReason: String { "magic-commit pid \(getpid())" }

/// Whether `worktree` is one of the temporary worktrees Batch oco creates.
static func isTempWorktree(_ worktree: Worktree, tempDirectory: URL = FileManager.default.temporaryDirectory) -> 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")
Expand Down Expand Up @@ -125,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 {
Expand All @@ -148,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 {
Expand Down Expand Up @@ -191,10 +303,14 @@ 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)
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)
Expand All @@ -209,17 +325,19 @@ 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
}

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<String>()
for entry in chain where isWIP(entry.subject) {
let diff = await Shell.run(["git", "diff", "--quiet", entry.parents[0], entry.hash], in: worktree)
Expand All @@ -244,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)
Expand Down
Loading
Loading