git-tm 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/edit.js ADDED
@@ -0,0 +1,513 @@
1
+ // History editing for edit mode (`git tm --edit`).
2
+ //
3
+ // This is the only module in git-tm that changes refs or the working tree. Everything else
4
+ // is read-only. The rules, in order:
5
+ // 1. Plan without side effects: new commits are built with plumbing (commit-tree,
6
+ // merge-tree --write-tree), so a preview only writes unreachable objects.
7
+ // 2. Apply with compare-and-swap: the branch must still be where the plan found it.
8
+ // 3. Back up first: the old tip is kept under refs/git-tm/backups/<id> and logged, so every
9
+ // edit can be undone.
10
+ // 4. All or nothing: any conflict aborts before a ref moves.
11
+
12
+ import { randomBytes } from "node:crypto";
13
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
14
+ import { existsSync } from "node:fs";
15
+ import path from "node:path";
16
+ import { git, checkRev, GitError } from "./git.js";
17
+ import { canonicalPath, samePath } from "./paths.js";
18
+
19
+ export const EDIT_OPS = ["reword", "author", "squash", "drop", "revert"];
20
+
21
+ /** Operations whose result has the same final tree, so the index and working tree never change. */
22
+ const TREE_PRESERVING = new Set(["reword", "author", "squash"]);
23
+ const MAX_REPLAY = 2000;
24
+ const MAX_MESSAGE = 32 * 1024;
25
+ const MAX_LOG = 200;
26
+ const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
27
+ const ID = /^\d{13}-[0-9a-f]{4}$/;
28
+ const BACKUP_PREFIX = "refs/git-tm/backups/";
29
+
30
+ const run = (repo, args, opts) => git(repo.root, args, opts);
31
+ const tryRun = (repo, args, opts) => run(repo, args, opts).catch(() => null);
32
+
33
+ const fail = (message, status = 400) => {
34
+ throw new GitError(message, status);
35
+ };
36
+
37
+ // ------------------------------------------------------------------ inputs
38
+
39
+ function checkBranchName(name) {
40
+ if (typeof name !== "string" || !name || name.length > 255 || name.startsWith("-") || /[\s\x00-\x1f\x7f~^:?*[\\]|\.\.|@\{/.test(name)) {
41
+ fail(`Invalid branch name: ${String(name).slice(0, 80)}`);
42
+ }
43
+ return name;
44
+ }
45
+
46
+ function checkMessage(message) {
47
+ if (typeof message !== "string" || !message.trim()) fail("The commit message can't be empty");
48
+ if (message.length > MAX_MESSAGE) fail("The commit message is too long");
49
+ if (message.includes("\0")) fail("The commit message contains a NUL character");
50
+ return message.replace(/\r\n/g, "\n").replace(/\s+$/, "") + "\n";
51
+ }
52
+
53
+ /** Name and email go into a commit header, so they must stay on one line and avoid <>. */
54
+ function checkIdentityPart(value, what) {
55
+ if (typeof value !== "string" || !value.trim()) fail(`The author ${what} can't be empty`);
56
+ if (value.length > 256 || /[<>\x00-\x1f\x7f]/.test(value)) fail(`The author ${what} contains characters that aren't allowed`);
57
+ return value.trim();
58
+ }
59
+
60
+ // ------------------------------------------------------------------ git helpers
61
+
62
+ /** Parse a raw commit object. Headers are read as text; the message is everything after the first blank line. */
63
+ async function readCommit(repo, sha) {
64
+ const raw = await run(repo, ["cat-file", "commit", sha]);
65
+ const split = raw.indexOf("\n\n");
66
+ const head = split === -1 ? raw : raw.slice(0, split);
67
+ const message = split === -1 ? "" : raw.slice(split + 2);
68
+ const c = { hash: sha, tree: null, parents: [], author: null, signed: false, message };
69
+ for (const line of head.split("\n")) {
70
+ if (line.startsWith("tree ")) c.tree = line.slice(5);
71
+ else if (line.startsWith("parent ")) c.parents.push(line.slice(7));
72
+ else if (line.startsWith("author ")) c.author = parseIdent(line.slice(7));
73
+ else if (line.startsWith("gpgsig") || line.startsWith("gpgsig-sha256")) c.signed = true;
74
+ }
75
+ c.subject = message.split("\n")[0] || "";
76
+ return c;
77
+ }
78
+
79
+ function requireAuthor(c) {
80
+ if (!c.author) fail(`Commit ${c.hash.slice(0, 7)} has an author line git-tm can't read, so it can't be rewritten safely.`);
81
+ }
82
+
83
+ function parseIdent(s) {
84
+ const m = s.match(/^(.*) <([^>]*)> (\d+) ([+-]\d{4})$/);
85
+ return m ? { name: m[1], email: m[2], date: `${m[3]} ${m[4]}`, time: Number(m[3]), tz: m[4] } : null;
86
+ }
87
+
88
+ /** Write a commit object. Committer identity comes from the user's git config; signing is skipped so the server never waits for a prompt. */
89
+ async function commitTree(repo, { tree, parents, message, author }) {
90
+ const args = ["commit-tree", "--no-gpg-sign", tree];
91
+ for (const p of parents) args.push("-p", p);
92
+ args.push("-F", "-");
93
+ const env = author ? { GIT_AUTHOR_NAME: author.name, GIT_AUTHOR_EMAIL: author.email, GIT_AUTHOR_DATE: author.date } : undefined;
94
+ try {
95
+ return (await run(repo, args, { input: message, env })).trim();
96
+ } catch (e) {
97
+ if (/identity|email address|user\.name|user\.email/i.test(e.message)) {
98
+ fail("Git doesn't know who you are. Set user.name and user.email (git config --global user.name \"Your Name\"), then try again.");
99
+ }
100
+ throw e;
101
+ }
102
+ }
103
+
104
+ /** Three-way merge without touching the working tree. Resolves with a tree id, or throws 409 listing conflicted files. */
105
+ async function mergeTree(repo, base, ours, theirs, what) {
106
+ const res = await run(repo, ["merge-tree", "--write-tree", "--name-only", "--no-messages", "-z", "--merge-base", base, ours, theirs], {
107
+ allowExit: [1],
108
+ });
109
+ const parts = res.stdout.split("\0").filter(Boolean);
110
+ if (res.code === 1) {
111
+ const files = [...new Set(parts.slice(1))];
112
+ const err = new GitError(`${what} would conflict in ${files.length === 1 ? files[0] : `${files.length} files`}. Nothing was changed.`, 409);
113
+ err.conflicts = files;
114
+ throw err;
115
+ }
116
+ return parts[0];
117
+ }
118
+
119
+ async function gitVersionAtLeast(repo, major, minor) {
120
+ repo._gitVersion ??= (await run(repo, ["version"])).match(/(\d+)\.(\d+)/);
121
+ const m = repo._gitVersion;
122
+ return Boolean(m) && (Number(m[1]) > major || (Number(m[1]) === major && Number(m[2]) >= minor));
123
+ }
124
+
125
+ async function requireMergeTree(repo, op) {
126
+ if (!(await gitVersionAtLeast(repo, 2, 40))) {
127
+ const v = (await run(repo, ["version"])).trim().replace(/^git version /, "");
128
+ fail(`${op} needs Git 2.40 or newer (you have ${v}).`);
129
+ }
130
+ }
131
+
132
+ async function commonDir(repo) {
133
+ if (!repo._commonDir) {
134
+ const out = (await run(repo, ["rev-parse", "--git-common-dir"])).trim();
135
+ repo._commonDir = path.resolve(repo.root, out);
136
+ }
137
+ return repo._commonDir;
138
+ }
139
+
140
+ /** Refuse while git is in the middle of something; editing then would corrupt that operation. */
141
+ async function assertIdle(repo) {
142
+ const markers = ["rebase-merge", "rebase-apply", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_LOG"];
143
+ const busy = markers.find((m) => existsSync(path.join(repo.gitDir, m)));
144
+ if (busy) {
145
+ const what = { "rebase-merge": "a rebase", "rebase-apply": "a rebase", MERGE_HEAD: "a merge", CHERRY_PICK_HEAD: "a cherry-pick", REVERT_HEAD: "a revert", BISECT_LOG: "a bisect" }[busy];
146
+ fail(`Git is in the middle of ${what}. Finish or abort it first.`, 409);
147
+ }
148
+ }
149
+
150
+ async function currentBranch(repo) {
151
+ const out = await tryRun(repo, ["symbolic-ref", "--quiet", "HEAD"]);
152
+ return out && out.trim().startsWith("refs/heads/") ? out.trim().slice(11) : null;
153
+ }
154
+
155
+ async function branchTip(repo, branch) {
156
+ const out = await tryRun(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`]);
157
+ return out ? out.trim() : null;
158
+ }
159
+
160
+ /** Branches checked out in other worktrees can't be moved without breaking those worktrees. */
161
+ async function checkedOutElsewhere(repo, branch) {
162
+ const out = await tryRun(repo, ["worktree", "list", "--porcelain", "-z"]);
163
+ if (!out) return false;
164
+ // Compare canonical paths: the same folder can be spelled differently (macOS /tmp vs
165
+ // /private/tmp, Windows c:\ vs C:\), and a mismatch would block edits on this worktree.
166
+ const root = await canonicalPath(repo.root);
167
+ let wtPath = null;
168
+ for (const line of out.split("\0")) {
169
+ if (line.startsWith("worktree ")) wtPath = line.slice(9);
170
+ else if (line === `branch refs/heads/${branch}` && wtPath) {
171
+ const other = await canonicalPath(wtPath);
172
+ if (!samePath(other, root)) return other;
173
+ }
174
+ }
175
+ return false;
176
+ }
177
+
178
+ // ------------------------------------------------------------------ planning
179
+
180
+ /**
181
+ * Work out an edit without changing anything.
182
+ * op: { type, commit, branch?, message?, author?: { name, email, date? } }
183
+ * date is Unix seconds; the original time zone offset is kept.
184
+ */
185
+ export async function planEdit(repo, op = {}) {
186
+ const type = op.type;
187
+ if (!EDIT_OPS.includes(type)) fail(`Unknown edit: ${String(type).slice(0, 40)}`);
188
+ await assertIdle(repo);
189
+
190
+ const branch = op.branch ? checkBranchName(op.branch) : await currentBranch(repo);
191
+ if (!branch) fail("HEAD is detached. Pick a branch to edit.");
192
+ const ref = `refs/heads/${branch}`;
193
+ const oldTip = await branchTip(repo, branch);
194
+ if (!oldTip) fail(`No local branch named ${branch}`, 404);
195
+
196
+ const target = await repo.resolve(checkRev(String(op.commit ?? "")));
197
+ if (!SHA.test(target)) fail("Pick a commit to edit");
198
+ const onBranch = await run(repo, ["merge-base", "--is-ancestor", target, oldTip], { allowExit: [1] });
199
+ if (onBranch.code !== 0) fail(`That commit isn't on ${branch}.`);
200
+
201
+ const tc = await readCommit(repo, target);
202
+ const plan = {
203
+ type,
204
+ branch,
205
+ ref,
206
+ oldTip,
207
+ newTip: null,
208
+ target,
209
+ targetSubject: tc.subject,
210
+ rewritten: [],
211
+ added: [],
212
+ treePreserving: TREE_PRESERVING.has(type),
213
+ pushed: [],
214
+ otherRefs: { branches: [], tags: [] },
215
+ signed: 0,
216
+ warnings: [],
217
+ checkedOut: !repo.bare && (await currentBranch(repo)) === branch,
218
+ };
219
+
220
+ if (type === "revert") {
221
+ await requireMergeTree(repo, "Revert");
222
+ if (tc.parents.length !== 1) fail(tc.parents.length ? "Merge commits can't be reverted here yet." : "The first commit can't be reverted.");
223
+ const tipCommit = await readCommit(repo, oldTip);
224
+ const tree = await mergeTree(repo, target, oldTip, tc.parents[0], "Reverting this commit");
225
+ if (tree === tipCommit.tree) fail("Nothing to revert: those changes are already undone on this branch.");
226
+ const message = checkMessage(op.message || `Revert "${tc.subject}"\n\nThis reverts commit ${target}.`);
227
+ plan.newTip = await commitTree(repo, { tree, parents: [oldTip], message });
228
+ plan.added.push({ new: plan.newTip, subject: message.split("\n")[0] });
229
+ plan.summary = `Add a commit on ${branch} that undoes "${tc.subject}". No history is rewritten.`;
230
+ return plan;
231
+ }
232
+
233
+ // Rewrites: the commit must be on the branch's first-parent line so we can replay what follows it.
234
+ const descendants = (await run(repo, ["rev-list", "--first-parent", "--reverse", `--max-count=${MAX_REPLAY + 1}`, `${target}..${oldTip}`]))
235
+ .split("\n")
236
+ .filter(Boolean);
237
+ if (descendants.length > MAX_REPLAY) fail(`That commit is more than ${MAX_REPLAY} commits back; edit something more recent.`);
238
+ const descCommits = [];
239
+ for (const d of descendants) descCommits.push(await readCommit(repo, d));
240
+ if (descCommits.length && descCommits[0].parents[0] !== target) {
241
+ fail(`That commit is on a branch that was merged into ${branch}. Edit that branch instead.`);
242
+ }
243
+ // Every rewritten commit keeps its author. Without a readable author line, commit-tree would
244
+ // silently use the current user instead, so refuse. (A dropped commit isn't rewritten.)
245
+ if (type !== "drop") requireAuthor(tc);
246
+ for (const d of descCommits) requireAuthor(d);
247
+
248
+ let start; // the first new commit, which replaces the target (or its parent, for squash)
249
+ let replaced = [tc]; // old commits that the new start commit stands in for
250
+ let replay = descCommits;
251
+
252
+ if (type === "reword") {
253
+ const message = checkMessage(op.message);
254
+ // A no-op rewrite would still give this commit and every later one new hashes (and a backup).
255
+ if (message.replace(/\s+$/, "") === tc.message.replace(/\s+$/, "")) fail("Nothing to change: the message is the same.");
256
+ start = await commitTree(repo, { tree: tc.tree, parents: tc.parents, message, author: tc.author });
257
+ plan.summary = `Reword "${tc.subject}" on ${branch}.`;
258
+ } else if (type === "author") {
259
+ const a = op.author || {};
260
+ const name = checkIdentityPart(a.name, "name");
261
+ const email = checkIdentityPart(a.email, "email");
262
+ let date = tc.author.date;
263
+ if (a.date !== undefined && a.date !== null && a.date !== "") {
264
+ const secs = Number(a.date);
265
+ if (!Number.isInteger(secs) || secs < 0 || secs > 253402300799) fail("Invalid author date");
266
+ date = `${secs} ${tc.author.tz}`;
267
+ }
268
+ const sameAuthor = name === tc.author.name && email === tc.author.email;
269
+ if (sameAuthor && date === tc.author.date) fail("Nothing to change: the author and date are the same.");
270
+ start = await commitTree(repo, { tree: tc.tree, parents: tc.parents, message: tc.message, author: { name, email, date } });
271
+ plan.summary = sameAuthor
272
+ ? `Change the date of "${tc.subject}" on ${branch}.`
273
+ : `Change the author of "${tc.subject}" on ${branch} to ${name} <${email}>.`;
274
+ } else if (type === "squash") {
275
+ if (tc.parents.length === 0) fail("The first commit has no parent to squash into.");
276
+ if (tc.parents.length > 1) fail("Merge commits can't be squashed.");
277
+ const pc = await readCommit(repo, tc.parents[0]);
278
+ if (pc.parents.length > 1) fail("Can't squash into a merge commit.");
279
+ requireAuthor(pc);
280
+ const message = checkMessage(op.message || `${pc.message.replace(/\s+$/, "")}\n\n${tc.message}`);
281
+ start = await commitTree(repo, { tree: tc.tree, parents: pc.parents, message, author: pc.author });
282
+ replaced = [pc, tc];
283
+ plan.summary = `Squash "${tc.subject}" into "${pc.subject}" on ${branch}.`;
284
+ } else if (type === "drop") {
285
+ await requireMergeTree(repo, "Dropping a commit");
286
+ if (tc.parents.length === 0) fail("The first commit can't be dropped.");
287
+ if (tc.parents.length > 1) fail("Merge commits can't be dropped here yet.");
288
+ if (descCommits.some((d) => d.parents.length > 1)) fail(`There's a merge between this commit and the tip of ${branch}, so it can't be dropped yet.`);
289
+ let parent = tc.parents[0];
290
+ for (const d of descCommits) {
291
+ const tree = await mergeTree(repo, d.parents[0], parent, d.hash, `Dropping "${tc.subject}"`);
292
+ const next = await commitTree(repo, { tree, parents: [parent], message: d.message, author: d.author });
293
+ plan.rewritten.push({ old: d.hash, new: next, subject: d.subject });
294
+ parent = next;
295
+ }
296
+ plan.rewritten.unshift({ old: target, new: null, subject: tc.subject });
297
+ plan.newTip = parent;
298
+ replay = [];
299
+ plan.summary = `Drop "${tc.subject}" from ${branch}.`;
300
+ }
301
+
302
+ if (type !== "drop") {
303
+ for (const r of replaced) plan.rewritten.push({ old: r.hash, new: start, subject: r.subject });
304
+ let prev = start;
305
+ for (const d of replay) {
306
+ prev = await commitTree(repo, { tree: d.tree, parents: [prev, ...d.parents.slice(1)], message: d.message, author: d.author });
307
+ plan.rewritten.push({ old: d.hash, new: prev, subject: d.subject });
308
+ }
309
+ plan.newTip = prev;
310
+ }
311
+
312
+ // Warnings: who else still sees the old timeline.
313
+ const oldest = replaced[0].hash;
314
+ const contains = await repo.containedIn(oldest);
315
+ plan.pushed = contains.remotes;
316
+ plan.otherRefs = { branches: contains.branches.filter((b) => b !== branch), tags: contains.tags };
317
+ plan.signed = [...replaced, ...descCommits].filter((c) => c.signed).length;
318
+ const changed = plan.rewritten.length;
319
+ plan.warnings.push(`This creates a branched timeline: ${changed} ${changed === 1 ? "commit gets a new ID" : "commits get new IDs"}.`);
320
+ if (plan.pushed.length) {
321
+ plan.warnings.push(`Paradox: these commits are already on ${plan.pushed.join(", ")}. Changing them means a force-push, and anyone who pulled them will have a different history.`);
322
+ }
323
+ if (plan.otherRefs.branches.length || plan.otherRefs.tags.length) {
324
+ plan.warnings.push(`Still on the old timeline afterwards: ${[...plan.otherRefs.branches, ...plan.otherRefs.tags.map((t) => `tag ${t}`)].join(", ")}.`);
325
+ }
326
+ if (plan.signed) plan.warnings.push(`${plan.signed} signed ${plan.signed === 1 ? "commit loses its signature" : "commits lose their signatures"}.`);
327
+ return plan;
328
+ }
329
+
330
+ // ------------------------------------------------------------------ applying
331
+
332
+ function checkPlan(plan) {
333
+ if (!plan || !EDIT_OPS.includes(plan.type)) fail("Invalid edit plan");
334
+ checkBranchName(plan.branch);
335
+ if (plan.ref !== `refs/heads/${plan.branch}`) fail("Invalid edit plan");
336
+ if (!SHA.test(plan.oldTip) || !SHA.test(plan.newTip)) fail("Invalid edit plan");
337
+ }
338
+
339
+ /** Move a branch from oldTip to newTip using the safest method for its situation. */
340
+ async function moveBranch(repo, { branch, oldTip, newTip, treePreserving, label }) {
341
+ const ref = `refs/heads/${branch}`;
342
+ const elsewhere = await checkedOutElsewhere(repo, branch);
343
+ if (elsewhere) fail(`${branch} is checked out in another worktree (${elsewhere}). Switch that worktree away first.`, 409);
344
+ const checkedOut = !repo.bare && (await currentBranch(repo)) === branch;
345
+
346
+ if (treePreserving || !checkedOut) {
347
+ // Atomic compare-and-swap; with an unchanged tree the index and working tree stay exactly as they are.
348
+ try {
349
+ await run(repo, ["update-ref", "-m", label, ref, newTip, oldTip]);
350
+ } catch {
351
+ fail(`${branch} changed since this edit was previewed. Preview it again.`, 409);
352
+ }
353
+ return;
354
+ }
355
+
356
+ // The tree changes on the checked-out branch, so the working tree has to follow.
357
+ // reset --keep resets the index, which would silently unstage changes: refuse instead.
358
+ const staged = await run(repo, ["diff", "--cached", "--quiet"], { allowExit: [1] });
359
+ if (staged.code === 1) fail("You have staged changes. Commit, stash or unstage them first, so this edit can't lose them.", 409);
360
+ if ((await branchTip(repo, branch)) !== oldTip) fail(`${branch} changed since this edit was previewed. Preview it again.`, 409);
361
+ try {
362
+ await run(repo, ["reset", "--keep", newTip], { env: { GIT_REFLOG_ACTION: label } });
363
+ } catch (e) {
364
+ fail(`Your uncommitted changes touch the same files, so the working tree can't be updated safely: ${e.message}`, 409);
365
+ }
366
+ }
367
+
368
+ async function logPath(repo) {
369
+ return path.join(await commonDir(repo), "git-tm", "edits.json");
370
+ }
371
+
372
+ async function readLog(repo) {
373
+ try {
374
+ const data = JSON.parse(await readFile(await logPath(repo), "utf8"));
375
+ return Array.isArray(data) ? data : [];
376
+ } catch {
377
+ return [];
378
+ }
379
+ }
380
+
381
+ /** Replace the log in one step, so a crash never leaves a half-written file. */
382
+ async function writeLog(repo, entries) {
383
+ const file = await logPath(repo);
384
+ await mkdir(path.dirname(file), { recursive: true });
385
+ const kept = entries.slice(-MAX_LOG);
386
+ const evicted = entries.length > MAX_LOG ? entries.slice(0, entries.length - MAX_LOG) : [];
387
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
388
+ try {
389
+ await writeFile(tmp, JSON.stringify(kept, null, 2) + "\n");
390
+ await rename(tmp, file);
391
+ } catch (e) {
392
+ await unlink(tmp).catch(() => {});
393
+ throw e;
394
+ }
395
+ for (const e of evicted) {
396
+ if (e?.id) await removeBackup(repo, e.id);
397
+ }
398
+ }
399
+
400
+ const newId = () => `${Date.now()}-${randomBytes(2).toString("hex")}`;
401
+
402
+ async function createBackup(repo, id, oldTip) {
403
+ await run(repo, ["update-ref", `${BACKUP_PREFIX}${id}`, oldTip, ""]);
404
+ }
405
+
406
+ async function removeBackup(repo, id) {
407
+ await tryRun(repo, ["update-ref", "-d", `${BACKUP_PREFIX}${id}`]);
408
+ }
409
+
410
+ /** Apply a plan from planEdit(). Returns { id, branch, oldTip, newTip }. */
411
+ export async function applyEdit(repo, plan, { allowPushed = false } = {}) {
412
+ checkPlan(plan);
413
+ await assertIdle(repo);
414
+ const rewriting = plan.type !== "revert";
415
+ if (rewriting && plan.pushed?.length && !allowPushed) {
416
+ fail("These commits are already on a remote. Confirm that you want to rewrite shared history.", 409);
417
+ }
418
+ if ((await branchTip(repo, plan.branch)) !== plan.oldTip) fail(`${plan.branch} changed since this edit was previewed. Preview it again.`, 409);
419
+
420
+ const id = newId();
421
+ await createBackup(repo, id, plan.oldTip);
422
+ try {
423
+ await moveBranch(repo, {
424
+ branch: plan.branch,
425
+ oldTip: plan.oldTip,
426
+ newTip: plan.newTip,
427
+ treePreserving: TREE_PRESERVING.has(plan.type),
428
+ label: `git-tm: ${plan.type} (backup ${id})`,
429
+ });
430
+ } catch (e) {
431
+ await removeBackup(repo, id);
432
+ throw e;
433
+ }
434
+ const entry = { id, branch: plan.branch, op: plan.type, summary: plan.summary || "", oldTip: plan.oldTip, newTip: plan.newTip, time: Math.floor(Date.now() / 1000) };
435
+ await writeLog(repo, [...(await readLog(repo)), entry]);
436
+ return { id, branch: plan.branch, oldTip: plan.oldTip, newTip: plan.newTip };
437
+ }
438
+
439
+ /** Edits git-tm made, newest first, with whether each can still be undone in place. */
440
+ export async function listBackups(repo) {
441
+ const refs = await tryRun(repo, ["for-each-ref", "--format=%(refname)%00%(objectname)", BACKUP_PREFIX]);
442
+ const present = new Map();
443
+ for (const line of (refs || "").split("\n")) {
444
+ const [name, oid] = line.split("\0");
445
+ if (name) present.set(name.slice(BACKUP_PREFIX.length), oid);
446
+ }
447
+ // One lookup per branch, not per log entry (the log holds up to MAX_LOG entries).
448
+ const tips = new Map();
449
+ const tipOf = async (branch) => {
450
+ if (!tips.has(branch)) tips.set(branch, await branchTip(repo, branch));
451
+ return tips.get(branch);
452
+ };
453
+ const out = [];
454
+ for (const e of (await readLog(repo)).reverse()) {
455
+ if (present.get(e.id) !== e.oldTip) continue;
456
+ const current = await tipOf(e.branch);
457
+ out.push({ ...e, current, canUndo: current === e.newTip });
458
+ }
459
+ return out;
460
+ }
461
+
462
+ /**
463
+ * Undo an edit. By default the branch moves back to where it was before the edit (and that undo
464
+ * is itself logged, so it can be undone too). With `newBranch`, the old timeline is restored as a
465
+ * new branch instead, which also works when the original branch has moved on since.
466
+ */
467
+ export async function undoEdit(repo, id, { newBranch } = {}) {
468
+ if (typeof id !== "string" || !ID.test(id)) fail("Invalid backup id");
469
+ await assertIdle(repo);
470
+ const entry = (await readLog(repo)).find((e) => e.id === id);
471
+ if (!entry) fail("No such edit", 404);
472
+ const backup = await tryRun(repo, ["rev-parse", "--verify", "--quiet", `${BACKUP_PREFIX}${id}^{commit}`]);
473
+ if (!backup || backup.trim() !== entry.oldTip) fail("The backup for this edit is gone", 404);
474
+
475
+ if (newBranch !== undefined && newBranch !== null && newBranch !== "") {
476
+ if (typeof newBranch !== "string" || newBranch.startsWith("-") || newBranch.length > 255) fail("Invalid branch name");
477
+ try {
478
+ await run(repo, ["check-ref-format", "--branch", newBranch]);
479
+ } catch {
480
+ fail(`Invalid branch name: ${newBranch.slice(0, 80)}`);
481
+ }
482
+ if (await branchTip(repo, newBranch)) fail(`A branch named ${newBranch} already exists`, 409);
483
+ try {
484
+ await run(repo, ["update-ref", "-m", `git-tm: restore backup ${id}`, `refs/heads/${newBranch}`, entry.oldTip, ""]);
485
+ } catch (e) {
486
+ fail(`Couldn't create ${newBranch}: ${e.message}`, 409);
487
+ }
488
+ return { branch: newBranch, newTip: entry.oldTip };
489
+ }
490
+
491
+ const current = await branchTip(repo, entry.branch);
492
+ if (current !== entry.newTip) {
493
+ fail(`${entry.branch} has moved since this edit. Restore the old timeline as a new branch instead.`, 409);
494
+ }
495
+ const [a, b] = await Promise.all([readCommit(repo, entry.newTip), readCommit(repo, entry.oldTip)]);
496
+ const undoId = newId();
497
+ await createBackup(repo, undoId, entry.newTip);
498
+ try {
499
+ await moveBranch(repo, {
500
+ branch: entry.branch,
501
+ oldTip: entry.newTip,
502
+ newTip: entry.oldTip,
503
+ treePreserving: a.tree === b.tree,
504
+ label: `git-tm: undo ${id} (backup ${undoId})`,
505
+ });
506
+ } catch (e) {
507
+ await removeBackup(repo, undoId);
508
+ throw e;
509
+ }
510
+ const undo = { id: undoId, branch: entry.branch, op: "undo", summary: `Undo: ${entry.summary}`, oldTip: entry.newTip, newTip: entry.oldTip, time: Math.floor(Date.now() / 1000) };
511
+ await writeLog(repo, [...(await readLog(repo)), undo]);
512
+ return { id: undoId, branch: entry.branch, newTip: entry.oldTip };
513
+ }
package/src/git.js CHANGED
@@ -27,8 +27,14 @@ export class GitError extends Error {
27
27
  }
28
28
  }
29
29
 
30
- /** Run git and resolve with stdout: a string, or with `raw` a Buffer that has `truncated` set. */
31
- export function git(cwd, args, { raw = false, input, maxBytes = 64 * MB, timeout = 60_000 } = {}) {
30
+ /**
31
+ * Run git and resolve with stdout: a string, or with `raw` a Buffer that has `truncated` set.
32
+ * `env` adds environment variables (for example GIT_AUTHOR_* for commit-tree).
33
+ * `allowExit` lists non-zero exit codes that are results rather than failures: for those
34
+ * (and for 0) it resolves with `{ stdout, code }` instead of a plain string. `git merge-tree
35
+ * --write-tree` uses exit code 1 to report conflicts, with the details on stdout.
36
+ */
37
+ export function git(cwd, args, { raw = false, input, maxBytes = 64 * MB, timeout = 60_000, env, allowExit } = {}) {
32
38
  return new Promise((resolve, reject) => {
33
39
  const child = spawn("git", [...GLOBAL_ARGS, ...args], {
34
40
  cwd,
@@ -39,6 +45,7 @@ export function git(cwd, args, { raw = false, input, maxBytes = 64 * MB, timeout
39
45
  GIT_OPTIONAL_LOCKS: "0",
40
46
  GIT_PAGER: "cat",
41
47
  LC_ALL: "C",
48
+ ...env,
42
49
  },
43
50
  });
44
51
  const out = [];
@@ -71,6 +78,9 @@ export function git(cwd, args, { raw = false, input, maxBytes = 64 * MB, timeout
71
78
  clearTimeout(timer);
72
79
  if (timedOut) return reject(new GitError(`git ${args[0]} timed out`, 504));
73
80
  const buf = Buffer.concat(out);
81
+ if (allowExit && (code === 0 || allowExit.includes(code))) {
82
+ return resolve({ stdout: buf.toString("utf8"), code });
83
+ }
74
84
  if (code !== 0 && !truncated) {
75
85
  const msg = Buffer.concat(err).toString().trim().split("\n").pop() || `git ${args[0]} failed`;
76
86
  return reject(new GitError(msg.replace(/^(fatal|error): /, ""), 400));
@@ -88,7 +98,7 @@ const tryGit = (cwd, args, opts) => git(cwd, args, opts).catch(() => null);
88
98
  // ---------------------------------------------------------------- validation
89
99
 
90
100
  /** User supplied revision: never let it be parsed as an option. */
91
- function checkRev(rev) {
101
+ export function checkRev(rev) {
92
102
  if (typeof rev !== "string" || !rev || rev.length > 512 || rev.startsWith("-") || /[\s\x00-\x1f\x7f]/.test(rev)) {
93
103
  throw new GitError(`Invalid revision: ${String(rev).slice(0, 80)}`, 400);
94
104
  }
package/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // Public API. The CLI is src/cli.js; everything here can be imported as `git-tm`.
2
2
  export { openRepo, git, GitError, WORKTREE, webUrl } from "./git.js";
3
- export { createServer, listen } from "./server.js";
3
+ export { createServer, createApiHandler, listen } from "./server.js";
4
+ export { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
4
5
  export { createLayout, layout } from "./public/js/graph.js";
@@ -0,0 +1,30 @@
1
+ // Re-listen on one exact port (used by the CLI's "r" reload). Internal: not in package.json exports.
2
+
3
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
4
+
5
+ /**
6
+ * Listen on `port` and nothing else, retrying while it is still in use: the old server's socket can take
7
+ * a moment to be released, or another program can grab the port in the gap. Rejects with the last error.
8
+ */
9
+ export async function listenAgain(server, port, host, { tries = 10, delay = 200 } = {}) {
10
+ for (let i = 1; ; i++) {
11
+ try {
12
+ return await new Promise((resolve, reject) => {
13
+ const onError = (err) => {
14
+ server.off("listening", onListening);
15
+ reject(err);
16
+ };
17
+ const onListening = () => {
18
+ server.off("error", onError);
19
+ resolve(server.address().port);
20
+ };
21
+ server.once("error", onError);
22
+ server.once("listening", onListening);
23
+ server.listen(port, host);
24
+ });
25
+ } catch (err) {
26
+ if (err.code !== "EADDRINUSE" || i >= tries) throw err;
27
+ await wait(delay);
28
+ }
29
+ }
30
+ }
package/src/paths.js ADDED
@@ -0,0 +1,21 @@
1
+ // Comparing file system paths that may be spelled differently but name the same folder:
2
+ // symlinks (macOS /tmp is /private/tmp) and Windows drive-letter or name casing (c:\ vs C:\).
3
+ // Internal: not part of the package's public exports.
4
+
5
+ import { realpath } from "node:fs/promises";
6
+ import path from "node:path";
7
+
8
+ /** The canonical form of a path: symlinks resolved when the path exists, otherwise just resolved. */
9
+ export async function canonicalPath(p) {
10
+ try {
11
+ return await realpath(p);
12
+ } catch {
13
+ return path.resolve(p);
14
+ }
15
+ }
16
+
17
+ /** Whether two canonical paths are the same. Windows file systems ignore case. */
18
+ export function samePath(a, b, platform = process.platform) {
19
+ const norm = (p) => (platform === "win32" ? path.win32.normalize(p).toLowerCase() : p);
20
+ return norm(a) === norm(b);
21
+ }