git-tm 1.1.2 → 2.0.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.
@@ -0,0 +1,384 @@
1
+ // Edit mode UI (`git tm --edit`): change a commit, preview the alternate timeline, apply, undo.
2
+ // The server does all the work and the safety checks; this module only collects input and
3
+ // shows what will happen before anything changes.
4
+
5
+ import { api, html, $, short, toast, relTime, fullDate, errorBox, loading } from "./ui.js";
6
+
7
+ const OPS = {
8
+ reword: { label: "Reword", desc: "Change the commit message." },
9
+ author: { label: "Change author", desc: "Change who wrote it, or when." },
10
+ date: { label: "Change date", desc: "Change when this commit was authored." },
11
+ squash: { label: "Squash into parent", desc: "Fold this commit into the one before it." },
12
+ drop: { label: "Drop", desc: "Remove this commit and its changes." },
13
+ revert: { label: "Revert", desc: "Add a new commit that undoes this one. Nothing is rewritten." },
14
+ };
15
+
16
+ const TREE_CHANGING = new Set(["drop", "revert"]);
17
+ const STATUS = { A: "added", D: "deleted", M: "modified", R: "renamed", C: "copied", T: "modified" };
18
+
19
+ function gitAtLeast(version, major, minor) {
20
+ const m = String(version || "").match(/(\d+)\.(\d+)/);
21
+ return Boolean(m) && (Number(m[1]) > major || (Number(m[1]) === major && Number(m[2]) >= minor));
22
+ }
23
+
24
+ /** Why an edit can't be used on this commit, or "" if it can. */
25
+ export function disabledReason(op, commit, { gitVersion, branches }) {
26
+ if (!branches.length) return "Not on a local branch";
27
+ const parents = commit.parents.length;
28
+ if ((op === "squash" || op === "drop" || op === "revert") && parents === 0) return "The first commit";
29
+ if ((op === "squash" || op === "drop" || op === "revert") && parents > 1) return "Merge commit";
30
+ if (TREE_CHANGING.has(op) && !gitAtLeast(gitVersion, 2, 40)) return "Needs Git 2.40+";
31
+ return "";
32
+ }
33
+
34
+ function dialogEl() {
35
+ let dlg = document.getElementById("edit-dialog");
36
+ if (!dlg) {
37
+ dlg = document.createElement("dialog");
38
+ dlg.id = "edit-dialog";
39
+ dlg.className = "edit-dialog";
40
+ dlg.setAttribute("aria-labelledby", "edit-title");
41
+ document.body.append(dlg);
42
+ }
43
+ return dlg;
44
+ }
45
+
46
+ /** Open the edit dialog for a commit (from the commit detail pane). */
47
+ export async function openEdit(app, commit) {
48
+ const dlg = dialogEl();
49
+ const s = { step: "choose", op: null, branch: null, branches: [], fields: {}, preview: null, error: null, busy: false, confirmed: false };
50
+
51
+ // Attach handlers first, so even the error view below (with its Close button) works.
52
+ // They only call function declarations further down, which are hoisted.
53
+ dlg.onclick = (e) => {
54
+ if (e.target === dlg) return dlg.close(); // backdrop
55
+ const opBtn = e.target.closest("[data-op]");
56
+ if (opBtn && !opBtn.disabled) return startForm(opBtn.dataset.op);
57
+ const act = e.target.closest("[data-act]")?.dataset.act;
58
+ if (act === "close") dlg.close();
59
+ else if (act === "back") {
60
+ s.step = "choose";
61
+ drawChoose();
62
+ } else if (act === "back-form") {
63
+ s.step = "form";
64
+ drawForm();
65
+ } else if (act === "preview") preview();
66
+ else if (act === "apply") apply();
67
+ };
68
+ dlg.onchange = (e) => {
69
+ const k = e.target.dataset?.field;
70
+ if (k === "confirm") {
71
+ s.confirmed = e.target.checked;
72
+ const btn = $('[data-act="apply"]', dlg);
73
+ if (btn) btn.disabled = !s.confirmed;
74
+ } else if (k === "changeDate") {
75
+ readFields();
76
+ drawForm();
77
+ }
78
+ };
79
+
80
+ dlg.innerHTML = String(loading("Checking branches"));
81
+ if (!dlg.open) dlg.showModal();
82
+ try {
83
+ const res = await api("contains", { rev: commit.hash });
84
+ s.branches = res.branches;
85
+ } catch (err) {
86
+ dlg.innerHTML = String(html`${errorBox(err)}<div class="edit-actions"><button class="btn" data-act="close">Close</button></div>`);
87
+ return;
88
+ }
89
+ s.branch = s.branches.includes(app.repo.branch) ? app.repo.branch : s.branches[0] || null;
90
+
91
+ function header(title) {
92
+ return html`<div class="edit-head">
93
+ <h2 id="edit-title">${title}</h2>
94
+ <span class="sha-pill" title="${commit.hash}">${short(commit.hash)}</span>
95
+ <span class="edit-subject">${commit.subject}</span>
96
+ </div>`;
97
+ }
98
+
99
+ function branchPicker() {
100
+ if (s.branches.length <= 1) return s.branch ? html`<p class="muted small">On branch <strong>${s.branch}</strong></p>` : "";
101
+ return html`<label class="edit-field"><span>Branch to change</span>
102
+ <select data-field="branch">${s.branches.map((b) => html`<option value="${b}" ${b === s.branch ? "selected" : ""}>${b}</option>`)}</select></label>`;
103
+ }
104
+
105
+ function drawChoose() {
106
+ const ctx = { gitVersion: app.repo.gitVersion, branches: s.branches };
107
+ dlg.innerHTML = String(html`
108
+ ${header("Edit commit")}
109
+ <div class="edit-ops">${Object.entries(OPS).map(([op, o]) => {
110
+ const why = disabledReason(op, commit, ctx);
111
+ return html`<button class="edit-op" data-op="${op}" ${why ? "disabled" : ""}>
112
+ <strong>${o.label}</strong><span>${why || o.desc}</span></button>`;
113
+ })}</div>
114
+ <p class="muted small">You'll see a preview of the new timeline before anything changes, and every edit can be undone.</p>
115
+ <div class="edit-actions"><button class="btn" data-act="close">Cancel</button></div>`);
116
+ }
117
+
118
+ function drawForm() {
119
+ const f = s.fields;
120
+ let body = "";
121
+ if (s.op === "reword" || s.op === "squash") {
122
+ body = html`<label class="edit-field"><span>${s.op === "squash" ? "Message for the combined commit" : "Commit message"}</span>
123
+ <textarea data-field="message" rows="8" spellcheck="true">${f.message ?? ""}</textarea></label>`;
124
+ } else if (s.op === "author") {
125
+ body = html`<label class="edit-field"><span>Name</span><input data-field="name" value="${f.name ?? ""}" autocomplete="off" /></label>
126
+ <label class="edit-field"><span>Email</span><input data-field="email" value="${f.email ?? ""}" autocomplete="off" /></label>
127
+ <label class="edit-check"><input type="checkbox" data-field="changeDate" ${f.changeDate ? "checked" : ""} /> Change the date too</label>
128
+ ${f.changeDate ? html`<label class="edit-field"><span>Date</span><input type="datetime-local" data-field="date" value="${f.date ?? ""}" step="1" /></label>` : ""}`;
129
+ } else if (s.op === "date") {
130
+ body = html`<label class="edit-field"><span>Author date</span><input type="datetime-local" data-field="date" value="${f.date ?? ""}" step="1" /></label>`;
131
+ } else if (s.op === "drop") {
132
+ body = html`<p>This removes <strong>${commit.subject}</strong> and its changes from the branch. Later commits are kept and re-applied without it.</p>`;
133
+ } else if (s.op === "revert") {
134
+ body = html`<p>This adds a new commit on top of the branch that undoes <strong>${commit.subject}</strong>. Existing commits stay exactly as they are, so it's safe even if they're already pushed.</p>`;
135
+ }
136
+ dlg.innerHTML = String(html`
137
+ ${header(OPS[s.op].label)}
138
+ ${branchPicker()}
139
+ <div class="edit-form">${body}</div>
140
+ ${s.error ? errorBox(s.error) : ""}
141
+ <div class="edit-actions">
142
+ <button class="btn" data-act="back">Back</button>
143
+ <span class="spacer"></span>
144
+ <button class="btn btn-primary" data-act="preview" ${s.busy ? "disabled" : ""}>${s.busy ? "Working…" : "Preview"}</button>
145
+ </div>`);
146
+ $("textarea, input:not([type=checkbox])", dlg)?.focus();
147
+ }
148
+
149
+ function timelineRows(plan) {
150
+ const rows = [];
151
+ for (const r of plan.rewritten) {
152
+ rows.push(html`<li class="${r.new ? "" : "dropped"}">
153
+ <code class="old">${short(r.old)}</code><span class="arrow">${r.new ? "→" : "×"}</span>
154
+ <code class="new">${r.new ? short(r.new) : "removed"}</code><span class="subj">${r.subject}</span></li>`);
155
+ }
156
+ for (const a of plan.added) {
157
+ rows.push(html`<li class="added"><code class="old">new</code><span class="arrow">+</span><code class="new">${short(a.new)}</code><span class="subj">${a.subject}</span></li>`);
158
+ }
159
+ return rows;
160
+ }
161
+
162
+ function drawPreview(files) {
163
+ const p = s.preview.plan;
164
+ const pushed = p.pushed.length > 0 && p.type !== "revert";
165
+ const fileNote = files === null
166
+ ? html`<span class="muted small">Loading file changes…</span>`
167
+ : files.files.length
168
+ ? html`<div class="edit-files">${files.files.slice(0, 12).map((f) => html`<div><span class="status status-${STATUS[f.status] || "modified"}">${f.status}</span><code>${f.path}</code><span class="add">+${f.additions}</span><span class="del">−${f.deletions}</span></div>`)}${files.files.length > 12 ? html`<div class="muted small">and ${files.files.length - 12} more</div>` : ""}</div>`
169
+ : html`<p class="muted small">No file changes: only commit details change, so your working tree isn't touched.</p>`;
170
+ dlg.innerHTML = String(html`
171
+ ${header("Preview the new timeline")}
172
+ <p class="edit-summary">${p.summary}</p>
173
+ <ul class="edit-timeline">${timelineRows(p)}</ul>
174
+ <h3 class="edit-sub">Files at the tip of ${p.branch}</h3>
175
+ ${fileNote}
176
+ ${p.warnings.filter((w) => !w.startsWith("Paradox")).map((w) => html`<p class="edit-warn">${w}</p>`)}
177
+ ${pushed ? html`<div class="edit-danger">
178
+ <strong>These commits are already on ${p.pushed.join(", ")}.</strong>
179
+ <p>Rewriting pushed history means a force-push, and anyone who already pulled these commits will have a different history from you. It can get messy. Revert is the safe alternative.</p>
180
+ <label class="edit-check"><input type="checkbox" data-field="confirm" ${s.confirmed ? "checked" : ""} /> I understand this rewrites shared history</label>
181
+ </div>` : ""}
182
+ ${s.error ? errorBox(s.error) : ""}
183
+ <div class="edit-actions">
184
+ <button class="btn" data-act="back-form">Back</button>
185
+ <span class="spacer"></span>
186
+ <button class="btn btn-primary" data-act="apply" ${(pushed && !s.confirmed) || s.busy ? "disabled" : ""}>${s.busy ? "Applying…" : "Apply"}</button>
187
+ </div>`);
188
+ }
189
+
190
+ async function startForm(op) {
191
+ s.op = op;
192
+ s.error = null;
193
+ s.fields = {};
194
+ if (op === "reword") s.fields.message = commit.body ? `${commit.subject}\n\n${commit.body}` : commit.subject;
195
+ if (op === "author" || op === "date") {
196
+ const d = new Date(commit.date * 1000);
197
+ const local = new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
198
+ s.fields = { name: commit.author, email: commit.email, changeDate: op === "date", date: local };
199
+ }
200
+ if (op === "squash") {
201
+ try {
202
+ const parent = (await api("commit", { rev: commit.parents[0] })).commit;
203
+ const msg = (c) => (c.body ? `${c.subject}\n\n${c.body}` : c.subject);
204
+ s.fields.message = `${msg(parent)}\n\n${msg(commit)}`;
205
+ } catch {
206
+ s.fields.message = commit.subject;
207
+ }
208
+ }
209
+ s.step = "form";
210
+ drawForm();
211
+ }
212
+
213
+ function readFields() {
214
+ for (const el of dlg.querySelectorAll("[data-field]")) {
215
+ const k = el.dataset.field;
216
+ if (k === "branch") s.branch = el.value;
217
+ else if (k === "confirm") s.confirmed = el.checked;
218
+ else s.fields[k] = el.type === "checkbox" ? el.checked : el.value;
219
+ }
220
+ }
221
+
222
+ async function preview() {
223
+ readFields();
224
+ const f = s.fields;
225
+ const body = { op: s.op === "date" ? "author" : s.op, commit: commit.hash, branch: s.branch };
226
+ if (s.op === "reword" || s.op === "squash") body.message = f.message;
227
+ if (s.op === "author" || s.op === "date") {
228
+ body.author = { name: f.name, email: f.email };
229
+ if ((s.op === "date" || f.changeDate) && f.date) {
230
+ const t = new Date(f.date).getTime();
231
+ if (Number.isNaN(t)) {
232
+ s.error = new Error("That date isn't valid");
233
+ return drawForm();
234
+ }
235
+ body.author.date = Math.floor(t / 1000);
236
+ } else if (s.op === "date") {
237
+ s.error = new Error("Pick a date");
238
+ return drawForm();
239
+ }
240
+ }
241
+ s.busy = true;
242
+ s.error = null;
243
+ drawForm();
244
+ try {
245
+ s.preview = await api("edit/preview", {}, { method: "POST", body });
246
+ s.confirmed = false;
247
+ s.busy = false;
248
+ s.step = "preview";
249
+ drawPreview(null);
250
+ const p = s.preview.plan;
251
+ const files = await api("files", { from: p.oldTip, to: p.newTip }).catch(() => ({ files: [] }));
252
+ if (s.step === "preview" && s.preview?.plan === p) drawPreview(files);
253
+ s.files = files;
254
+ } catch (err) {
255
+ s.busy = false;
256
+ s.error = err.conflicts?.length ? new Error(`${err.message} Conflicting files: ${err.conflicts.join(", ")}`) : err;
257
+ drawForm();
258
+ }
259
+ }
260
+
261
+ async function apply() {
262
+ readFields();
263
+ const p = s.preview.plan;
264
+ s.busy = true;
265
+ s.error = null;
266
+ drawPreview(s.files ?? null);
267
+ try {
268
+ const res = await api("edit/apply", {}, { method: "POST", body: { token: s.preview.token, allowPushed: s.confirmed } });
269
+ dlg.close();
270
+ await app.afterEdit();
271
+ toast(p.type === "revert" ? "Revert commit added" : "History rewritten. A backup was saved.", "success", 8000, {
272
+ label: "Undo",
273
+ onClick: () => undo(app, res.id),
274
+ });
275
+ // Show the commit that took this one's place.
276
+ const replacement = p.rewritten.find((r) => r.old === commit.hash)?.new || (p.type === "revert" ? p.newTip : null);
277
+ app.navigate(replacement ? `#/commit/${replacement}` : "#/");
278
+ } catch (err) {
279
+ s.busy = false;
280
+ s.error = err;
281
+ drawPreview(s.files ?? null);
282
+ }
283
+ }
284
+
285
+ drawChoose();
286
+ }
287
+
288
+ /** Undo an edit by id, with a toast for the result. */
289
+ export async function undo(app, id, newBranch) {
290
+ try {
291
+ const res = await api("edit/undo", {}, { method: "POST", body: { id, newBranch } });
292
+ await app.afterEdit();
293
+ // An open commit pane would otherwise keep showing the undone (now orphaned) commit.
294
+ if (location.hash.startsWith("#/commit/")) app.navigate(`#/commit/${res.newTip}`);
295
+ toast(newBranch ? `Old timeline restored as ${res.branch}` : "Timeline restored", "success");
296
+ return true;
297
+ } catch (err) {
298
+ toast(err.message, "error", 7000);
299
+ return false;
300
+ }
301
+ }
302
+
303
+ /** The "Edits by git-tm" section in the Reflog view: every edit with Undo, or restore as a new branch. */
304
+ export function mountBackups(container, app) {
305
+ let restoring = null;
306
+
307
+ async function render() {
308
+ let backups;
309
+ try {
310
+ backups = (await api("edit/backups")).backups;
311
+ } catch (err) {
312
+ container.innerHTML = String(errorBox(err));
313
+ return;
314
+ }
315
+ if (!backups.length) {
316
+ container.innerHTML = String(html`<div class="edit-backups-empty muted small">Edits you make in edit mode show up here, ready to undo.</div>`);
317
+ return;
318
+ }
319
+ const cleanSummary = (b) => {
320
+ const s = b.summary || b.op;
321
+ return b.op === "undo" ? s.replace(/^Undo:\s*/i, "") : s;
322
+ };
323
+ const opCls = (op) => (op === "undo" ? "undo" : op === "drop" ? "drop" : op === "revert" ? "revert" : "edit");
324
+
325
+ container.innerHTML = String(html`
326
+ <h2 class="edit-backups-title">Edits by git-tm</h2>
327
+ <ul class="edit-backups-list">${backups.slice(0, 20).map((b) => html`<li>
328
+ <div class="edit-backup-main">
329
+ <div class="edit-backup-top">
330
+ <span class="edit-backup-op op-${opCls(b.op)}">${b.op}</span>
331
+ <span class="edit-backup-sum">${cleanSummary(b)}</span>
332
+ </div>
333
+ <div class="edit-backup-meta muted small" title="${fullDate(b.time)}">
334
+ <span>${b.branch}</span>
335
+ <span>·</span>
336
+ <span>${relTime(b.time)}</span>
337
+ ${b.oldTip && b.newTip ? html`<span>·</span>
338
+ <a class="sha-link" href="#/commit/${b.oldTip}" title="Before: ${b.oldTip}">${b.oldTip.slice(0, 6)}</a>
339
+ <span>→</span>
340
+ <a class="sha-link" href="#/commit/${b.newTip}" title="After: ${b.newTip}">${b.newTip.slice(0, 6)}</a>` : ""}
341
+ </div>
342
+ </div>
343
+ <div class="edit-backup-actions">
344
+ ${b.canUndo
345
+ ? html`<button class="btn btn-sm" data-undo="${b.id}">${b.op === "undo" ? "Redo" : "Undo"}</button>`
346
+ : restoring === b.id
347
+ ? html`<form class="edit-restore" data-restore="${b.id}">
348
+ <input name="branch" value="restore/${b.branch}-${b.id.slice(-4)}" aria-label="New branch name" autocomplete="off" />
349
+ <button class="btn btn-sm btn-primary">Create</button>
350
+ <button type="button" class="btn btn-sm btn-ghost" data-restore-cancel>Cancel</button></form>`
351
+ : html`<button class="btn btn-sm btn-ghost" data-restore-open="${b.id}" title="${b.branch} has moved on — restore the old tip as a new branch">Restore as branch…</button>`}
352
+ </div></li>`)}</ul>`);
353
+ }
354
+
355
+ container.onclick = async (e) => {
356
+ const u = e.target.closest("[data-undo]");
357
+ if (u) {
358
+ u.disabled = true;
359
+ if (!(await undo(app, u.dataset.undo))) u.disabled = false;
360
+ return;
361
+ }
362
+ const open = e.target.closest("[data-restore-open]");
363
+ if (open) {
364
+ restoring = open.dataset.restoreOpen;
365
+ await render();
366
+ $(".edit-restore input", container)?.select();
367
+ return;
368
+ }
369
+ if (e.target.closest("[data-restore-cancel]")) {
370
+ restoring = null;
371
+ await render();
372
+ }
373
+ };
374
+ container.onsubmit = async (e) => {
375
+ const form = e.target.closest("[data-restore]");
376
+ if (!form) return;
377
+ e.preventDefault();
378
+ const name = form.elements.branch.value.trim();
379
+ if (await undo(app, form.dataset.restore, name)) restoring = null;
380
+ };
381
+
382
+ render();
383
+ }
384
+