decklight 0.4.0 → 0.6.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/cli/git.mjs CHANGED
@@ -120,7 +120,19 @@ export function commitSubject(raw, fallback) {
120
120
  return /^-/.test(capped) ? `agent: ${capped}` : capped;
121
121
  }
122
122
 
123
+ /**
124
+ * The sha of the commit `gitAutocommit` last made, or null.
125
+ *
126
+ * Kept beside the commit rather than returned in its place because every
127
+ * existing caller treats the return value as a boolean — "did anything land" —
128
+ * and widening that to an object would put a truthiness question in front of
129
+ * the safety net. `--commit-messages` is the only caller that needs the sha,
130
+ * and it reads it immediately.
131
+ */
132
+ export let lastCommitSha = null;
133
+
123
134
  export function gitAutocommit(deckPath, cwd, message = `decklight: autosave ${basename(deckPath)}`) {
135
+ lastCommitSha = null;
124
136
  try {
125
137
  if (!git(['status', '--porcelain', '--', deckPath], cwd)) return false;
126
138
  git(['add', '--', deckPath], cwd);
@@ -133,9 +145,345 @@ export function gitAutocommit(deckPath, cwd, message = `decklight: autosave ${ba
133
145
  git(['-c', 'user.name=decklight', '-c', 'user.email=decklight@localhost',
134
146
  'commit', '-m', message, '--', deckPath], cwd);
135
147
  }
148
+ try { lastCommitSha = git(['rev-parse', 'HEAD'], cwd); } catch { lastCommitSha = null; }
136
149
  return true;
137
150
  } catch (e) {
138
151
  console.error(` git autocommit failed: ${oneline(e)}`);
139
152
  return false;
140
153
  }
141
154
  }
155
+
156
+ // ── the remote half ────────────────────────────────────────────────────────
157
+ //
158
+ // Everything above is LOCAL: does a repo exist, is the tree dirty, commit it.
159
+ // That was the whole vocabulary, and it is why decklight could commit
160
+ // diligently for a week and never once mention that none of it existed anywhere
161
+ // but this laptop.
162
+ //
163
+ // Two rules govern this section, and both are learned rather than assumed:
164
+ //
165
+ // NEVER A HANG. `GIT_TERMINAL_PROMPT=0` is what cloneMarketplace already uses,
166
+ // and it is HALF the answer: it stops git's own prompts and the https askpass,
167
+ // while an `ssh://` remote will still sit forever on a host-key or passphrase
168
+ // question nobody is there to type. `ssh -oBatchMode=yes` is the other half.
169
+ // Blanking the askpass variables stops a GUI credential window opening behind a
170
+ // headless probe, without disabling real credential HELPERS (osxkeychain,
171
+ // libsecret), which is what makes a private remote work at all.
172
+ //
173
+ // NEVER A FETCH YOU DID NOT ASK FOR. cli/marketplace.mjs already decided this
174
+ // for catalogs — "nothing ever pulls into it, which is what keeps decklight out
175
+ // of the credential-helper trap a background `git pull` walks into" — and the
176
+ // same holds here. Everything the author loop reads (`unpushed`, `@{u}`) is a
177
+ // LOCAL read of remote-tracking refs and needs no network at all. `behind` is
178
+ // therefore as fresh as your last fetch, and saying so is better than fetching
179
+ // behind someone's back.
180
+
181
+ /** The env every remote-touching git call runs under. See the note above. */
182
+ export function noPromptEnv(env = process.env) {
183
+ const { GIT_ASKPASS, SSH_ASKPASS, ...rest } = env;
184
+ return {
185
+ ...rest,
186
+ GIT_TERMINAL_PROMPT: '0',
187
+ GIT_SSH_COMMAND: rest.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=5',
188
+ GCM_INTERACTIVE: 'Never',
189
+ };
190
+ }
191
+
192
+ /**
193
+ * `git rev-list --left-right --count @{u}...HEAD` → `{ ahead, behind }`.
194
+ *
195
+ * THE LEFT COUNT IS `behind`. With `A...B` the left side is what is reachable
196
+ * from A and not B; A is the upstream, so the left number is what the upstream
197
+ * has and you do not. Getting this backwards is the classic bug in this command
198
+ * — it type-checks, it looks right, and it reports your unpushed work as the
199
+ * other side's — so the parse is its own function with its own test.
200
+ */
201
+ export function parseAheadBehind(out) {
202
+ const parts = String(out ?? '').trim().split(/\s+/);
203
+ if (parts.length !== 2) return null;
204
+ const [behind, ahead] = parts.map(Number);
205
+ if (!Number.isInteger(behind) || !Number.isInteger(ahead) || behind < 0 || ahead < 0) return null;
206
+ return { ahead, behind };
207
+ }
208
+
209
+ /**
210
+ * Which remote to speak of when a command has to name one.
211
+ *
212
+ * Pure, because "several remotes and none called origin" is a real repository
213
+ * and guessing there would put someone's work on the wrong host.
214
+ */
215
+ export function preferredRemote(names = []) {
216
+ if (!names.length) return { name: null, state: 'none' };
217
+ if (names.includes('origin')) return { name: 'origin', state: 'ok' };
218
+ if (names.length === 1) return { name: names[0], state: 'ok' };
219
+ return { name: null, state: 'ambiguous' };
220
+ }
221
+
222
+ /**
223
+ * Why a remote operation failed, as a word.
224
+ *
225
+ * The distinction that matters is `denied` versus `offline`: one means "your
226
+ * credentials do not open this", the other "nothing was reachable", and telling
227
+ * someone to check their network when the answer is a missing key wastes the
228
+ * ten minutes before a talk. `offline` also covers the timeout, because a
229
+ * remote that did not answer inside the bound is indistinguishable from one
230
+ * that is not there — and both are answers rather than hangs.
231
+ */
232
+ export function classifyRemoteError(e) {
233
+ const text = String(e?.stderr || e?.message || e || '');
234
+ if (e?.signal || /\bETIMEDOUT\b|timed out/i.test(text)) return 'offline';
235
+ if (/could not resolve host|could not resolve hostname|network is unreachable|connection refused|connection timed out|failed to connect|unable to access/i.test(text)) return 'offline';
236
+ if (/authentication failed|permission denied|could not read (username|password)|terminal prompts disabled|access denied|\b403\b/i.test(text)) return 'denied';
237
+ if (/repository not found|does not appear to be a git repository|\b404\b/i.test(text)) return 'gone';
238
+ return 'unknown';
239
+ }
240
+
241
+ /**
242
+ * Is this string safe to hand to `git remote add` as a URL?
243
+ *
244
+ * The leading-dash refusal is the point: `git remote add origin
245
+ * --upload-pack=…` is an argument, not a URL, and `git remote add` offers no
246
+ * `--` terminator to hide behind. Same reasoning as commitSubject's dash rule.
247
+ */
248
+ export function looksLikeGitUrl(s) {
249
+ const v = String(s ?? '').trim();
250
+ if (!v || v.startsWith('-')) return false;
251
+ if (/^(https?|ssh|git|file):\/\//i.test(v)) return true;
252
+ if (/^[\w.-]+@[\w.-]+:[^\s]+$/.test(v)) return true; // scp form: git@host:owner/repo
253
+ return v.startsWith('/'); // a local path is a remote too
254
+ }
255
+
256
+ // ── the probes, and the one object that answers "where does this stand?" ────
257
+
258
+ /** Is git installed at all? `inGitRepo` swallows ENOENT, so it cannot tell you. */
259
+ export function gitAvailable(cwd = process.cwd(), exec = execFileSync) {
260
+ try { git(['--version'], cwd, exec); return true; } catch { return false; }
261
+ }
262
+
263
+ /** Every remote's name, or `[]` — a repository with none is normal, not an error. */
264
+ export function remoteNames(cwd, run = git) {
265
+ try { return run(['remote'], cwd).split('\n').map((s) => s.trim()).filter(Boolean); }
266
+ catch { return []; }
267
+ }
268
+
269
+ /** A remote's URL, for display only. Nothing branches on it. */
270
+ export function remoteUrl(name, cwd, run = git) {
271
+ try { return run(['remote', 'get-url', name], cwd) || null; } catch { return null; }
272
+ }
273
+
274
+ /**
275
+ * What HEAD is: a branch, a detached commit, or nothing committed yet.
276
+ *
277
+ * The order is the correctness. An unborn HEAD (`git init`, nothing committed)
278
+ * has a symbolic-ref but no commit, so asking about the commit first is what
279
+ * distinguishes it from a detached one.
280
+ */
281
+ export function headState(cwd, run = git) {
282
+ try { run(['rev-parse', '--verify', '--quiet', 'HEAD'], cwd); }
283
+ catch { return { state: 'unborn', branch: null }; }
284
+ try {
285
+ const branch = run(['symbolic-ref', '--short', '-q', 'HEAD'], cwd);
286
+ return branch ? { state: 'ok', branch } : { state: 'detached', branch: null };
287
+ } catch { return { state: 'detached', branch: null }; }
288
+ }
289
+
290
+ /** The branch's upstream (`origin/main`), or null when it tracks nothing. */
291
+ export function upstreamOf(cwd, run = git) {
292
+ try { return run(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], cwd) || null; }
293
+ catch { return null; }
294
+ }
295
+
296
+ /** `{ ahead, behind }` against the upstream, or null. A LOCAL read — no fetch. */
297
+ export function aheadBehind(cwd, run = git) {
298
+ try { return parseAheadBehind(run(['rev-list', '--left-right', '--count', '@{u}...HEAD'], cwd)); }
299
+ catch { return null; }
300
+ }
301
+
302
+ /**
303
+ * Commits that exist on no remote at all — the number the UI should show.
304
+ *
305
+ * Deliberately not `ahead`. This needs NO upstream, so a freshly added remote
306
+ * with nothing pushed still gets a truthful count where `@{u}` would simply
307
+ * fail; with no remotes at all it degrades to "every commit", which is exactly
308
+ * right ("none of this exists anywhere else"); and it is per-commit, so an
309
+ * overlay can mark the rows rather than print a number.
310
+ */
311
+ export function unpushed(cwd, run = git) {
312
+ try { return run(['rev-list', 'HEAD', '--not', '--remotes'], cwd).split('\n').filter(Boolean); }
313
+ catch { return null; }
314
+ }
315
+
316
+ /**
317
+ * Where this repository stands, as one object. Never throws, never networks.
318
+ *
319
+ * Resolution is ordered and short-circuits, because each state makes the next
320
+ * question meaningless: you cannot be behind a remote you do not have, and you
321
+ * cannot be ahead of an upstream when HEAD is not on a branch.
322
+ */
323
+ export function remoteState(cwd, { run = git, exec = execFileSync } = {}) {
324
+ const nothing = { remote: null, url: null, branch: null, upstream: null, ahead: null, behind: null, unpushed: null, why: null };
325
+ if (!gitAvailable(cwd, exec)) return { ...nothing, state: 'no-git' };
326
+ if (!inGitRepo(cwd, exec)) return { ...nothing, state: 'no-repo' };
327
+
328
+ const head = headState(cwd, run);
329
+ if (head.state === 'unborn') return { ...nothing, state: 'unborn' };
330
+
331
+ const local = unpushed(cwd, run);
332
+ const base = { ...nothing, branch: head.branch, unpushed: local ? local.length : null };
333
+ if (head.state === 'detached') return { ...base, state: 'detached' };
334
+
335
+ const picked = preferredRemote(remoteNames(cwd, run));
336
+ if (picked.state === 'none') return { ...base, state: 'no-remote' };
337
+ if (picked.state === 'ambiguous') return { ...base, state: 'ambiguous-remote' };
338
+
339
+ const withRemote = { ...base, remote: picked.name, url: remoteUrl(picked.name, cwd, run) };
340
+ const upstream = upstreamOf(cwd, run);
341
+ if (!upstream) return { ...withRemote, state: 'no-upstream' };
342
+
343
+ const counts = aheadBehind(cwd, run);
344
+ if (!counts) return { ...withRemote, upstream, state: 'unreadable', why: 'could not count against the upstream' };
345
+ return { ...withRemote, upstream, ...counts, state: 'ok' };
346
+ }
347
+
348
+ // ── the words ──────────────────────────────────────────────────────────────
349
+ //
350
+ // Four places tell you about unpushed work — a toast while authoring, a line
351
+ // when author mode exits, the history overlay's footer, and `decklight
352
+ // history` — and they must not disagree. So none of them writes a sentence:
353
+ // they all call one of the three functions below. A wording change is then a
354
+ // diff in one file with a test beside it, rather than four strings that were
355
+ // the same in March.
356
+
357
+ /** The push command that would actually work here, given what is set up. */
358
+ const pushCommand = (s) => (s.state === 'no-upstream'
359
+ ? `git push -u ${s.remote} ${s.branch}`
360
+ : 'git push');
361
+
362
+ /**
363
+ * Is there something to nudge about, and how much? `null` for "say nothing".
364
+ *
365
+ * The `ahead === 0` row returning null is the do-not-nag guarantee, and it is
366
+ * stated here rather than at each call site so it cannot be forgotten at one of
367
+ * them. A repository with NO remote also returns null: telling someone to push
368
+ * when there is nowhere to push is noise, and that nudge belongs to `init`.
369
+ */
370
+ export function pushHint(s) {
371
+ if (!s || ['no-git', 'no-repo', 'unborn', 'unreadable'].includes(s.state)) return null;
372
+ if (s.state === 'detached') return { kind: 'detached', n: 0, text: 'detached HEAD — there is no branch to push' };
373
+ if (s.state === 'no-remote' || s.state === 'ambiguous-remote') return null;
374
+ const n = s.state === 'ok' ? s.ahead : s.unpushed;
375
+ if (!n) return null;
376
+ return { kind: s.state === 'ok' ? 'unpushed' : 'no-upstream', n, text: `↑${n} unpushed — ${pushCommand(s)}` };
377
+ }
378
+
379
+ /**
380
+ * The line author mode prints on its way out, or null for a clean exit.
381
+ *
382
+ * This one DOES speak up when there is no remote, unlike `pushHint` — the end
383
+ * of a session is the moment when "this only exists here" is worth knowing, and
384
+ * it is said once rather than every few minutes.
385
+ */
386
+ export function exitPushLine(s) {
387
+ if (!s) return null;
388
+ if (s.state === 'no-remote' || s.state === 'ambiguous-remote') {
389
+ return s.unpushed
390
+ ? ` this deck's history is only on this machine — back it up: git remote add origin <url>`
391
+ : null;
392
+ }
393
+ const hint = pushHint(s);
394
+ if (!hint || !hint.n) return null;
395
+ return ` ↑${hint.n} commit${hint.n === 1 ? '' : 's'} only on this machine — ${pushCommand(s)}`;
396
+ }
397
+
398
+ /** The one-line readout `decklight history` and the overlay footer both show. */
399
+ export function remoteLine(s) {
400
+ if (!s) return '';
401
+ switch (s.state) {
402
+ case 'no-git': return 'git is not installed';
403
+ case 'no-repo': return 'not in a git repository';
404
+ case 'unborn': return 'nothing committed yet';
405
+ case 'detached': return `detached HEAD · ${s.unpushed ?? 0} commits here`;
406
+ case 'no-remote': return `${s.branch} · no remote — this history is only on this machine`;
407
+ case 'ambiguous-remote': return `${s.branch} · several remotes, none named origin — push by name`;
408
+ case 'no-upstream': return s.unpushed
409
+ ? `${s.branch} → no upstream (${s.remote} exists) · ↑${s.unpushed} never pushed`
410
+ : `${s.branch} → no upstream — ${s.remote} exists but this branch tracks nothing`;
411
+ case 'unreadable': return `${s.branch} → ${s.upstream} · could not be counted`;
412
+ default: {
413
+ const bits = [`${s.branch} → ${s.upstream}`];
414
+ if (s.ahead) bits.push(`↑${s.ahead} unpushed`);
415
+ if (s.behind) bits.push(`↓${s.behind} behind`);
416
+ if (!s.ahead && !s.behind) bits.push('all pushed');
417
+ return bits.join(' · ');
418
+ }
419
+ }
420
+ }
421
+
422
+ // ── what else rides along ──────────────────────────────────────────────────
423
+ //
424
+ // A fast-forward updates the WHOLE working tree. If the deck shares a
425
+ // repository with anything else, "update the deck" quietly means "update the
426
+ // source tree, the CI config and the scripts too" — and the person clicking is
427
+ // thinking about a slide.
428
+ //
429
+ // The measure is deliberately what a given change WOULD touch rather than what
430
+ // the repository contains, because that is the number worth interrupting for:
431
+ // a repo that holds only a deck stays silent, and one that holds a product says
432
+ // so with the file names.
433
+
434
+ /**
435
+ * Split a list of paths into the deck's own and everything else.
436
+ *
437
+ * Pure, and the definition of "the deck's own" is the interesting part: the
438
+ * deck file plus anything under the directory it lives in. Themes, images and
439
+ * narration travel WITH a deck and are not a surprise; `src/server.js` is.
440
+ * Paths arrive relative to the repository root, which is how git reports them.
441
+ */
442
+ export function splitDeckPaths(paths = [], deckRelPath = '') {
443
+ const deck = String(deckRelPath).replace(/^\.\//, '');
444
+ const dir = deck.includes('/') ? `${deck.slice(0, deck.lastIndexOf('/'))}/` : '';
445
+ const own = [];
446
+ const foreign = [];
447
+ for (const p of paths) {
448
+ const rel = String(p).replace(/^\.\//, '');
449
+ if (!rel) continue;
450
+ (rel === deck || (dir && rel.startsWith(dir)) ? own : foreign).push(rel);
451
+ }
452
+ return { own, foreign };
453
+ }
454
+
455
+ /**
456
+ * What pulling `range` would change, and how much of it is not the deck.
457
+ *
458
+ * `range` is `HEAD..@{u}` for a pull; the same shape answers "what would be
459
+ * pushed" for a range the other way round. Unreadable is `null` — a warning
460
+ * nobody can compute must not become a warning nobody can dismiss.
461
+ */
462
+ export function foreignChanges(cwd, deckRelPath, range = 'HEAD..@{u}', run = git) {
463
+ let paths;
464
+ try { paths = run(['diff', '--name-only', range], cwd).split('\n').filter(Boolean); }
465
+ catch { return null; }
466
+ const { own, foreign } = splitDeckPaths(paths, deckRelPath);
467
+ return { total: paths.length, own, foreign };
468
+ }
469
+
470
+ /**
471
+ * The warning itself, or null when there is nothing surprising to say.
472
+ *
473
+ * Names three files and counts the rest: a wall of paths is skimmed, and three
474
+ * is enough to recognise what kind of repository this is. The recommendation is
475
+ * the last line because it is the fix, not the finding.
476
+ */
477
+ export function foreignWarning(changes, { verb = 'pull', scope = 'the whole working tree' } = {}) {
478
+ if (!changes || !changes.foreign.length) return null;
479
+ const { total, foreign } = changes;
480
+ const shown = foreign.slice(0, 3).join(' · ');
481
+ const more = foreign.length > 3 ? ` · … ${foreign.length - 3} more` : '';
482
+ return [
483
+ `this ${verb} would change ${total} file${total === 1 ? '' : 's'}, `
484
+ + `${foreign.length} of them not the deck:`,
485
+ ` ${shown}${more}`,
486
+ `a ${verb} updates ${scope} — if that is not what you want here, keep the deck`
487
+ + ' in a repository of its own',
488
+ ];
489
+ }
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * `decklight history <deck.html>` — what decklight committed, and where it
7
+ * stands against the remote.
8
+ *
9
+ * WHY THIS IS NOT `decklight restore`. `restore` already prints this list, and
10
+ * for a while that was the argument against a second command. But its listing
11
+ * is a MEANS: the footer says `Restore one with: …`, and it exits 1 when there
12
+ * is nothing to restore, because it is an action that could not be performed.
13
+ * This is a READOUT. It answers "where does this deck stand", nobody types
14
+ * "restore" to ask that, and it must not fail just because the answer is
15
+ * "nowhere yet" — a readout that exits non-zero on an empty history breaks
16
+ * `decklight history && …` and reads as a malfunction.
17
+ *
18
+ * What it adds over that listing is the half `restore` has no business knowing:
19
+ * which commits exist nowhere but this machine, and what to type about it.
20
+ */
21
+
22
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
23
+ import { basename, dirname, join, relative, resolve } from 'node:path';
24
+ import { deckHistory, formatEntry } from './restore.mjs';
25
+ import {
26
+ gitAvailable, inGitRepo, oneline, pushHint, remoteLine, remoteState, unpushed,
27
+ } from './git.mjs';
28
+ import { argReader, isMain } from '../tools/args.mjs';
29
+
30
+ const HELP = `decklight history [deck.html] — the commits behind a deck, and what is unpushed
31
+
32
+ -n <count> how many to show (default 20)
33
+ --all every commit
34
+ --help, -h this
35
+
36
+ A readout, never a write. To go back to one of these: decklight restore <deck> <hash>
37
+ `;
38
+
39
+ /** Marks each entry with whether it exists anywhere but here. Pure. */
40
+ export function markPushState(entries, localHashes) {
41
+ const set = localHashes ? new Set(localHashes) : null;
42
+ return entries.map((e) => ({ ...e, pushed: set ? !set.has(e.full) : null }));
43
+ }
44
+
45
+ /**
46
+ * The single deck in `dir`, or null when the answer is not single.
47
+ *
48
+ * Nothing else in the CLI infers a deck, so the inference is deliberately
49
+ * narrow: a `.html` file that carries decklight's own runtime marker. A folder
50
+ * with three decks gets a refusal that names them rather than a guess.
51
+ */
52
+ export function findDeck(dir, read = readFileSync, list = readdirSync) {
53
+ let names;
54
+ try { names = list(dir).filter((f) => /\.html?$/i.test(f)); } catch { return { decks: [] }; }
55
+ const decks = names.filter((f) => {
56
+ try { return /data-decklight-runtime|Decklight\s*\.\s*init/.test(read(join(dir, f), 'utf8')); }
57
+ catch { return false; }
58
+ });
59
+ return { decks };
60
+ }
61
+
62
+ export function historyMain(argv = process.argv.slice(2)) {
63
+ const { opt } = argReader(argv);
64
+ if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); return 0; }
65
+
66
+ const cwd = process.cwd();
67
+ let deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
68
+ if (!deckArg) {
69
+ const { decks } = findDeck(cwd);
70
+ if (decks.length === 1) [deckArg] = decks;
71
+ else if (!decks.length) {
72
+ console.error('decklight history: name the deck — no decklight deck found in this directory');
73
+ return 1;
74
+ } else {
75
+ console.error(`decklight history: name the deck — this directory has ${decks.length}`
76
+ + ` (${decks.slice(0, 4).join(', ')}${decks.length > 4 ? ', …' : ''})`);
77
+ return 1;
78
+ }
79
+ }
80
+
81
+ const deckPath = resolve(cwd, deckArg);
82
+ const name = basename(deckPath);
83
+ if (!existsSync(deckPath)) { console.error(`decklight history: no such file: ${deckArg}`); return 1; }
84
+
85
+ const root = dirname(deckPath);
86
+ // git missing and "not a repository" are different answers, and inGitRepo
87
+ // swallows the first into the second.
88
+ if (!gitAvailable(root)) {
89
+ console.error('decklight history: git is not installed — decklight\'s durable record needs it');
90
+ return 1;
91
+ }
92
+ if (!inGitRepo(root)) {
93
+ console.error(`decklight history: ${name} is not in a git repository — there is no history yet`
94
+ + ' (decklight init --git, or git init)');
95
+ return 1;
96
+ }
97
+
98
+ // The state comes first because it answers the question that would otherwise
99
+ // look like a failure: in a repository with no commits at all, `git log`
100
+ // exits non-zero ("does not have any commits yet"), and reporting that as a
101
+ // read error would turn the ordinary first minute of a deck's life into an
102
+ // error message.
103
+ const state = remoteState(root);
104
+ if (state.state === 'unborn') {
105
+ console.log(`${name} — nothing committed yet`);
106
+ console.log(' the repository exists; the first commit does not');
107
+ return 0;
108
+ }
109
+
110
+ let entries;
111
+ try { entries = deckHistory(deckPath, root); }
112
+ catch (e) { console.error(`decklight history: could not read the history: ${oneline(e)}`); return 1; }
113
+ const marked = markPushState(entries, ['no-remote', 'ambiguous-remote'].includes(state.state)
114
+ ? null : unpushed(root));
115
+
116
+ // Not an error: a deck git has never seen is a true and useful answer, and it
117
+ // is the state every new deck starts in.
118
+ if (!marked.length) {
119
+ console.log(`${name} — git has no record of this file yet`);
120
+ console.log(` ${remoteLine(state)}`);
121
+ return 0;
122
+ }
123
+
124
+ const all = argv.includes('--all');
125
+ const limit = all ? marked.length : Math.max(1, Number(opt('-n', 20)) || 20);
126
+ const shown = marked.slice(0, limit);
127
+ const pad = Math.max(...shown.map((e) => e.when.length));
128
+
129
+ console.log(`${name} — ${marked.length} commit${marked.length === 1 ? '' : 's'}, newest first\n`);
130
+ for (const e of shown) {
131
+ // The ↑ trails the row rather than leading it, so the hashes still line up
132
+ // and an all-pushed deck reads clean rather than column-padded.
133
+ console.log(` ${formatEntry(e, pad)}${e.pushed === false ? ' ↑' : ''}`);
134
+ }
135
+ if (marked.length > shown.length) console.log(` … ${marked.length - shown.length} more (--all)`);
136
+
137
+ console.log(`\n ${remoteLine(state)}`);
138
+ const hint = pushHint(state);
139
+ if (hint) console.log(` ${hint.text.replace(/^↑\d+ unpushed — /, 'push them with: ')}`);
140
+ console.log(` restore one with: decklight restore ${relative(cwd, deckPath) || name}`
141
+ + ` ${shown[Math.min(1, shown.length - 1)].hash}`);
142
+ return 0;
143
+ }
144
+
145
+ if (isMain(import.meta.url)) process.exit(historyMain());