git-tm 1.1.0 → 1.1.2

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
@@ -14,7 +14,7 @@
14
14
 
15
15
  <br>
16
16
 
17
- ![Git Time Machine showing a commit graph and a merge commit's changes](docs/screenshot.png)
17
+ ![Demo: picking two commits in History, then stepping through every snapshot between them](docs/img/demo.gif)
18
18
 
19
19
  > **Full documentation:** [git-time-machine.js.org](https://git-time-machine.js.org) covers every feature, time travel, keyboard shortcuts, troubleshooting and the JavaScript API.
20
20
 
@@ -153,7 +153,7 @@ cd Git-Time-Machine
153
153
  node src/cli.js .
154
154
  ```
155
155
 
156
- Run the tests with `npm test`. See [CONTRIBUTING.md](CONTRIBUTING.md) for how the project is organised, its principles and how to send a pull request.
156
+ Run the tests with `npm test`. Questions and ideas are welcome in [Discussions](https://github.com/nandhu-44/Git-Time-Machine/discussions). See [CONTRIBUTING.md](CONTRIBUTING.md) for how the project is organised, its principles and how to send a pull request.
157
157
 
158
158
  ## Background
159
159
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "git-tm",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "Explore any Git repository in your browser: commit graph, diffs, blame, insights and time travel between any two commits. Zero dependencies.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/cli.js CHANGED
@@ -114,6 +114,15 @@ async function main() {
114
114
  fail(`Could not start server: ${err.message}`);
115
115
  }
116
116
 
117
+ // Handle Ctrl+C and SIGTERM before printing the address, so a signal that
118
+ // arrives right after startup still shuts down cleanly with exit code 0.
119
+ const stop = () => {
120
+ server.close();
121
+ process.exit(0);
122
+ };
123
+ process.on("SIGINT", stop);
124
+ process.on("SIGTERM", stop);
125
+
117
126
  const shownHost = ["127.0.0.1", "::1", "0.0.0.0", "::"].includes(values.host) ? "localhost" : values.host;
118
127
  const url = `http://${shownHost}:${actual}`;
119
128
  const info = await repo.info().catch(() => ({}));
@@ -135,13 +144,6 @@ async function main() {
135
144
  const report = (err) => console.error(`${c.red("error")} ${err?.stack || err}`);
136
145
  process.on("uncaughtException", report);
137
146
  process.on("unhandledRejection", report);
138
-
139
- const stop = () => {
140
- server.close();
141
- process.exit(0);
142
- };
143
- process.on("SIGINT", stop);
144
- process.on("SIGTERM", stop);
145
147
  }
146
148
 
147
149
  main();
package/src/git.js CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { spawn } from "node:child_process";
6
6
  import { createHash } from "node:crypto";
7
- import { readFile, stat } from "node:fs/promises";
7
+ import { lstat, readFile, readlink, realpath, stat } from "node:fs/promises";
8
8
  import path from "node:path";
9
9
 
10
10
  export const WORKTREE = "WORKTREE";
@@ -27,7 +27,7 @@ export class GitError extends Error {
27
27
  }
28
28
  }
29
29
 
30
- /** Run git and resolve with stdout (string, or Buffer when raw). */
30
+ /** Run git and resolve with stdout: a string, or with `raw` a Buffer that has `truncated` set. */
31
31
  export function git(cwd, args, { raw = false, input, maxBytes = 64 * MB, timeout = 60_000 } = {}) {
32
32
  return new Promise((resolve, reject) => {
33
33
  const child = spawn("git", [...GLOBAL_ARGS, ...args], {
@@ -76,8 +76,7 @@ export function git(cwd, args, { raw = false, input, maxBytes = 64 * MB, timeout
76
76
  return reject(new GitError(msg.replace(/^(fatal|error): /, ""), 400));
77
77
  }
78
78
  if (raw) return resolve(Object.assign(buf, { truncated }));
79
- const text = buf.toString("utf8");
80
- resolve(truncated ? Object.assign(new String(text), { truncated: true }) : text);
79
+ resolve(buf.toString("utf8"));
81
80
  });
82
81
  child.stdin.on("error", () => {});
83
82
  child.stdin.end(input);
@@ -483,8 +482,8 @@ class Repo {
483
482
  const ctx = Math.min(100000, Math.max(0, context | 0));
484
483
  const compute = async () => {
485
484
  const args = this.diffArgs(a, b, ["-M", `-U${ctx}`, "--no-ext-diff", ...(ignoreWhitespace ? ["-w"] : [])]);
486
- const out = await this.run([...args, "--", ...paths], { maxBytes: 4 * MB });
487
- return { patch: String(out), truncated: Boolean(out.truncated) };
485
+ const out = await this.run([...args, "--", ...paths], { raw: true, maxBytes: 4 * MB });
486
+ return { patch: out.toString("utf8"), truncated: out.truncated };
488
487
  };
489
488
  if (b === WORKTREE) {
490
489
  const res = await compute();
@@ -500,6 +499,16 @@ class Repo {
500
499
  async untrackedPatch(p) {
501
500
  const full = path.resolve(this.root, p);
502
501
  if (!full.startsWith(this.root + path.sep)) throw new GitError("Invalid path", 400);
502
+ const info = await lstat(full).catch(() => null);
503
+ if (!info) return { patch: "", truncated: false };
504
+ // Like git: a symlink's content is its target, never the file it points to.
505
+ if (info.isSymbolicLink()) {
506
+ const target = await readlink(full);
507
+ return { patch: `new file mode 120000\n--- /dev/null\n+++ b/${p}\n@@ -0,0 +1 @@\n+${target}\n\\n`, truncated: false };
508
+ }
509
+ // A symlinked folder on the way must not lead outside the repository either.
510
+ const [realRoot, realFull] = await Promise.all([realpath(this.root), realpath(full)]);
511
+ if (!realFull.startsWith(realRoot + path.sep)) throw new GitError("Invalid path", 400);
503
512
  const buf = await readFile(full).catch(() => null);
504
513
  if (!buf) return { patch: "", truncated: false };
505
514
  if (isBinary(buf)) return { patch: `Binary files /dev/null and b/${p} differ\n`, truncated: false };
@@ -523,10 +532,11 @@ class Repo {
523
532
  async range(from, to) {
524
533
  const a = await this.resolve(from);
525
534
  const b = await this.resolve(to);
526
- const empty = { added: [], removed: [], path: [], addedCount: 0, removedCount: 0, mergeBase: null };
535
+ const empty = { added: [], removed: [], path: [], addedCount: 0, removedCount: 0, mergeBase: null, truncated: false };
527
536
  if (a === WORKTREE || b === WORKTREE || a === b) return empty;
528
537
  const log = (...args) => this.run(["log", "--decorate=full", `--format=${LOG_FORMAT}`, ...args]).then(parseLog);
529
- const LIMIT = "--max-count=500";
538
+ const MAX = 500;
539
+ const LIMIT = `--max-count=${MAX}`;
530
540
  const [counts, baseOut, added, removed, down, up] = await Promise.all([
531
541
  this.run(["rev-list", "--left-right", "--count", `${a}...${b}`]),
532
542
  tryGit(this.root, ["merge-base", a, b]),
@@ -543,7 +553,9 @@ class Repo {
543
553
  path.push(...up.reverse()); // then forward to `to`
544
554
  if (!path.length || path[path.length - 1].hash !== b) path.push((await log("-1", b))[0]);
545
555
 
546
- return { added, removed, path, addedCount, removedCount, mergeBase };
556
+ // Very long trips only include the first MAX steps on each side.
557
+ const truncated = down.length === MAX || up.length === MAX;
558
+ return { added, removed, path, addedCount, removedCount, mergeBase, truncated };
547
559
  }
548
560
 
549
561
  // ---------------------------------------------------------- browsing
@@ -850,11 +850,16 @@ button.chip:hover {
850
850
  font: 500 11.5px var(--mono);
851
851
  white-space: nowrap;
852
852
  overflow: hidden;
853
- text-overflow: ellipsis;
854
853
  max-width: 180px;
855
854
  border: 1px solid transparent;
856
855
  }
857
856
 
857
+ .ref-name {
858
+ min-width: 0;
859
+ overflow: hidden;
860
+ text-overflow: ellipsis;
861
+ }
862
+
858
863
  .ref svg {
859
864
  width: 11px !important;
860
865
  height: 11px !important;
@@ -2234,7 +2239,7 @@ mark.del {
2234
2239
  .punch {
2235
2240
  display: block;
2236
2241
  width: 100%;
2237
- min-width: 520px;
2242
+ min-width: 360px;
2238
2243
  }
2239
2244
 
2240
2245
  .punch circle {
@@ -230,6 +230,7 @@ export function createCompare(app) {
230
230
  </div>
231
231
  <div class="travel-ends muted small"><span>From</span><span>${plural(path.length, "step")} along the way</span><span>To</span></div>
232
232
  <div class="travel-now">${stepLabel()}</div>
233
+ ${travel.truncated ? html`<div class="diff-note">This trip is too long to show every step: the slider skips part of the middle. The diff and commit lists are complete.</div>` : ""}
233
234
  </section>`;
234
235
  }
235
236
 
@@ -34,7 +34,7 @@ function heatmap(days, endTs) {
34
34
  const size = 11;
35
35
  const gap = 3;
36
36
  const weeks = Math.ceil(cells.length / 7);
37
- const w = 28 + weeks * (size + gap);
37
+ const w = 28 + weeks * (size + gap) + 20; // room for a month label in the last column
38
38
  const h = 18 + 7 * (size + gap);
39
39
  let svg = `<svg class="heatmap" viewBox="0 0 ${w} ${h}" role="img" aria-label="Commit activity over the last year">`;
40
40
  for (const m of months) svg += `<text x="${28 + m.col * (size + gap)}" y="10" class="axis">${m.name}</text>`;
@@ -50,9 +50,9 @@ function heatmap(days, endTs) {
50
50
 
51
51
  function punchcard(punch) {
52
52
  const max = Math.max(1, ...punch.flat());
53
- const cw = 22;
53
+ const cw = 16;
54
54
  const rh = 24;
55
- const w = 40 + 24 * cw;
55
+ const w = 40 + 24 * cw + 12; // room for the last hour label
56
56
  const h = 7 * rh + 20;
57
57
  let svg = `<svg class="punch" viewBox="0 0 ${w} ${h}" role="img" aria-label="Commits by weekday and hour">`;
58
58
  for (let d = 0; d < 7; d++) {
@@ -60,7 +60,7 @@ function punchcard(punch) {
60
60
  for (let hr = 0; hr < 24; hr++) {
61
61
  const v = punch[d][hr];
62
62
  if (!v) continue;
63
- const r = 2 + Math.sqrt(v / max) * 8;
63
+ const r = 2 + Math.sqrt(v / max) * 5; // at most 7, so neighbouring hours never overlap
64
64
  svg += `<circle cx="${40 + hr * cw + cw / 2}" cy="${d * rh + rh / 2}" r="${r.toFixed(1)}"><title>${plural(v, "commit")} · ${DAYS[d]} ${hr}:00</title></circle>`;
65
65
  }
66
66
  }
@@ -390,7 +390,7 @@ async function boot() {
390
390
  try {
391
391
  await app.reloadRepo();
392
392
  } catch (err) {
393
- $("#main").innerHTML = `<div class="empty error"><strong>Could not load the repository</strong><span>${err.message}</span></div>`;
393
+ $("#main").innerHTML = String(html`<div class="empty error"><strong>Could not load the repository</strong><span>${err.message}</span></div>`);
394
394
  return;
395
395
  }
396
396
  if (!app.repo.remotes.length) $("#fetch-btn").hidden = true;
@@ -150,7 +150,7 @@ export function refBadges(refs, { max = 4 } = {}) {
150
150
  return html`<span class="refs">${shown.map(
151
151
  (r) => html`<span class="ref ref-${r.type}" title="${r.name}">${
152
152
  r.type === "tag" ? raw(icons.tag) : r.type === "head" ? raw(icons.head) : ""
153
- }${r.name}</span>`,
153
+ }<span class="ref-name">${r.name}</span></span>`,
154
154
  )}${extra > 0 ? html`<span class="ref ref-more" title="${sorted.slice(max).map((r) => r.name).join(", ")}">+${extra}</span>` : ""}</span>`;
155
155
  }
156
156
 
package/src/server.js CHANGED
@@ -114,7 +114,14 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
114
114
  };
115
115
 
116
116
  async function serveStatic(res, pathname) {
117
- const rel = pathname === "/" ? "index.html" : decodeURIComponent(pathname).replace(/^\/+/, "");
117
+ let rel = "index.html";
118
+ if (pathname !== "/") {
119
+ try {
120
+ rel = decodeURIComponent(pathname).replace(/^\/+/, "");
121
+ } catch {
122
+ return send(res, 400, "Bad request");
123
+ }
124
+ }
118
125
  const file = path.resolve(PUBLIC_DIR, rel);
119
126
  if (!file.startsWith(PUBLIC_DIR + path.sep)) return send(res, 403, "Forbidden");
120
127
  let body = staticCache.get(file);
@@ -134,7 +141,7 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
134
141
  return http.createServer(async (req, res) => {
135
142
  try {
136
143
  if (checkHost) {
137
- const h = (req.headers.host || "").replace(/:\d+$/, "");
144
+ const h = (req.headers.host || "").toLowerCase().replace(/:\d+$/, "");
138
145
  if (!LOOPBACK.has(h)) return send(res, 421, "Misdirected request");
139
146
  }
140
147
  const url = new URL(req.url, "http://localhost");
@@ -12,7 +12,7 @@ export interface GitOptions {
12
12
  raw?: boolean;
13
13
  /** Written to git's stdin. */
14
14
  input?: string | Buffer;
15
- /** Stop reading after this many bytes of output; the result gets `truncated: true`. Default 64 MB. */
15
+ /** Stop reading after this many bytes of output. With `raw`, the Buffer's `truncated` says whether this happened. Default 64 MB. */
16
16
  maxBytes?: number;
17
17
  /** Kill git after this many milliseconds. Default 60 000. */
18
18
  timeout?: number;
@@ -137,6 +137,8 @@ export interface Range {
137
137
  addedCount: number;
138
138
  removedCount: number;
139
139
  mergeBase: string | null;
140
+ /** True when the trip is so long that `path` only covers its first 500 steps on each side. */
141
+ truncated: boolean;
140
142
  }
141
143
 
142
144
  export interface TreeEntry {