xonecas.io
725
Ds

diff-scope / files

diff-scope / src / index.ts

12.7 KB
1import { Spacer } from "@cel-tui/components";
2import { HStack, ProcessTerminal, Text, VStack, cel } from "@cel-tui/core";
3import packageJson from "../package.json";
4
5type GitCommandResult = {
6  ok: boolean;
7  stdout: string;
8  stderr: string;
9};
10
11type RepoSnapshot = {
12  cwd: string;
13  branch: string;
14  statusSummary: string;
15  diffLines: string[];
16};
17
18type RepoState = {
19  snapshot: RepoSnapshot;
20  fingerprint: string;
21};
22
23type StatusPillColor =
24  | "color00"
25  | "color01"
26  | "color02"
27  | "color03"
28  | "color04"
29  | "color05"
30  | "color06"
31  | "color07"
32  | "color08";
33
34const APP_NAME = packageJson.name;
35const APP_VERSION = packageJson.version;
36const CHANGE_DETECTION_INTERVAL_MS = 5_000;
37const MIN_AUTO_REFRESH_INTERVAL_SECONDS = 5;
38const MAX_AUTO_REFRESH_INTERVAL_SECONDS = 60;
39const AUTO_REFRESH_STEP_SECONDS = 5;
40const textDecoder = new TextDecoder();
41
42let helpOpen = false;
43let autoRefreshEnabled = true;
44let autoRefreshIntervalSeconds = 15;
45let autoRefreshTimer: ReturnType<typeof setInterval> | null = null;
46let displayedState = readRepoState();
47let snapshot = displayedState.snapshot;
48let displayedFingerprint = displayedState.fingerprint;
49let hasPendingChanges = false;
50
51function decode(buffer: Uint8Array<ArrayBufferLike>): string {
52  return textDecoder.decode(buffer).replace(/\r\n/g, "\n").trimEnd();
53}
54
55function runGit(args: string[]): GitCommandResult {
56  const result = Bun.spawnSync({
57    cmd: ["git", ...args],
58    cwd: process.cwd(),
59    stdout: "pipe",
60    stderr: "pipe",
61  });
62
63  return {
64    ok: result.exitCode === 0,
65    stdout: decode(result.stdout),
66    stderr: decode(result.stderr),
67  };
68}
69
70function shortenPath(path: string): string {
71  const home = process.env.HOME;
72
73  if (!home || !path.startsWith(home)) {
74    return path;
75  }
76
77  const suffix = path.slice(home.length);
78  return suffix ? `~${suffix}` : "~";
79}
80
81function summarizeStatus(shortStatus: string): string {
82  if (!shortStatus) {
83    return "clean";
84  }
85
86  let staged = 0;
87  let modified = 0;
88  let untracked = 0;
89
90  for (const line of shortStatus.split("\n")) {
91    if (!line) {
92      continue;
93    }
94
95    if (line.startsWith("??")) {
96      untracked += 1;
97      continue;
98    }
99
100    const indexStatus = line[0] ?? " ";
101    const worktreeStatus = line[1] ?? " ";
102
103    if (indexStatus !== " ") {
104      staged += 1;
105    }
106
107    if (worktreeStatus !== " ") {
108      modified += 1;
109    }
110  }
111
112  const parts: string[] = [];
113
114  if (staged > 0) {
115    parts.push(`staged ${staged}`);
116  }
117
118  if (modified > 0) {
119    parts.push(`modified ${modified}`);
120  }
121
122  if (untracked > 0) {
123    parts.push(`untracked ${untracked}`);
124  }
125
126  return parts.length > 0 ? parts.join(" · ") : "clean";
127}
128
129function readBranch(): string {
130  const branch = runGit(["branch", "--show-current"]);
131  const branchName = branch.stdout.trim();
132
133  if (branch.ok && branchName) {
134    return branchName;
135  }
136
137  const detachedHead = runGit(["rev-parse", "--short", "HEAD"]);
138  if (detachedHead.ok && detachedHead.stdout.trim()) {
139    return `(detached ${detachedHead.stdout.trim()})`;
140  }
141
142  return "(unknown branch)";
143}
144
145function buildFingerprint(parts: string[]): string {
146  return parts.join("\n\0\n");
147}
148
149function buildDiffLines(
150  statusSummary: string,
151  stagedDiff: string,
152  unstagedDiff: string,
153): string[] {
154  const stagedLines = stagedDiff ? stagedDiff.split("\n") : [];
155  const unstagedLines = unstagedDiff ? unstagedDiff.split("\n") : [];
156
157  if (stagedLines.length > 0 && unstagedLines.length > 0) {
158    return [
159      "Staged changes",
160      "",
161      ...stagedLines,
162      "",
163      "Unstaged changes",
164      "",
165      ...unstagedLines,
166    ];
167  }
168
169  if (stagedLines.length > 0) {
170    return stagedLines;
171  }
172
173  if (unstagedLines.length > 0) {
174    return unstagedLines;
175  }
176
177  if (statusSummary === "clean") {
178    return [
179      "Working tree is clean.",
180      "",
181      "Edit a tracked file, then press r to refresh this snapshot.",
182    ];
183  }
184
185  return [
186    "No diff to show.",
187    "",
188    `Status: ${statusSummary}.`,
189    "",
190    "Tip: untracked files do not appear in git diff until they are added.",
191  ];
192}
193
194function readRepoState(): RepoState {
195  const cwd = shortenPath(process.cwd());
196  const status = runGit(["status", "--short"]);
197
198  if (!status.ok) {
199    const snapshot = {
200      cwd,
201      branch: "(not a git repo)",
202      statusSummary: "git status unavailable",
203      diffLines: [
204        "This directory is not a git repository.",
205        "",
206        status.stderr || "git status failed.",
207      ],
208    };
209
210    return {
211      snapshot,
212      fingerprint: buildFingerprint([cwd, snapshot.branch, snapshot.statusSummary, status.stderr]),
213    };
214  }
215
216  const branch = readBranch();
217  const statusSummary = summarizeStatus(status.stdout);
218  const unstaged = runGit(["diff", "--no-color"]);
219  if (!unstaged.ok) {
220    const snapshot = {
221      cwd,
222      branch,
223      statusSummary,
224      diffLines: ["git diff failed.", "", unstaged.stderr || "Unknown git error."],
225    };
226
227    return {
228      snapshot,
229      fingerprint: buildFingerprint([cwd, branch, status.stdout, unstaged.stderr]),
230    };
231  }
232
233  const staged = runGit(["diff", "--cached", "--no-color"]);
234  if (!staged.ok) {
235    const snapshot = {
236      cwd,
237      branch,
238      statusSummary,
239      diffLines: [
240        "git diff --cached failed.",
241        "",
242        staged.stderr || "Unknown git error.",
243      ],
244    };
245
246    return {
247      snapshot,
248      fingerprint: buildFingerprint([cwd, branch, status.stdout, staged.stderr]),
249    };
250  }
251
252  return {
253    snapshot: {
254      cwd,
255      branch,
256      statusSummary,
257      diffLines: buildDiffLines(statusSummary, staged.stdout, unstaged.stdout),
258    },
259    fingerprint: buildFingerprint([cwd, branch, status.stdout, staged.stdout, unstaged.stdout]),
260  };
261}
262
263function applyDisplayedState(nextState: RepoState) {
264  displayedState = nextState;
265  snapshot = nextState.snapshot;
266  displayedFingerprint = nextState.fingerprint;
267  hasPendingChanges = false;
268}
269
270function refreshSnapshot() {
271  applyDisplayedState(readRepoState());
272  cel.render();
273}
274
275function runAutoRefreshTick() {
276  const current = readRepoState();
277
278  if (current.fingerprint === displayedFingerprint) {
279    if (hasPendingChanges) {
280      hasPendingChanges = false;
281      cel.render();
282    }
283    return;
284  }
285
286  applyDisplayedState(current);
287  cel.render();
288}
289
290function syncAutoRefreshTimer() {
291  if (autoRefreshTimer !== null) {
292    clearInterval(autoRefreshTimer);
293    autoRefreshTimer = null;
294  }
295
296  if (!autoRefreshEnabled) {
297    return;
298  }
299
300  autoRefreshTimer = setInterval(
301    runAutoRefreshTick,
302    autoRefreshIntervalSeconds * 1_000,
303  );
304}
305
306function checkForPendingChanges() {
307  const current = readRepoState();
308  const nextHasPendingChanges = current.fingerprint !== displayedFingerprint;
309
310  if (nextHasPendingChanges !== hasPendingChanges) {
311    hasPendingChanges = nextHasPendingChanges;
312    cel.render();
313  }
314}
315
316function quit() {
317  cel.stop();
318  process.exit(0);
319}
320
321function diffLineProps(line: string) {
322  if (line === "Staged changes" || line === "Unstaged changes") {
323    return { bold: true, fgColor: "color05" as const };
324  }
325
326  if (line.startsWith("diff --git") || line.startsWith("--- ") || line.startsWith("+++ ")) {
327    return { bold: true, fgColor: "color06" as const };
328  }
329
330  if (line.startsWith("@@")) {
331    return { bold: true, fgColor: "color03" as const };
332  }
333
334  if (line.startsWith("+") && !line.startsWith("+++")) {
335    return { fgColor: "color02" as const };
336  }
337
338  if (line.startsWith("-") && !line.startsWith("---")) {
339    return { fgColor: "color01" as const };
340  }
341
342  if (line.startsWith("index ") || line.startsWith("Binary files ")) {
343    return { fgColor: "color08" as const };
344  }
345
346  if (line.startsWith("fatal:") || line.startsWith("error:")) {
347    return { fgColor: "color01" as const, bold: true };
348  }
349
350  return {};
351}
352
353function renderDiffLine(line: string) {
354  return VStack({ width: "100%", padding: { x: 1 } }, [
355    Text(line || " ", { wrap: "word", ...diffLineProps(line) }),
356  ]);
357}
358
359function renderStatusPill(
360  text: string,
361  options: {
362    bgColor: StatusPillColor;
363    fgColor?: StatusPillColor;
364    bold?: boolean;
365  },
366) {
367  return HStack(
368    {
369      bgColor: options.bgColor,
370      fgColor: options.fgColor ?? "color00",
371      padding: { x: 1 },
372    },
373    [Text(text, { bold: options.bold ?? true })],
374  );
375}
376
377function statusSummaryPillColors(statusSummary: string) {
378  if (statusSummary === "clean") {
379    return { bgColor: "color02" as const, fgColor: "color00" as const };
380  }
381
382  if (statusSummary.includes("modified")) {
383    return { bgColor: "color03" as const, fgColor: "color00" as const };
384  }
385
386  if (statusSummary.includes("staged")) {
387    return { bgColor: "color06" as const, fgColor: "color00" as const };
388  }
389
390  if (statusSummary.includes("untracked")) {
391    return { bgColor: "color05" as const, fgColor: "color00" as const };
392  }
393
394  return { bgColor: "color08" as const, fgColor: "color07" as const };
395}
396
397function renderStatusBar() {
398  return HStack(
399    {
400      padding: { x: 1 },
401      bgColor: "color00",
402      fgColor: "color07",
403    },
404    [
405      HStack({ gap: 1 }, [
406        renderStatusPill(snapshot.cwd, {
407          bgColor: "color08",
408          fgColor: "color07",
409          bold: false,
410        }),
411        renderStatusPill(snapshot.branch, {
412          bgColor: "color06",
413          fgColor: "color00",
414        }),
415        renderStatusPill(snapshot.statusSummary, statusSummaryPillColors(snapshot.statusSummary)),
416      ]),
417      Spacer(),
418      HStack({ gap: 1 }, [
419        renderStatusPill(autoRefreshModeLabel(), {
420          bgColor: autoRefreshEnabled ? "color04" : "color08",
421          fgColor: "color07",
422        }),
423        ...(hasPendingChanges
424          ? [
425              renderStatusPill("new changes pending", {
426                bgColor: "color01",
427                fgColor: "color07",
428              }),
429            ]
430          : []),
431        Text("r refresh · ctrl+r auto · ? help · ctrl+q quit", {
432          fgColor: "color08",
433        }),
434      ]),
435    ],
436  );
437}
438
439function renderHelpModal() {
440  return VStack(
441    {
442      height: "100%",
443      justifyContent: "center",
444      alignItems: "center",
445      onKeyPress: handleKeyPress,
446    },
447    [
448      VStack(
449        {
450          padding: { x: 2, y: 1 },
451          bgColor: "color07",
452          fgColor: "color00",
453        },
454        [
455          Text(`${APP_NAME} v${APP_VERSION}`, {
456            bold: true,
457            fgColor: "color06",
458          }),
459          Text(`Mode: ${autoRefreshModeLabel()}`, {
460            fgColor: "color08",
461          }),
462          Text(""),
463          Text("Keybinds", { bold: true }),
464          Text("r         refresh snapshot"),
465          Text("ctrl+r    toggle auto-refresh"),
466          Text("pageup    slower auto-refresh (+5s)"),
467          Text("pagedown  faster auto-refresh (-5s)"),
468          Text("? / esc   close help"),
469          Text("ctrl+q    quit"),
470          Text(""),
471          Text("Mouse wheel scrolls the diff view.", {
472            fgColor: "color08",
473          }),
474        ],
475      ),
476    ],
477  );
478}
479
480function isHelpKey(key: string) {
481  return key === "?" || key === "shift+/";
482}
483
484function autoRefreshModeLabel() {
485  return autoRefreshEnabled
486    ? `auto ${autoRefreshIntervalSeconds}s`
487    : `manual (${autoRefreshIntervalSeconds}s)`;
488}
489
490function toggleAutoRefresh() {
491  autoRefreshEnabled = !autoRefreshEnabled;
492  syncAutoRefreshTimer();
493  cel.render();
494}
495
496function adjustAutoRefreshInterval(deltaSeconds: number) {
497  const nextInterval = Math.min(
498    MAX_AUTO_REFRESH_INTERVAL_SECONDS,
499    Math.max(
500      MIN_AUTO_REFRESH_INTERVAL_SECONDS,
501      autoRefreshIntervalSeconds + deltaSeconds,
502    ),
503  );
504
505  if (nextInterval === autoRefreshIntervalSeconds) {
506    return;
507  }
508
509  autoRefreshIntervalSeconds = nextInterval;
510  syncAutoRefreshTimer();
511  cel.render();
512}
513
514function handleKeyPress(key: string) {
515  if (key === "ctrl+q" || key === "ctrl+c") {
516    quit();
517    return;
518  }
519
520  if (helpOpen && (isHelpKey(key) || key === "escape")) {
521    helpOpen = false;
522    cel.render();
523    return;
524  }
525
526  if (isHelpKey(key)) {
527    helpOpen = true;
528    cel.render();
529    return;
530  }
531
532  if (key === "ctrl+r") {
533    toggleAutoRefresh();
534    return;
535  }
536
537  if (key === "pageup") {
538    adjustAutoRefreshInterval(AUTO_REFRESH_STEP_SECONDS);
539    return;
540  }
541
542  if (key === "pagedown") {
543    adjustAutoRefreshInterval(-AUTO_REFRESH_STEP_SECONDS);
544    return;
545  }
546
547  if (key === "r") {
548    refreshSnapshot();
549  }
550}
551
552syncAutoRefreshTimer();
553setInterval(checkForPendingChanges, CHANGE_DETECTION_INTERVAL_MS);
554
555cel.init(new ProcessTerminal());
556cel.viewport(() => {
557  const baseLayer = VStack(
558    {
559      height: "100%",
560      onKeyPress: handleKeyPress,
561    },
562    [
563      VStack(
564        {
565          flex: 1,
566          overflow: "scroll",
567          scrollbar: true,
568        },
569        snapshot.diffLines.map(renderDiffLine),
570      ),
571      renderStatusBar(),
572    ],
573  );
574
575  return helpOpen ? [baseLayer, renderHelpModal()] : baseLayer;
576});