-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-cherry-pick-tool.ts
More file actions
351 lines (317 loc) · 12.1 KB
/
git-cherry-pick-tool.ts
File metadata and controls
351 lines (317 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import type { FastMCP } from "fastmcp";
import { z } from "zod";
import { spawnGitAsync } from "./git.js";
import {
commitListBetween,
conflictPaths,
getCurrentBranch,
isFullyMergedInto,
isProtectedBranch,
isSafeGitRangeToken,
isSafeGitRefToken,
isWorkingTreeClean,
resolveRef,
worktreeForBranch,
} from "./git-refs.js";
import { jsonRespond, spreadDefined, spreadWhen } from "./json.js";
import { requireSingleRepo } from "./roots.js";
import { WorkspacePickSchema } from "./schemas.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type SourceKind = "sha" | "range" | "branch";
interface ResolvedSource {
raw: string;
kind: SourceKind;
commits: string[];
}
interface SourceReport extends ResolvedSource {
branchDeleted?: boolean;
worktreeRemoved?: string;
}
interface ConflictReport {
stage: "cherry-pick";
commit?: string;
paths: string[];
detail?: string;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function cherryPickHead(gitTop: string): Promise<string | undefined> {
const r = await spawnGitAsync(gitTop, ["rev-parse", "--verify", "--quiet", "CHERRY_PICK_HEAD"]);
if (!r.ok) return undefined;
const sha = r.stdout.trim();
return sha === "" ? undefined : sha;
}
async function abortCherryPick(gitTop: string): Promise<void> {
await spawnGitAsync(gitTop, ["cherry-pick", "--abort"]);
}
async function branchExists(gitTop: string, name: string): Promise<boolean> {
const r = await spawnGitAsync(gitTop, ["show-ref", "--verify", "--quiet", `refs/heads/${name}`]);
return r.ok;
}
/**
* Expand a source spec into a list of SHAs to cherry-pick.
* - `A..B` / `A...B` → `git rev-list --reverse` of the range
* - branch name (refs/heads/<name> exists) → `onto..<branch>` oldest-first
* - SHA or ref → single commit
*/
async function resolveSource(
gitTop: string,
onto: string,
raw: string,
): Promise<ResolvedSource | { error: string; detail?: string; raw: string }> {
if (raw.includes("..")) {
if (!isSafeGitRangeToken(raw)) {
return { error: "unsafe_ref_token", raw };
}
const r = await spawnGitAsync(gitTop, ["rev-list", "--reverse", raw]);
if (!r.ok) {
return {
error: "range_resolution_failed",
detail: (r.stderr || r.stdout).trim(),
raw,
};
}
const commits = r.stdout
.split("\n")
.map((l) => l.trim())
.filter((l) => l.length > 0);
return { raw, kind: "range", commits };
}
if (!isSafeGitRefToken(raw)) {
return { error: "unsafe_ref_token", raw };
}
if (await branchExists(gitTop, raw)) {
const commits = await commitListBetween(gitTop, onto, raw);
if (commits === null) {
return { error: "range_resolution_failed", raw };
}
return { raw, kind: "branch", commits };
}
const sha = await resolveRef(gitTop, raw);
if (!sha) {
return { error: "source_not_found", raw };
}
return { raw, kind: "sha", commits: [sha] };
}
/**
* Pre-filter already-in-destination commits (they would cherry-pick to empty).
* Also dedupe across sources while preserving first-seen order per-commit.
*/
async function filterAndDedupe(
gitTop: string,
onto: string,
resolved: ResolvedSource[],
): Promise<{ picks: string[]; perSourceKept: Map<string, string[]> }> {
const seen = new Set<string>();
const picks: string[] = [];
const perSourceKept = new Map<string, string[]>();
for (const src of resolved) {
const kept: string[] = [];
for (const sha of src.commits) {
if (seen.has(sha)) continue;
seen.add(sha);
// Skip commits already reachable from destination (would produce empty commits).
const contained = await spawnGitAsync(gitTop, ["merge-base", "--is-ancestor", sha, onto]);
if (contained.ok) continue; // already in destination
picks.push(sha);
kept.push(sha);
}
perSourceKept.set(src.raw, kept);
}
return { picks, perSourceKept };
}
// ---------------------------------------------------------------------------
// Tool registration
// ---------------------------------------------------------------------------
export function registerGitCherryPickTool(server: FastMCP): void {
server.addTool({
name: "git_cherry_pick",
description:
"Play commits from one or more sources onto a destination. Sources may be SHAs, " +
"`A..B` ranges, or branch names (expanded to `onto..<branch>`, oldest-first). " +
"Commits already reachable from the destination are skipped. Refuses on dirty tree; " +
"stops on the first conflict and reports paths. Optional flags auto-delete fully " +
"merged source branches and their worktrees, skipping protected names.",
annotations: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
},
parameters: WorkspacePickSchema.omit({ absoluteGitRoots: true }).extend({
sources: z
.array(z.string().min(1))
.min(1)
.max(50)
.describe(
"Sources to cherry-pick: SHA, `A..B` range, or branch name. Branch sources " +
"resolve to `onto..<branch>` (only commits missing from destination).",
),
onto: z
.string()
.optional()
.describe("Destination branch. Defaults to the currently checked-out branch."),
deleteMergedBranches: z
.boolean()
.optional()
.default(false)
.describe(
"After all commits apply, delete each branch-kind source locally " +
"(`git branch -d`) when it is fully merged into the destination. " +
"Protected names always skipped; never touches remote refs.",
),
deleteMergedWorktrees: z
.boolean()
.optional()
.default(false)
.describe(
"After success, remove any local worktree attached to a branch-kind source " +
"(`git worktree remove`). Protected tails always skipped.",
),
}),
execute: async (args) => {
const pre = requireSingleRepo(server, args);
if (!pre.ok) return jsonRespond(pre.error);
const gitTop = pre.gitTop;
// --- Resolve destination ---
const startBranch = await getCurrentBranch(gitTop);
const onto = args.onto?.trim() || startBranch;
if (!onto) return jsonRespond({ error: "onto_detached_head" });
if (args.onto !== undefined && !isSafeGitRefToken(args.onto)) {
return jsonRespond({ error: "unsafe_ref_token", ref: args.onto });
}
// --- Refuse dirty tree ---
if (!(await isWorkingTreeClean(gitTop))) {
return jsonRespond({ error: "working_tree_dirty" });
}
// --- Ensure destination is checked out ---
if (onto !== startBranch) {
const co = await spawnGitAsync(gitTop, ["checkout", onto]);
if (!co.ok) {
return jsonRespond({
error: "checkout_failed",
detail: (co.stderr || co.stdout).trim(),
});
}
}
if (!(await resolveRef(gitTop, onto))) {
return jsonRespond({ error: "destination_not_found", ref: onto });
}
// --- Resolve each source ---
const resolved: ResolvedSource[] = [];
for (const raw of args.sources) {
const r = await resolveSource(gitTop, onto, raw);
if ("error" in r) {
return jsonRespond({
error: r.error,
source: raw,
...spreadDefined("detail", r.detail),
});
}
resolved.push(r);
}
// --- Dedupe + skip already-present ---
const { picks, perSourceKept } = await filterAndDedupe(gitTop, onto, resolved);
// --- Apply cherry-pick (single atomic call) ---
// `--empty=drop` silently drops commits that would produce no change against the
// current tip — makes the tool idempotent when the same patch is re-applied.
let conflict: ConflictReport | undefined;
let appliedCount = 0;
const preHeadProbe = await spawnGitAsync(gitTop, ["rev-parse", "HEAD"]);
const preHead = preHeadProbe.ok ? preHeadProbe.stdout.trim() : "";
if (picks.length > 0) {
const r = await spawnGitAsync(gitTop, ["cherry-pick", "--empty=drop", ...picks]);
if (!r.ok) {
const failedSha = await cherryPickHead(gitTop);
const paths = await conflictPaths(gitTop);
await abortCherryPick(gitTop);
conflict = {
stage: "cherry-pick",
...spreadDefined("commit", failedSha),
paths,
detail: (r.stderr || r.stdout).trim(),
};
} else {
// Actual commits written = HEAD advance count (empty-drop may skip some).
const adv = await spawnGitAsync(gitTop, ["rev-list", "--count", `${preHead}..HEAD`]);
appliedCount = adv.ok ? parseInt(adv.stdout.trim(), 10) || 0 : 0;
}
}
const allOk = !conflict;
// --- Cleanup (only on full success, only branch-kind sources) ---
const perSourceReport: SourceReport[] = resolved.map((s) => ({ ...s }));
if (allOk) {
for (let i = 0; i < perSourceReport.length; i++) {
const src = perSourceReport[i];
if (!src || src.kind !== "branch") continue;
if (isProtectedBranch(src.raw)) continue;
if (args.deleteMergedWorktrees) {
const path = await worktreeForBranch(gitTop, src.raw);
if (path) {
const tail = path.split("/").pop() ?? "";
if (!isProtectedBranch(tail)) {
const r = await spawnGitAsync(gitTop, ["worktree", "remove", path]);
if (r.ok) src.worktreeRemoved = path;
}
}
}
if (args.deleteMergedBranches) {
const merged = await isFullyMergedInto(gitTop, src.raw, onto);
if (merged) {
const r = await spawnGitAsync(gitTop, ["branch", "-d", src.raw]);
if (r.ok) src.branchDeleted = true;
}
}
}
}
const headProbe = await spawnGitAsync(gitTop, ["rev-parse", "HEAD"]);
const headSha = headProbe.ok ? headProbe.stdout.trim() : undefined;
if (args.format === "json") {
return jsonRespond({
ok: allOk,
onto,
...spreadDefined("headSha", headSha),
applied: appliedCount,
picked: picks.length,
results: perSourceReport.map((s) => ({
source: s.raw,
kind: s.kind,
resolvedCommits: s.commits.length,
keptCommits: perSourceKept.get(s.raw)?.length ?? 0,
...spreadWhen(s.branchDeleted === true, { branchDeleted: true }),
...spreadDefined("worktreeRemoved", s.worktreeRemoved),
})),
...spreadWhen(conflict !== undefined, {
conflict: {
stage: conflict?.stage ?? "cherry-pick",
...spreadDefined("commit", conflict?.commit),
paths: conflict?.paths ?? [],
...spreadDefined("detail", conflict?.detail),
},
}),
});
}
// --- Markdown ---
const lines: string[] = [];
const header = allOk
? `# Cherry-pick onto \`${onto}\`: ${appliedCount} commit(s) applied`
: `# Cherry-pick onto \`${onto}\`: stopped on conflict after ${appliedCount} commit(s)`;
lines.push(header, "");
for (const s of perSourceReport) {
const kept = perSourceKept.get(s.raw)?.length ?? 0;
const tail: string[] = [`${s.kind}`, `${kept}/${s.commits.length} picked`];
if (s.branchDeleted) tail.push("branch deleted");
if (s.worktreeRemoved) tail.push(`worktree removed: ${s.worktreeRemoved}`);
lines.push(`- ${s.raw} — ${tail.join(", ")}`);
}
if (conflict) {
lines.push("", `Conflict at commit \`${conflict.commit ?? "?"}\` (${conflict.stage}):`);
for (const p of conflict.paths) lines.push(` conflict: ${p}`);
if (conflict.detail) lines.push(` detail: ${conflict.detail}`);
}
return lines.join("\n");
},
});
}