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/README.md CHANGED
@@ -53,7 +53,7 @@ git tm
53
53
 
54
54
  `git -C ../other-repo tm` works too. Use `git tm -h` for help: Git handles `git tm --help` itself and looks for a manual page instead.
55
55
 
56
- While it runs, press `o` in the terminal to open the browser, `h` to list these keys and `q` (or `Ctrl+C`) to stop.
56
+ While it runs, press `o` in the terminal to open the browser, `r` to restart the server (picks up repository changes), `h` to list these keys and `q` (or `Ctrl+C`) to stop.
57
57
 
58
58
  | Option | Description |
59
59
  | --- | --- |
@@ -61,6 +61,7 @@ While it runs, press `o` in the terminal to open the browser, `h` to list these
61
61
  | `--host <address>` | Interface to bind (default `127.0.0.1`) |
62
62
  | `-o, --open` | Open the browser once the server is running |
63
63
  | `--no-avatars` | Do not load author avatars from GitHub or Gravatar |
64
+ | `--edit` | Allow changing history: reword, change author or date, squash, drop and revert (off by default; see [Edit mode](#edit-mode)) |
64
65
  | `-v, --version` | Print the version |
65
66
  | `-h, --help` | Print help |
66
67
 
@@ -113,9 +114,36 @@ While it runs, press `o` in the terminal to open the browser, `h` to list these
113
114
  - Light and dark themes (follows your system by default)
114
115
  - Notices when the repository changes on disk and offers to refresh; if the git-tm process stops, the page says so and reconnects when it is back
115
116
  - Fetch all remotes with one click
116
- - Keyboard shortcuts: `j`/`k` to move, `Enter` to open, `t` for time travel mode, `←`/`→` to step through a journey, `/` to search, `Esc` to close, `g h`/`g c`/`g r`/`g i` to switch views, `?` for help
117
+ - Keyboard shortcuts: `j`/`k` to move, `Enter` to open, `t` for time travel mode, `←`/`→` to step through a journey, `/` to search, `Esc` to close, `g h`/`g c`/`g r`/`g i` to switch views, `?` for help. Right-click a commit or a branch for quick actions such as copying the SHA or comparing
117
118
  - Works on phones and tablets
118
119
 
120
+ ## Edit mode
121
+
122
+ Start git-tm with `--edit` and the time machine can change the past:
123
+
124
+ ```bash
125
+ git tm --edit
126
+ ```
127
+
128
+ Every commit gets an **Edit** button (and an *Edit commit* item when you right-click it in History):
129
+
130
+ - **Reword** the message, **change the author**, or just **change the date**
131
+ - **Squash** a commit into its parent
132
+ - **Drop** a commit and its changes
133
+ - **Revert** a commit: adds a new commit that undoes it, without rewriting anything
134
+
135
+ ![Edit mode previewing a reword: later commits get new IDs, with a warning that they are already pushed](docs/img/edit.jpg)
136
+
137
+ Edit mode is built to be hard to regret:
138
+
139
+ - **Off by default.** Without `--edit`, git-tm stays read-only. It only works on a local address, never with `--host 0.0.0.0`.
140
+ - **Preview first.** You see the new timeline before anything changes: which commits get new IDs, the file changes, and who still has the old commits.
141
+ - **Everything can be undone.** Before each edit, git-tm saves a backup of the branch under `refs/git-tm/backups/`. Undo it from the toast or from the Reflog view, or restore it as a new branch if you've moved on since.
142
+ - **Your work stays safe.** Message, author and squash edits never touch your working tree. Drop and revert refuse if you have staged changes, and stop if anything conflicts, leaving everything as it was.
143
+ - **Pushed commits** can be rewritten only after a clear warning: it means a force-push and a different history for everyone else. git-tm never pushes for you.
144
+
145
+ Each edit is printed in the terminal with its backup id. Drop and revert need Git 2.40 or newer. git-tm keeps backups for your last 200 edits per repository and removes older ones automatically (`git for-each-ref refs/git-tm/backups/` lists them, `git update-ref -d <ref>` removes one).
146
+
119
147
  ## Use it from code
120
148
 
121
149
  git-tm is also a library, with TypeScript types included:
@@ -129,12 +157,12 @@ const trip = await repo.range("v1.0.0", "main");
129
157
  console.log(`${trip.addedCount} commits applied, ${trip.removedCount} undone`);
130
158
  ```
131
159
 
132
- Entry points: `git-tm`, `git-tm/git`, `git-tm/server` and `git-tm/graph`. See the [API documentation](https://git-time-machine.js.org/guide.html#api) for every method.
160
+ Entry points: `git-tm`, `git-tm/git`, `git-tm/server`, `git-tm/edit` and `git-tm/graph`. See the [API documentation](https://git-time-machine.js.org/guide.html#api) for every method.
133
161
 
134
162
  ## Privacy and safety
135
163
 
136
164
  - Everything runs locally. The server binds to `127.0.0.1` and rejects requests for other host names, so other websites cannot read your repository.
137
- - Read-only. Git Time Machine never checks out, commits or rewrites anything. The only command that touches the network is **Fetch**, and only when you press it.
165
+ - Read-only by default. Git Time Machine never checks out, commits or rewrites anything unless you start it with `--edit`, and even then only after a preview, with a backup you can undo. The only command that touches the network is **Fetch**, and only when you press it.
138
166
  - Author avatars are loaded from GitHub (for `users.noreply.github.com` addresses) or Gravatar. Use `--no-avatars` to keep everything offline; initials are shown instead.
139
167
 
140
168
  ## How it works
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "git-tm",
3
- "version": "1.2.0",
4
- "description": "Explore any Git repository in your browser: commit graph, diffs, blame, insights and time travel between any two commits. Zero dependencies.",
3
+ "version": "2.1.0",
4
+ "description": "Explore any Git repository in your browser: commit graph, syntax-highlighted diffs, blame, reflog recovery, insights, time travel, and opt-in safe history editing. Zero dependencies.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
7
  "types": "./src/types/index.d.ts",
@@ -18,6 +18,10 @@
18
18
  "types": "./src/types/server.d.ts",
19
19
  "default": "./src/server.js"
20
20
  },
21
+ "./edit": {
22
+ "types": "./src/types/edit.d.ts",
23
+ "default": "./src/edit.js"
24
+ },
21
25
  "./graph": {
22
26
  "types": "./src/types/graph.d.ts",
23
27
  "default": "./src/public/js/graph.js"
@@ -55,6 +59,10 @@
55
59
  "history-viewer",
56
60
  "diff",
57
61
  "blame",
62
+ "reflog",
63
+ "rebase",
64
+ "edit-history",
65
+ "syntax-highlighting",
58
66
  "compare",
59
67
  "cli",
60
68
  "developer-tools",
package/src/cli.js CHANGED
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
  import { parseArgs } from "node:util";
7
7
  import { openRepo } from "./git.js";
8
8
  import { createServer, listen } from "./server.js";
9
+ import { listenAgain } from "./listen-again.js";
9
10
 
10
11
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
11
12
 
@@ -17,6 +18,7 @@ const c = {
17
18
  red: paint("31"),
18
19
  green: paint("32"),
19
20
  cyan: paint("36"),
21
+ yellow: paint("33"),
20
22
  accent: (s) => (useColor ? `\x1b[38;2;240;81;51m${s}\x1b[0m` : String(s)),
21
23
  };
22
24
 
@@ -32,6 +34,7 @@ ${c.bold("Options")}
32
34
  --host <address> Interface to bind ${c.dim("(default 127.0.0.1)")}
33
35
  -o, --open Open the browser once the server is running
34
36
  --no-avatars Do not load author avatars from GitHub / Gravatar
37
+ --edit Allow changing history: reword, squash, drop, revert ${c.dim("(off by default)")}
35
38
  -v, --version Print the version
36
39
  -h, --help Print this help
37
40
 
@@ -59,6 +62,7 @@ function parse() {
59
62
  open: { type: "boolean", short: "o", default: false },
60
63
  "no-open": { type: "boolean", default: false }, // accepted for compatibility; opening is now opt-in
61
64
  "no-avatars": { type: "boolean", default: false },
65
+ edit: { type: "boolean", default: false },
62
66
  version: { type: "boolean", short: "v", default: false },
63
67
  help: { type: "boolean", short: "h", default: false },
64
68
  },
@@ -98,6 +102,10 @@ async function main() {
98
102
  const port = Number(values.port);
99
103
  if (!Number.isInteger(port) || port < 0 || port > 65535) fail(`Invalid port: ${values.port}`);
100
104
 
105
+ if (values.edit && !["127.0.0.1", "localhost", "::1", "[::1]"].includes(values.host)) {
106
+ fail("--edit only works on 127.0.0.1, localhost or ::1, so nothing else on your network can change your history");
107
+ }
108
+
101
109
  const target = path.resolve(positionals[0] ?? ".");
102
110
  let repo;
103
111
  try {
@@ -106,7 +114,57 @@ async function main() {
106
114
  fail(err.message);
107
115
  }
108
116
 
109
- const server = createServer(repo, { avatars: !values["no-avatars"], host: values.host });
117
+ let shortcutsShown = false;
118
+ const clock = () => {
119
+ const d = new Date();
120
+ const pad = (n) => String(n).padStart(2, "0");
121
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
122
+ };
123
+ const log = (tag, text, extra = "") => {
124
+ shortcutsShown = false;
125
+ console.log(` ${c.dim(clock())} ${tag} ${text}${extra}`);
126
+ };
127
+
128
+ // In edit mode, log every change to the terminal as an audit trail.
129
+ const onEdit = (e) => {
130
+ const what =
131
+ e.op === "undo" ? `undid an edit on ${e.branch}.`
132
+ : e.op === "restore" ? `restored the old timeline as ${e.branch}.`
133
+ : e.summary || `${e.op} on ${e.branch}.`;
134
+ const backup = e.id ? c.dim(` (backup ${e.id})`) : "";
135
+ log(c.yellow("edit "), what, backup);
136
+ };
137
+
138
+ const shortRev = (r) => (r && /^[0-9a-f]{40,64}$/i.test(r) ? r.slice(0, 7) : r || "");
139
+ const onLog = ({ path: p, query: q, status, ms, error }) => {
140
+ const timing = c.dim(` (${ms} ms)`);
141
+ if (status >= 400) {
142
+ log(c.red(`${status} `), `${p}${error ? ` — ${error}` : ""}`, timing);
143
+ return;
144
+ }
145
+ if (p === "/api/history") {
146
+ if (Number(q.get("skip")) > 0) return;
147
+ const parts = [q.get("rev"), q.get("message"), q.get("author") && `author:${q.get("author")}`, q.get("path") && `path:${q.get("path")}`, q.get("code") && `code:${q.get("code")}`].filter(Boolean);
148
+ log(c.dim("history"), parts.length ? parts.join(" ") : "all branches", timing);
149
+ } else if (p === "/api/commit") {
150
+ log(c.dim("commit "), shortRev(q.get("rev")), timing);
151
+ } else if (p === "/api/range") {
152
+ log(c.dim("compare"), `${shortRev(q.get("from"))}..${shortRev(q.get("to"))}`, timing);
153
+ } else if (p === "/api/reflog") {
154
+ if (Number(q.get("skip")) > 0) return;
155
+ log(c.dim("reflog "), q.get("rev") || "HEAD", timing);
156
+ } else if (p === "/api/insights") {
157
+ log(c.dim("insight"), q.get("rev") || "all branches", timing);
158
+ } else if (p === "/api/blame") {
159
+ log(c.dim("blame "), `${q.get("path")} @ ${shortRev(q.get("rev"))}`, timing);
160
+ } else if (p === "/api/fetch") {
161
+ log(c.green("fetch "), "fetched all remotes", timing);
162
+ } else if (p === "/api/edit/preview") {
163
+ log(c.dim("preview"), "edit plan ready", timing);
164
+ }
165
+ };
166
+
167
+ let server = createServer(repo, { avatars: !values["no-avatars"], host: values.host, edit: values.edit, onEdit, onLog });
110
168
  let actual;
111
169
  try {
112
170
  actual = await listen(server, port, values.host);
@@ -116,6 +174,7 @@ async function main() {
116
174
 
117
175
  let rawModeEnabled = false;
118
176
  let stopping = false;
177
+ let reloading = false;
119
178
  let onKeypress;
120
179
  const restoreTerminal = () => {
121
180
  if (onKeypress) {
@@ -149,21 +208,65 @@ async function main() {
149
208
 
150
209
  const shownHost = ["127.0.0.1", "::1", "0.0.0.0", "::"].includes(values.host) ? "localhost" : values.host;
151
210
  const url = `http://${shownHost}:${actual}`;
152
- const info = await repo.info().catch(() => ({}));
211
+ const [info, remotesOut] = await Promise.all([
212
+ repo.info().catch(() => ({})),
213
+ repo.run(["remote", "-v"]).catch(() => ""),
214
+ ]);
153
215
  const where = info.branch ?? (info.head ? info.head.slice(0, 7) : "no commits yet");
216
+ const remotes = [];
217
+ const seenRemotes = new Set();
218
+ for (const line of remotesOut.split("\n")) {
219
+ const m = line.match(/^(\S+)\t(\S+)\s+\((fetch|push)\)$/);
220
+ if (!m || seenRemotes.has(m[1])) continue;
221
+ seenRemotes.add(m[1]);
222
+ // Never leak embedded credentials from remote URLs to the terminal.
223
+ const cleanUrl = m[2].replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]+@/i, "$1");
224
+ remotes.push([m[1], cleanUrl]);
225
+ }
226
+
227
+ const reload = async () => {
228
+ if (reloading || stopping) return;
229
+ reloading = true;
230
+ const t0 = performance.now();
231
+ try {
232
+ // Open the repository first: if that fails, the running server keeps serving.
233
+ const nextRepo = await openRepo(target);
234
+ const old = server;
235
+ await new Promise((resolve) => {
236
+ old.close(() => resolve()); // also resolves when a previous reload left it not listening
237
+ old.closeAllConnections?.();
238
+ });
239
+ repo = nextRepo;
240
+ server = createServer(repo, { avatars: !values["no-avatars"], host: values.host, edit: values.edit, onEdit, onLog });
241
+ await listenAgain(server, actual, values.host);
242
+ log(c.green("reload "), `restarted server on ${c.cyan(url)}`, c.dim(` (${Math.round(performance.now() - t0)} ms)`));
243
+ } catch (err) {
244
+ const why = err.code === "EADDRINUSE" ? `port ${actual} is in use by another program` : err.message;
245
+ log(c.red("reload "), `failed: ${why}. Press r to try again, or q to quit.`);
246
+ } finally {
247
+ reloading = false;
248
+ }
249
+ };
154
250
 
155
251
  console.log();
156
252
  console.log(` ${c.accent(c.bold("git-tm"))} ${c.dim(`v${pkg.version}`)}`);
157
253
  console.log();
158
- console.log(` ${c.dim("repo")} ${tildify(repo.root)} ${c.dim(`(${where})`)}`);
159
- console.log(` ${c.dim("url ")} ${c.cyan(url)}`);
254
+ console.log(` ${c.dim("repo ")} ${tildify(repo.root)} ${c.dim(`(${where})`)}`);
255
+ if (remotes.length) {
256
+ const padName = Math.max(...remotes.map(([n]) => n.length));
257
+ remotes.forEach(([name, rUrl], i) => {
258
+ const label = i === 0 ? c.dim("remote") : " ";
259
+ console.log(` ${label} ${name.padEnd(padName)} ${c.dim(rUrl)}`);
260
+ });
261
+ }
262
+ console.log(` ${c.dim("url ")} ${c.cyan(url)}`);
160
263
  if (actual !== port && port !== 0) console.log(` ${c.dim(`port ${port} was busy, using ${actual}`)}`);
264
+ if (values.edit) console.log(` ${c.yellow("edit ")} on: history can be changed. Every edit is backed up and can be undone. Mind the timeline.`);
161
265
  console.log();
162
266
 
163
267
  if (values.open) openBrowser(url);
164
268
 
165
269
  let interactiveInput = false;
166
- let shortcutsShown = false;
167
270
  if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
168
271
  try {
169
272
  process.stdin.setRawMode(true);
@@ -177,10 +280,15 @@ async function main() {
177
280
  }
178
281
  if (normalizedKey === "o") {
179
282
  openBrowser(url);
283
+ log(c.dim("open "), c.cyan(url));
284
+ } else if (normalizedKey === "r") {
285
+ reload();
180
286
  } else if (normalizedKey === "h" && !shortcutsShown) {
181
287
  shortcutsShown = true;
288
+ console.log();
182
289
  console.log(c.dim(" Keyboard shortcuts:"));
183
290
  console.log(c.dim(" o Open browser"));
291
+ console.log(c.dim(" r Reload server"));
184
292
  console.log(c.dim(" h Show shortcuts"));
185
293
  console.log(c.dim(" q Quit server"));
186
294
  console.log(c.dim(" Ctrl+C Quit server"));
@@ -199,14 +307,17 @@ async function main() {
199
307
  console.log(
200
308
  c.dim(
201
309
  interactiveInput
202
- ? " Press o to open, h for help, q to quit (Ctrl+C to quit)"
310
+ ? " Press o to open, r to reload, h for help, q to quit (Ctrl+C to quit)"
203
311
  : " Press Ctrl+C to stop",
204
312
  ),
205
313
  );
206
314
  console.log();
207
315
 
208
316
  // Keep serving if something unexpected goes wrong; say what happened instead of dying silently.
209
- const report = (err) => console.error(`${c.red("error")} ${err?.stack || err}`);
317
+ const report = (err) => {
318
+ shortcutsShown = false;
319
+ console.error(`${c.red("error")} ${err?.stack || err}`);
320
+ };
210
321
  process.on("uncaughtException", report);
211
322
  process.on("unhandledRejection", report);
212
323
  }