git-tm 1.2.0 → 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.
@@ -1,4 +1,4 @@
1
- import { api, html, raw, $, $$, icons, toast, storage, WORKTREE } from "./ui.js";
1
+ import { api, html, raw, $, $$, icons, toast, storage, copyText, openContextMenu, WORKTREE } from "./ui.js";
2
2
  import { createHistory } from "./history.js";
3
3
  import { createCompare } from "./compare.js";
4
4
  import { createReflog } from "./reflog.js";
@@ -36,6 +36,21 @@ const app = {
36
36
  renderRepo();
37
37
  renderSidebar();
38
38
  },
39
+
40
+ /** After git-tm itself changed history: refresh every view without the "changed on disk" banner. */
41
+ async afterEdit() {
42
+ await app.reloadRepo();
43
+ try {
44
+ fingerprint = (await api("state")).fingerprint;
45
+ } catch {
46
+ /* the next poll catches up */
47
+ }
48
+ $("#banner").hidden = true;
49
+ app.views.history.reload();
50
+ app.views.reflog.invalidate();
51
+ app.views.insights.invalidate();
52
+ if (app.current === "reflog") app.views.reflog.load();
53
+ },
39
54
  };
40
55
 
41
56
  // ------------------------------------------------------------------ search
@@ -92,8 +107,32 @@ function renderRepo() {
92
107
  const r = app.repo;
93
108
  const where = r.branch ?? (r.head ? `detached at ${r.head.slice(0, 7)}` : "no commits yet");
94
109
  $("#repo").innerHTML = String(html`<span class="repo-name" title="${r.root}">${r.name}</span>
95
- <span class="repo-branch" title="Current branch">${raw(icons.branch)}${where}</span>`);
110
+ <span class="repo-branch" title="Current branch">${raw(icons.branch)}${where}</span>
111
+ ${r.edit ? html`<span class="edit-badge" title="Started with --edit: history can be changed. Every edit is backed up and can be undone.">Edit mode</span>` : ""}`);
96
112
  document.title = `${r.name} · Git Time Machine`;
113
+ const mb = $("#mode-banner");
114
+ if (mb) {
115
+ if (r.edit) {
116
+ mb.className = "mode-banner edit";
117
+ mb.hidden = false;
118
+ mb.innerHTML = String(html`<span><strong>Edit mode active</strong> — read-only protection is off. History can be rewritten here; every edit is previewed and backed up for Undo.</span>`);
119
+ mb.onclick = null;
120
+ } else {
121
+ const show = !storage.get("hide-edit-hint", false);
122
+ mb.className = "mode-banner";
123
+ mb.hidden = !show;
124
+ if (show && !mb.childElementCount) {
125
+ mb.innerHTML = String(html`<span><strong>Read-only mode</strong> — want to reword, squash, drop, or revert commits? Restart with <code>git-tm --edit</code></span>
126
+ <button class="icon-btn" data-act="dismiss-mode" title="Dismiss" aria-label="Dismiss">${raw(icons.close)}</button>`);
127
+ mb.onclick = (e) => {
128
+ if (e.target.closest("[data-act=dismiss-mode]")) {
129
+ mb.hidden = true;
130
+ storage.set("hide-edit-hint", true);
131
+ }
132
+ };
133
+ }
134
+ }
135
+ }
97
136
  }
98
137
 
99
138
  const collapsed = new Set(storage.get("collapsed", ["tags"]));
@@ -380,6 +419,27 @@ async function boot() {
380
419
  if (!$("#search").value && app.filter) app.setFilter(null);
381
420
  });
382
421
  $("#sidebar").addEventListener("click", onSidebarClick);
422
+ $("#sidebar").addEventListener("contextmenu", (e) => {
423
+ const item = e.target.closest("[data-ref]");
424
+ if (!item || !item.dataset.ref) return;
425
+ const ref = item.dataset.ref;
426
+ const base = app.repo.branch || "HEAD";
427
+ openContextMenu(e, [
428
+ { label: "View history", icon: icons.history, onClick: () => app.setRef(ref) },
429
+ ref !== base
430
+ ? {
431
+ label: `Compare with ${base}`,
432
+ icon: icons.compare,
433
+ onClick: () => {
434
+ closeSidebar();
435
+ app.navigate(`#/compare/${encodeURIComponent(base)}...${encodeURIComponent(ref)}`);
436
+ },
437
+ }
438
+ : null,
439
+ "sep",
440
+ { label: "Copy ref name", icon: icons.copy, onClick: () => copyText(ref, "Ref name copied") },
441
+ ]);
442
+ });
383
443
  $("#sidebar").addEventListener("keydown", (e) => {
384
444
  if (e.key === "Enter" && e.target.matches("[data-ref]")) app.setRef(e.target.dataset.ref || null);
385
445
  });
@@ -1,6 +1,7 @@
1
1
  // Reflog view: recent HEAD movements and read-only recovery of lost commits.
2
2
 
3
3
  import { api, html, raw, $, avatar, refBadges, relTime, fullDate, short, plural, icons, copyText, loading, errorBox, empty } from "./ui.js";
4
+ import { mountBackups } from "./edit.js";
4
5
 
5
6
  const PAGE = 200;
6
7
 
@@ -50,6 +51,7 @@ export function createReflog(app) {
50
51
  entries = [];
51
52
  done = true;
52
53
  expanded.clear();
54
+ backupsEl = null;
53
55
  el.innerHTML = String(html`
54
56
  <div class="page-head">
55
57
  <h1>Reflog</h1>
@@ -136,10 +138,34 @@ export function createReflog(app) {
136
138
  <h1>Reflog</h1>
137
139
  <p class="muted">Recent <code>HEAD</code> movements — read-only.</p>
138
140
  </div>
141
+ ${backupsSlot()}
139
142
  ${empty("No reflog entries", "Git records HEAD movements here as you commit, checkout, reset, or rebase.")}`);
143
+ mountSlot();
140
144
  return;
141
145
  }
142
146
 
147
+ drawFull();
148
+ }
149
+
150
+ // Edits made in edit mode, with Undo, shown above the reflog when git-tm runs with --edit.
151
+ // One element per load, moved into place on each redraw, so typing in the filter doesn't refetch it.
152
+ let backupsEl = null;
153
+ function backupsSlot() {
154
+ return app.repo?.edit ? html`<div id="edit-backups"></div>` : "";
155
+ }
156
+
157
+ function mountSlot() {
158
+ const slot = $("#edit-backups", el);
159
+ if (!slot) return;
160
+ if (!backupsEl) {
161
+ backupsEl = document.createElement("section");
162
+ backupsEl.className = "edit-backups";
163
+ mountBackups(backupsEl, app);
164
+ }
165
+ slot.replaceWith(backupsEl);
166
+ }
167
+
168
+ function drawFull() {
143
169
  const lostCount = entries.filter((e) => e.orphaned).length;
144
170
  const list = filtered();
145
171
  const hadFocus = document.activeElement?.id === "reflog-filter";
@@ -150,6 +176,7 @@ export function createReflog(app) {
150
176
  <h1>Reflog</h1>
151
177
  <p class="muted">Recent <code>HEAD</code> movements — inspect or recover commits lost to <code>reset</code>, <code>rebase</code>, <code>amend</code>, or deleted branches.</p>
152
178
  </div>
179
+ ${backupsSlot()}
153
180
  <div class="reflog-bar">
154
181
  <div class="seg" role="group" aria-label="Filter reflog">
155
182
  <button data-filter="all" aria-pressed="${!onlyLost}">All <span class="seg-count">${entries.length}</span></button>
@@ -164,6 +191,8 @@ export function createReflog(app) {
164
191
  : empty(onlyLost ? "No lost commits in reflog" : "No matching reflog entries", onlyLost ? "Every recent HEAD commit is reachable from a branch or tag." : "Try clearing the filter.")}
165
192
  ${!done ? html`<div class="reflog-more"><button class="btn" data-act="more">Load older entries</button></div>` : ""}`);
166
193
 
194
+ mountSlot();
195
+
167
196
  if (hadFocus) {
168
197
  const inp = $("#reflog-filter", el);
169
198
  if (inp) {
@@ -4,7 +4,7 @@ export const WORKTREE = "WORKTREE";
4
4
 
5
5
  const avatarMap = Object.create(null);
6
6
 
7
- export async function api(path, params = {}, { method = "GET" } = {}) {
7
+ export async function api(path, params = {}, { method = "GET", body } = {}) {
8
8
  const qs = new URLSearchParams();
9
9
  for (const [k, v] of Object.entries(params)) {
10
10
  if (v !== undefined && v !== null && v !== "" && v !== false) qs.set(k, v === true ? "1" : String(v));
@@ -13,7 +13,9 @@ export async function api(path, params = {}, { method = "GET" } = {}) {
13
13
  const url = `/api/${path}${query ? `?${query}` : ""}`;
14
14
  let res;
15
15
  try {
16
- res = await fetch(url, { method, headers: method === "GET" ? {} : { "x-git-tm": "1" } });
16
+ const headers = method === "GET" ? {} : { "x-git-tm": "1" };
17
+ if (body !== undefined) headers["content-type"] = "application/json";
18
+ res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
17
19
  } catch {
18
20
  // No HTTP response. Either git-tm stopped, or the browser cancelled the
19
21
  // request (ad blockers do this to URLs that look like tracking). Ask the
@@ -31,7 +33,7 @@ export async function api(path, params = {}, { method = "GET" } = {}) {
31
33
  } catch {
32
34
  throw new Error(`Request failed (${res.status})`);
33
35
  }
34
- if (!res.ok) throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status });
36
+ if (!res.ok) throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status, conflicts: data.conflicts });
35
37
  if (data && data.avatars) Object.assign(avatarMap, data.avatars);
36
38
  return data;
37
39
  }
@@ -176,18 +178,33 @@ export const icons = {
176
178
 
177
179
  // ------------------------------------------------------------------ toasts
178
180
 
179
- export function toast(message, type = "info", ms = 3500) {
181
+ /** Show a toast. `action` ({ label, onClick }) adds a button, for example Undo. */
182
+ export function toast(message, type = "info", ms = 3500, action = null) {
180
183
  const box = document.getElementById("toasts");
181
184
  const el = document.createElement("div");
182
185
  el.className = `toast toast-${type}`;
183
186
  el.setAttribute("role", type === "error" ? "alert" : "status");
184
- el.textContent = message;
185
- box.append(el);
186
- requestAnimationFrame(() => el.classList.add("in"));
187
- setTimeout(() => {
187
+ const text = document.createElement("span");
188
+ text.textContent = message;
189
+ el.append(text);
190
+ const close = () => {
188
191
  el.classList.remove("in");
189
192
  setTimeout(() => el.remove(), 250);
190
- }, ms);
193
+ };
194
+ if (action) {
195
+ el.classList.add("has-action");
196
+ const btn = document.createElement("button");
197
+ btn.className = "btn btn-sm";
198
+ btn.textContent = action.label;
199
+ btn.addEventListener("click", () => {
200
+ close();
201
+ action.onClick();
202
+ });
203
+ el.append(btn);
204
+ }
205
+ box.append(el);
206
+ requestAnimationFrame(() => el.classList.add("in"));
207
+ setTimeout(close, ms);
191
208
  }
192
209
 
193
210
  export async function copyText(text, label = "Copied") {
@@ -226,3 +243,98 @@ export const storage = {
226
243
  } catch {}
227
244
  },
228
245
  };
246
+
247
+ // ------------------------------------------------------------------ context menu
248
+
249
+ let activeMenu = null;
250
+
251
+ export function closeContextMenu() {
252
+ if (!activeMenu) return;
253
+ activeMenu.cleanup();
254
+ activeMenu = null;
255
+ }
256
+
257
+ /**
258
+ * Show a floating context menu at the pointer location.
259
+ * items: Array<{ label, icon?, cls?, onClick } | "sep">
260
+ * anchorEl: where to show the menu when it was opened from the keyboard (defaults to the event target).
261
+ */
262
+ export function openContextMenu(e, items, anchorEl = null) {
263
+ if (typeof document === "undefined") return;
264
+ const list = items.filter(Boolean);
265
+ if (!list.length) return;
266
+ e.preventDefault();
267
+ closeContextMenu();
268
+
269
+ const menu = document.createElement("div");
270
+ menu.className = "ctx-menu";
271
+ menu.setAttribute("role", "menu");
272
+ const handlers = [];
273
+ menu.innerHTML = String(
274
+ html`${list.map((item) => {
275
+ if (item === "sep") return raw('<div class="ctx-sep" role="separator"></div>');
276
+ const idx = handlers.push(item.onClick) - 1;
277
+ return html`<button type="button" class="ctx-item${item.cls ? ` ${item.cls}` : ""}" role="menuitem" data-idx="${idx}">${item.icon ? raw(item.icon) : ""}<span>${item.label}</span></button>`;
278
+ })}`,
279
+ );
280
+ document.body.append(menu);
281
+
282
+ // Opened from the keyboard (Shift+F10 or the Menu key) there is no pointer position: anchor to the element.
283
+ const trigger = anchorEl || (e.target instanceof Element ? e.target : null);
284
+ const fromKeyboard = e.clientX === 0 && e.clientY === 0 && trigger;
285
+ const anchor = fromKeyboard ? trigger.getBoundingClientRect() : null;
286
+ const px = anchor ? anchor.left + Math.min(24, anchor.width / 2) : e.clientX;
287
+ const py = anchor ? anchor.bottom : e.clientY;
288
+ const rect = menu.getBoundingClientRect();
289
+ const x = Math.max(8, Math.min(px, window.innerWidth - rect.width - 8));
290
+ const y = Math.max(8, Math.min(py, window.innerHeight - rect.height - 8));
291
+ menu.style.left = `${x}px`;
292
+ menu.style.top = `${y}px`;
293
+
294
+ const onDown = (ev) => {
295
+ if (!menu.contains(ev.target)) closeContextMenu();
296
+ };
297
+ const onKey = (ev) => {
298
+ if (ev.key === "Escape") {
299
+ ev.preventDefault();
300
+ closeContextMenu();
301
+ return;
302
+ }
303
+ const btns = [...menu.querySelectorAll(".ctx-item")];
304
+ if (!btns.length) return;
305
+ if (ev.key === "ArrowDown" || ev.key === "ArrowUp") {
306
+ ev.preventDefault();
307
+ const i = btns.indexOf(document.activeElement);
308
+ const next = ev.key === "ArrowDown" ? (i + 1) % btns.length : (i - 1 + btns.length) % btns.length;
309
+ btns[next].focus();
310
+ }
311
+ };
312
+ const onScroll = () => closeContextMenu();
313
+ menu.addEventListener("click", (ev) => {
314
+ const btn = ev.target.closest("[data-idx]");
315
+ if (!btn) return;
316
+ const fn = handlers[Number(btn.dataset.idx)];
317
+ closeContextMenu();
318
+ fn?.();
319
+ });
320
+
321
+ document.addEventListener("pointerdown", onDown, true);
322
+ document.addEventListener("keydown", onKey, true);
323
+ window.addEventListener("scroll", onScroll, true);
324
+ window.addEventListener("resize", onScroll);
325
+
326
+ const returnFocus = document.activeElement;
327
+ if (fromKeyboard) menu.querySelector(".ctx-item")?.focus();
328
+
329
+ activeMenu = {
330
+ cleanup() {
331
+ const hadFocus = menu.contains(document.activeElement);
332
+ menu.remove();
333
+ if (hadFocus && returnFocus instanceof HTMLElement) returnFocus.focus({ preventScroll: true });
334
+ document.removeEventListener("pointerdown", onDown, true);
335
+ document.removeEventListener("keydown", onKey, true);
336
+ window.removeEventListener("scroll", onScroll, true);
337
+ window.removeEventListener("resize", onScroll);
338
+ },
339
+ };
340
+ }
package/src/server.js CHANGED
@@ -3,11 +3,12 @@
3
3
  // header so other websites cannot read the repository via DNS rebinding.
4
4
 
5
5
  import http from "node:http";
6
- import { createHash } from "node:crypto";
6
+ import { createHash, randomBytes } from "node:crypto";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { GitError } from "./git.js";
11
+ import { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
11
12
 
12
13
  const PUBLIC_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "public");
13
14
 
@@ -32,6 +33,8 @@ const CSP = [
32
33
  ].join("; ");
33
34
 
34
35
  const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
36
+ const MAX_BODY = 64 * 1024;
37
+ const PLAN_TTL = 10 * 60 * 1000;
35
38
 
36
39
  function md5(s) {
37
40
  return createHash("md5").update(s).digest("hex");
@@ -59,14 +62,22 @@ function attachAvatars(enabled, ...lists) {
59
62
  return map;
60
63
  }
61
64
 
62
- export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {}) {
65
+ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit = false, onEdit, onLog } = {}) {
63
66
  const staticCache = new Map();
64
67
  const checkHost = LOOPBACK.has(host);
68
+ // Changing history from another device is a different risk from reading it: edit mode is local only.
69
+ if (edit && !checkHost) throw new Error("Edit mode only works on a loopback host (127.0.0.1, localhost or ::1)");
70
+
71
+ // Previewed plans, by one-time token, so apply can only move a branch to a tip git-tm computed.
72
+ const plans = new Map();
73
+ const requireEdit = () => {
74
+ if (!edit) throw new GitError("Edit mode is off. Start git-tm with --edit to change history.", 403);
75
+ };
65
76
 
66
77
  const bool = (v) => v === "1" || v === "true";
67
78
 
68
79
  const routes = {
69
- "GET /api/repo": async () => ({ ...(await repo.info()), avatars }),
80
+ "GET /api/repo": async () => ({ ...(await repo.info()), avatars, edit }),
70
81
  "GET /api/state": async () => ({ fingerprint: await repo.fingerprint() }),
71
82
  "GET /api/history": async (q) => {
72
83
  const res = await repo.log({
@@ -119,6 +130,52 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
119
130
  await repo.fetch();
120
131
  return { ok: true };
121
132
  },
133
+ "GET /api/edit/backups": async () => {
134
+ requireEdit();
135
+ return { backups: await listBackups(repo) };
136
+ },
137
+ "POST /api/edit/preview": async (q, req) => {
138
+ requireEdit();
139
+ const body = await readJson(req);
140
+ const plan = await planEdit(repo, {
141
+ type: body.op,
142
+ commit: body.commit,
143
+ branch: body.branch || undefined,
144
+ message: body.message,
145
+ author: body.author,
146
+ });
147
+ const now = Date.now();
148
+ for (const [k, v] of plans) if (v.expires < now) plans.delete(k);
149
+ if (plans.size > 50) plans.delete(plans.keys().next().value);
150
+ const token = randomBytes(16).toString("hex");
151
+ plans.set(token, { plan, expires: now + PLAN_TTL });
152
+ return { token, plan };
153
+ },
154
+ "POST /api/edit/apply": async (q, req) => {
155
+ requireEdit();
156
+ const body = await readJson(req);
157
+ const entry = typeof body.token === "string" ? plans.get(body.token) : null;
158
+ if (!entry || entry.expires < Date.now()) throw new GitError("This preview has expired. Preview the edit again.", 400);
159
+ // A double click must not run the same edit twice (duplicate backups and log entries).
160
+ if (entry.busy) throw new GitError("This edit is already being applied.", 409);
161
+ entry.busy = true;
162
+ let result;
163
+ try {
164
+ result = await applyEdit(repo, entry.plan, { allowPushed: body.allowPushed === true });
165
+ } finally {
166
+ entry.busy = false; // a failed apply (for example, unconfirmed pushed commits) can be retried
167
+ }
168
+ plans.delete(body.token);
169
+ onEdit?.({ ...result, op: entry.plan.type, summary: entry.plan.summary, count: entry.plan.rewritten.length || entry.plan.added.length });
170
+ return result;
171
+ },
172
+ "POST /api/edit/undo": async (q, req) => {
173
+ requireEdit();
174
+ const body = await readJson(req);
175
+ const result = await undoEdit(repo, body.id, { newBranch: body.newBranch });
176
+ onEdit?.({ ...result, op: body.newBranch ? "restore" : "undo" });
177
+ return result;
178
+ },
122
179
  };
123
180
 
124
181
  async function serveStatic(res, pathname) {
@@ -146,7 +203,19 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
146
203
  res.end(body);
147
204
  }
148
205
 
206
+ // A broken logger must never fail a request, or get the same request logged twice by the error path.
207
+ const logRequest = (event) => {
208
+ if (!onLog || event.path === "/api/state") return;
209
+ try {
210
+ onLog(event);
211
+ } catch (err) {
212
+ console.error(`onLog failed: ${err?.stack || err}`);
213
+ }
214
+ };
215
+
149
216
  return http.createServer(async (req, res) => {
217
+ let apiUrl = null;
218
+ const started = onLog ? performance.now() : 0;
150
219
  try {
151
220
  if (checkHost) {
152
221
  const h = (req.headers.host || "").toLowerCase().replace(/:\d+$/, "");
@@ -157,21 +226,45 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
157
226
  if (req.method !== "GET" && req.method !== "HEAD") return send(res, 405, "Method not allowed");
158
227
  return await serveStatic(res, url.pathname);
159
228
  }
229
+ apiUrl = url;
160
230
  const route = routes[`${req.method} ${url.pathname}`];
161
231
  if (!route) return json(res, 404, { error: "Unknown endpoint" });
162
232
  // Simple CSRF guard: browsers will not send this custom header cross-origin without a preflight.
163
233
  if (req.method !== "GET" && req.headers["x-git-tm"] !== "1") return json(res, 403, { error: "Forbidden" });
164
- const data = await route(url.searchParams);
234
+ const data = await route(url.searchParams, req);
165
235
  json(res, 200, data);
236
+ logRequest({ method: req.method, path: url.pathname, query: url.searchParams, status: 200, ms: Math.round(performance.now() - started) });
166
237
  } catch (err) {
167
238
  const status = err instanceof GitError ? err.status : 500;
168
239
  if (status >= 500) console.error(`${req.method} ${req.url}: ${err instanceof GitError ? err.message : err.stack}`);
240
+ if (apiUrl) logRequest({ method: req.method, path: apiUrl.pathname, query: apiUrl.searchParams, status, ms: Math.round(performance.now() - started), error: err.message });
169
241
  if (res.headersSent) res.destroy();
170
- else json(res, status, { error: err.message || "Internal error" });
242
+ else json(res, status, { error: err.message || "Internal error", ...(err.conflicts ? { conflicts: err.conflicts } : {}) });
171
243
  }
172
244
  });
173
245
  }
174
246
 
247
+ /** Read a small JSON object body. Requiring application/json also forces a CORS preflight for cross-site requests. */
248
+ async function readJson(req) {
249
+ if (!/^application\/json(;|$)/i.test(req.headers["content-type"] || "")) throw new GitError("Expected a JSON body", 415);
250
+ const chunks = [];
251
+ let size = 0;
252
+ // Keep reading past the limit (discarding) so the client gets a clean 413 instead of a reset connection.
253
+ for await (const chunk of req) {
254
+ size += chunk.length;
255
+ if (size <= MAX_BODY) chunks.push(chunk);
256
+ }
257
+ if (size > MAX_BODY) throw new GitError("Request body too large", 413);
258
+ let data;
259
+ try {
260
+ data = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
261
+ } catch {
262
+ throw new GitError("Invalid JSON body", 400);
263
+ }
264
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new GitError("Expected a JSON object", 400);
265
+ return data;
266
+ }
267
+
175
268
  function required(q, name) {
176
269
  const v = q.get(name);
177
270
  if (!v) throw new GitError(`Missing parameter: ${name}`, 400);
@@ -0,0 +1,69 @@
1
+ import type { Repo } from "./git.js";
2
+
3
+ /** The kinds of edit edit mode supports. */
4
+ export type EditType = "reword" | "author" | "squash" | "drop" | "revert";
5
+
6
+ export interface EditOptions {
7
+ type: EditType;
8
+ /** The commit to edit (any revision git understands). */
9
+ commit: string;
10
+ /** Local branch whose history changes. Default: the current branch. */
11
+ branch?: string;
12
+ /** New message for reword; optional combined message for squash; optional message for revert. */
13
+ message?: string;
14
+ /** New author for the "author" edit. `date` is Unix seconds; the original time zone is kept. */
15
+ author?: { name: string; email: string; date?: number };
16
+ }
17
+
18
+ export interface EditPlan {
19
+ type: EditType;
20
+ branch: string;
21
+ ref: string;
22
+ oldTip: string;
23
+ newTip: string;
24
+ target: string;
25
+ targetSubject: string;
26
+ summary: string;
27
+ /** Old commits and what replaces them (`new` is null for a dropped commit). */
28
+ rewritten: { old: string; new: string | null; subject: string }[];
29
+ /** New commits that rewrite nothing (revert). */
30
+ added: { new: string; subject: string }[];
31
+ /** True when the final tree is unchanged, so the working tree is never touched. */
32
+ treePreserving: boolean;
33
+ /** Remote branches that already have the affected commits. Applying then needs `allowPushed`. */
34
+ pushed: string[];
35
+ /** Other refs that keep pointing at the old commits. */
36
+ otherRefs: { branches: string[]; tags: string[] };
37
+ /** Number of signed commits that lose their signature. */
38
+ signed: number;
39
+ warnings: string[];
40
+ /** Whether the branch is checked out in this worktree. */
41
+ checkedOut: boolean;
42
+ }
43
+
44
+ export interface EditResult {
45
+ id: string;
46
+ branch: string;
47
+ oldTip: string;
48
+ newTip: string;
49
+ }
50
+
51
+ export interface EditBackup extends EditResult {
52
+ op: EditType | "undo";
53
+ summary: string;
54
+ /** Unix seconds. */
55
+ time: number;
56
+ /** Where the branch is now. */
57
+ current: string | null;
58
+ /** True while the branch is still exactly where the edit left it. */
59
+ canUndo: boolean;
60
+ }
61
+
62
+ /** Work out an edit without changing anything. Throws GitError (409 with `conflicts` for conflicting drops and reverts). */
63
+ export function planEdit(repo: Repo, options: EditOptions): Promise<EditPlan>;
64
+ /** Apply a plan: backs up the old tip, then moves the branch only if it hasn't moved since planning. */
65
+ export function applyEdit(repo: Repo, plan: EditPlan, options?: { allowPushed?: boolean }): Promise<EditResult>;
66
+ /** Edits made by git-tm, newest first. */
67
+ export function listBackups(repo: Repo): Promise<EditBackup[]>;
68
+ /** Undo an edit, or with `newBranch` restore the old timeline as a new branch. */
69
+ export function undoEdit(repo: Repo, id: string, options?: { newBranch?: string }): Promise<{ id?: string; branch: string; newTip: string }>;
@@ -16,12 +16,19 @@ export interface GitOptions {
16
16
  maxBytes?: number;
17
17
  /** Kill git after this many milliseconds. Default 60 000. */
18
18
  timeout?: number;
19
+ /** Extra environment variables for this git process. */
20
+ env?: Record<string, string>;
19
21
  }
20
22
 
21
23
  /** Run git in `cwd` with a clean, non-interactive environment and resolve with its stdout. */
22
24
  export function git(cwd: string, args: string[], options: GitOptions & { raw: true }): Promise<Buffer & { truncated: boolean }>;
25
+ /** With `allowExit`, the listed non-zero exit codes (and 0) resolve with stdout and the code instead of throwing. */
26
+ export function git(cwd: string, args: string[], options: GitOptions & { allowExit: number[] }): Promise<{ stdout: string; code: number }>;
23
27
  export function git(cwd: string, args: string[], options?: GitOptions): Promise<string>;
24
28
 
29
+ /** Validate a user-supplied revision so it can never be read as a git option. Returns it unchanged or throws GitError. */
30
+ export function checkRev(rev: string): string;
31
+
25
32
  /** Open the repository containing `dir` (any folder inside it works). Throws GitError if there is none. */
26
33
  export function openRepo(dir: string): Promise<Repo>;
27
34
 
@@ -1,5 +1,7 @@
1
1
  export * from "./git.js";
2
2
  export { createServer, listen } from "./server.js";
3
3
  export type { ServerOptions } from "./server.js";
4
+ export { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
5
+ export type { EditType, EditOptions, EditPlan, EditResult, EditBackup } from "./edit.js";
4
6
  export { createLayout, layout } from "./graph.js";
5
7
  export type { GraphRow, LayoutState } from "./graph.js";
@@ -6,6 +6,12 @@ export interface ServerOptions {
6
6
  avatars?: boolean;
7
7
  /** The host you will listen on. For loopback hosts, requests for other host names are rejected. Default "127.0.0.1". */
8
8
  host?: string;
9
+ /** Enable edit mode: the /api/edit/* routes that change history. Only allowed with a loopback host. Default false. */
10
+ edit?: boolean;
11
+ /** Called after each applied edit, undo or restore (for logging). */
12
+ onEdit?: (event: { id?: string; branch: string; newTip: string; op: string; summary?: string; count?: number }) => void;
13
+ /** Called after each handled API request (excluding /api/state polling). */
14
+ onLog?: (event: { method: string; path: string; query: URLSearchParams; status: number; ms: number; error?: string }) => void;
9
15
  }
10
16
 
11
17
  /** An HTTP server for the git-tm web interface and its JSON API. Call listen() to start it. */