@osdlc/repo-cleaner 0.20.5 → 0.22.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +545 -165
  3. package/dist/approval.d.ts +91 -0
  4. package/dist/approval.js +233 -0
  5. package/dist/archive.d.ts +87 -0
  6. package/dist/archive.js +252 -0
  7. package/dist/branches.d.ts +4 -4
  8. package/dist/branches.js +56 -43
  9. package/dist/clean.d.ts +30 -70
  10. package/dist/clean.js +251 -197
  11. package/dist/cli.d.ts +16 -10
  12. package/dist/cli.js +252 -103
  13. package/dist/discover.d.ts +28 -7
  14. package/dist/discover.js +185 -42
  15. package/dist/index.d.ts +6 -3
  16. package/dist/index.js +5 -2
  17. package/dist/landing.d.ts +10 -5
  18. package/dist/landing.js +15 -16
  19. package/dist/plan.d.ts +18 -11
  20. package/dist/plan.js +33 -13
  21. package/dist/processes.d.ts +19 -9
  22. package/dist/processes.js +51 -25
  23. package/dist/providers/github.d.ts +21 -3
  24. package/dist/providers/github.js +149 -27
  25. package/dist/providers/gitlab.js +37 -17
  26. package/dist/providers/index.d.ts +1 -1
  27. package/dist/providers/index.js +1 -1
  28. package/dist/providers/types.d.ts +15 -2
  29. package/dist/prs.d.ts +19 -10
  30. package/dist/prs.js +21 -13
  31. package/dist/receipt.d.ts +68 -3
  32. package/dist/receipt.js +30 -3
  33. package/dist/reference.d.ts +1 -1
  34. package/dist/reference.js +93 -50
  35. package/dist/remote-mirror.d.ts +2 -1
  36. package/dist/remote-mirror.js +3 -14
  37. package/dist/render.d.ts +17 -2
  38. package/dist/render.js +80 -13
  39. package/dist/scope.d.ts +15 -0
  40. package/dist/scope.js +125 -0
  41. package/dist/size.d.ts +20 -0
  42. package/dist/size.js +34 -0
  43. package/dist/status-line.js +1 -0
  44. package/dist/step-board.js +6 -4
  45. package/dist/sweep.d.ts +45 -18
  46. package/dist/sweep.js +151 -127
  47. package/dist/types.d.ts +89 -10
  48. package/dist/types.js +50 -6
  49. package/dist/util.d.ts +2 -0
  50. package/dist/util.js +25 -0
  51. package/dist/version.generated.d.ts +1 -1
  52. package/dist/version.generated.js +1 -1
  53. package/dist/worktrees.js +87 -11
  54. package/package.json +6 -5
package/dist/cli.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
- * `repo-cleaner` — what has been merged, and what can go away.
2
+ * `repo-cleaner` — what has been merged, and what can go away. Nothing runs
3
+ * until a phase is named; the bare command explains them and exits 2.
3
4
  *
4
- * repo-cleaner [target...] the report; deletes nothing
5
- * repo-cleaner plan save the sweep's rows and their evidence, to run later
5
+ * repo-cleaner status look: every row and its verdict; deletes nothing
6
+ * repo-cleaner plan save what status found, to clean later
6
7
  * repo-cleaner clean check again, show the steps, ask, delete
7
8
  * repo-cleaner cache list or remove the clones kept for remote URL targets
8
9
  *
@@ -12,21 +13,26 @@
12
13
  * with an option that would have no effect, is refused with exit 2 before
13
14
  * anything is swept.
14
15
  *
15
- * Exit codes:
16
- * 0 swept; or clean ran, was declined, or had nothing to do
17
- * 1 failed against the state it found
18
- * 2 cannot run as typed
19
- * 10 no target named a repository
20
- * 11 clean stopped at a failed step; the receipt says which
16
+ * Exit codes: see EXIT in src/reference.ts (shown by --help --extended).
21
17
  */
22
- import { type CliContext } from '@osdlc/cli-tool';
18
+ import { type ChecklistItem, type CliContext } from '@osdlc/cli-tool';
19
+ import { type Runners } from './sweep.ts';
23
20
  /**
24
21
  * Asks a yes/no question, or returns null when there is no one to ask. `main`
25
22
  * takes it as a parameter so a test can answer.
26
23
  */
27
24
  export type Confirm = (question: string) => boolean | null;
25
+ /**
26
+ * Shows a checklist and returns the ticked indexes, or null when there is no
27
+ * one to ask. `main` takes it as a parameter so a test can answer.
28
+ */
29
+ export type Checklist = (question: string, items: readonly ChecklistItem[]) => number[] | null;
28
30
  export interface MainDeps {
29
31
  confirm?: Confirm;
32
+ /** Answers `clean -i`. Defaults to a checklist on the terminal. */
33
+ checklist?: Checklist;
34
+ /** The `git`, `gh` and `glab` runners and the process probe every phase uses. Default: the real ones. */
35
+ runners?: Runners;
30
36
  /** Reads `--plan -`. Defaults to stdin. */
31
37
  readStdin?: () => string;
32
38
  /** Whether stderr is a terminal, so a status line may be drawn. Defaults to `isatty(2)`. */
package/dist/cli.js CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
- * `repo-cleaner` — what has been merged, and what can go away.
2
+ * `repo-cleaner` — what has been merged, and what can go away. Nothing runs
3
+ * until a phase is named; the bare command explains them and exits 2.
3
4
  *
4
- * repo-cleaner [target...] the report; deletes nothing
5
- * repo-cleaner plan save the sweep's rows and their evidence, to run later
5
+ * repo-cleaner status look: every row and its verdict; deletes nothing
6
+ * repo-cleaner plan save what status found, to clean later
6
7
  * repo-cleaner clean check again, show the steps, ask, delete
7
8
  * repo-cleaner cache list or remove the clones kept for remote URL targets
8
9
  *
@@ -12,63 +13,69 @@
12
13
  * with an option that would have no effect, is refused with exit 2 before
13
14
  * anything is swept.
14
15
  *
15
- * Exit codes:
16
- * 0 swept; or clean ran, was declined, or had nothing to do
17
- * 1 failed against the state it found
18
- * 2 cannot run as typed
19
- * 10 no target named a repository
20
- * 11 clean stopped at a failed step; the receipt says which
16
+ * Exit codes: see EXIT in src/reference.ts (shown by --help --extended).
21
17
  */
22
18
  import { readSync, rmSync } from 'node:fs';
23
19
  import { basename, dirname, join, resolve } from 'node:path';
24
20
  import { isatty } from 'node:tty';
25
- import { EXIT, askYesNo, canPrompt, defineCli, renderError, } from '@osdlc/cli-tool';
21
+ import { EXIT, askChecklist, askYesNo, canPrompt, defineCli, renderError, } from '@osdlc/cli-tool';
26
22
  import { detectColorLevel, stripControls } from '@osdlc/ux';
27
- import { check, checkApproval, parseAllow, run } from "./clean.js";
28
- import { fileStamp, parsePlan, plan as planOf, readPlan, writePlan } from "./plan.js";
23
+ import { allowed, checkApproval, keyOf, parseAllow, resolveApproval, } from "./approval.js";
24
+ import { check, run } from "./clean.js";
25
+ import { fileStamp, parsePlan, plan as planOf, readPlan, runnable, writePlan, } from "./plan.js";
29
26
  import { PROVIDER_CHOICES } from "./providers/index.js";
30
27
  import { REFERENCE } from "./reference.js";
31
28
  import { cachedMirrorOf, defaultCacheDir, listMirrors, redactUrl, } from "./remote-mirror.js";
32
29
  import { PLAIN, TERMINAL_STYLE, renderCommands, renderJson, renderLateDrops, renderPreview, renderReceipt, renderStepFailure, renderSummary, renderText, renderTotals, rowsActedOn, summarizeRun, } from "./render.js";
33
30
  import { NO_STATUS_LINE, describeStep, describeSweep, statusLine, } from "./status-line.js";
31
+ import { formatBytes } from "./size.js";
34
32
  import { stepBoard } from "./step-board.js";
35
- import { sweep as sweepTargets, sweptWith } from "./sweep.js";
33
+ import { sweptWith } from "./scope.js";
34
+ import { sweep as sweepTargets } from "./sweep.js";
36
35
  import { KINDS, RISKS, RepoCleanerError, sweepNotes, } from "./types.js";
37
36
  const EXIT_NOTHING_TO_SWEEP = 10;
38
37
  const EXIT_STEP_FAILED = 11;
39
38
  const NAME = 'repo-cleaner';
39
+ const NO_TERMINAL_FOR_I = '-i needs a terminal to ask on; name the rows with --pick and --spare instead';
40
40
  /** `--help` and its modifier: commander must not own `--help`, or it would never see `--extended`. */
41
41
  const HELP_FLAGS = {
42
42
  help: { kind: 'boolean', short: 'h', help: 'show this message' },
43
43
  extended: { kind: 'boolean', help: 'with --help: the full reference' },
44
44
  };
45
- /** The flags every command that sweeps takes. */
46
- const SWEEP_FLAGS = {
45
+ /** Which rows a phase looks at. With none of them, `--local`. */
46
+ const SCOPE_FLAGS = {
47
+ local: { kind: 'boolean', help: 'worktrees and local branches (the default)' },
47
48
  remote: {
48
- kind: 'boolean',
49
- help: 'also judge remote branches: fetches first and looks up pull requests; slower',
50
- },
51
- offline: { kind: 'boolean', help: 'with --remote: do not fetch' },
52
- only: {
53
49
  kind: 'list',
54
- valueName: 'kinds',
55
- help: `only these kinds of row: ${KINDS.join(', ')} (default: worktree,branch; remote too with --remote)`,
50
+ valueName: 'name',
51
+ valueAfterEquals: true,
52
+ commaSeparated: false,
53
+ help: "branches on the default remote; --remote=<name> another, --remote='*' every remote; repeatable",
56
54
  },
55
+ all: { kind: 'boolean', help: '--local and --remote' },
56
+ worktrees: { kind: 'boolean', help: 'only worktrees, of the local rows' },
57
+ branches: { kind: 'boolean', help: 'only local branches, of the local rows' },
58
+ };
59
+ /** The flags every phase that looks takes. */
60
+ const SWEEP_FLAGS = {
61
+ ...SCOPE_FLAGS,
62
+ fetch: { kind: 'boolean', help: 'fetch the default remote before judging local rows' },
63
+ offline: { kind: 'boolean', help: 'no network: no fetch, judge from the refs on disk' },
57
64
  branch: {
58
65
  kind: 'string',
59
66
  valueName: 'name|HEAD',
60
- help: "only one branch's rows: its worktree, local branch, and remote branch with --remote",
67
+ help: "one branch's rows: its worktree, local branch, and remote branches",
61
68
  },
62
69
  against: {
63
70
  kind: 'string',
64
71
  valueName: 'remote',
65
- help: 'the remote whose default branch counts as merged into (default: origin)',
72
+ help: "judge every row against this remote's default branch (a fork against its parent)",
66
73
  },
67
74
  provider: {
68
75
  kind: 'enum',
69
76
  choices: PROVIDER_CHOICES,
70
77
  valueName: 'name',
71
- help: 'with --remote: where pull requests come from',
78
+ help: 'with remote rows: where pull requests come from',
72
79
  },
73
80
  progress: { kind: 'boolean', negatable: true, help: 'no progress line on stderr' },
74
81
  };
@@ -88,16 +95,43 @@ const TARGETS = [
88
95
  },
89
96
  ];
90
97
  const MORE = `Run with --help --extended for the full reference: what every option means, the words the report uses, and which combinations are refused.`;
91
- const reportCli = () => defineCli({
92
- name: NAME,
93
- summary: 'Say which worktrees and local branches (remote branches too, with --remote) are merged ' +
94
- 'into the default branch and can go, with the evidence and the command that would delete ' +
95
- 'each. Deletes nothing.',
98
+ const PHASES = `phases:
99
+ ${NAME} status look: every row and its verdict, with the command that would delete it
100
+ ${NAME} plan save what status found, to clean later or hand over
101
+ ${NAME} clean check again, show the steps, ask, delete
102
+ ${NAME} cache list or remove the clones kept for remote URL targets`;
103
+ /** What the bare command prints: the phases, and that nothing ran. */
104
+ const OVERVIEW = `${NAME} finds worktrees and branches whose work has landed, and deletes them safely.
105
+
106
+ It works in phases. Nothing is deleted until clean, and only what is safe.
107
+
108
+ 1. status Look: each worktree and branch, with a verdict and the reason.
109
+ $ ${NAME} status this repository
110
+ $ ${NAME} status --all local and remote branches
111
+ 2. plan Optional: save what status found, to run later or hand on.
112
+ $ ${NAME} plan --all -o plan.json
113
+ 3. clean Delete what is safe: checks each row again, shows the steps, asks.
114
+ $ ${NAME} clean asks first
115
+ $ ${NAME} clean -y does not ask
116
+ $ ${NAME} clean --plan plan.json
117
+
118
+ Nothing ran. Name a phase; \`${NAME} <phase> --help\` shows its options.
119
+ \`${NAME} cache\` manages the clones of remote URL targets; \`${NAME} dev\` runs a
120
+ development checkout.
121
+ `;
122
+ const statusCli = () => defineCli({
123
+ name: `${NAME} status`,
124
+ summary: 'Sort every worktree and local branch (remote branches too, with --remote) into a ' +
125
+ 'verdict, with the evidence and the command that would delete each. Deletes nothing.',
96
126
  autoHelp: false,
97
127
  positionals: TARGETS,
98
128
  flags: {
99
129
  ...SWEEP_FLAGS,
100
- all: { kind: 'boolean', help: 'also show keep rows (with --format text)' },
130
+ sizes: {
131
+ kind: 'boolean',
132
+ help: "read each worktree's size on disk: rank rows largest first and total what can be freed; slower",
133
+ },
134
+ allRows: { kind: 'boolean', help: 'also show keep rows (with --format text)' },
101
135
  format: {
102
136
  kind: 'enum',
103
137
  choices: ['text', 'json', 'summary', 'commands'],
@@ -107,16 +141,8 @@ const reportCli = () => defineCli({
107
141
  },
108
142
  ...HELP_FLAGS,
109
143
  },
110
- shortEpilogue: `commands:
111
- ${NAME} [target...] this report (the default)
112
- ${NAME} plan save the sweep's rows and their evidence, to run later
113
- ${NAME} clean check again, show the steps, ask, delete
114
- ${NAME} cache list or remove the clones kept for remote URL targets
115
- ${NAME} dev run ${NAME} from a development checkout
116
-
117
- A checkout directory named like a command is swept as ./<name>.
118
- ${MORE}`,
119
- epilogue: REFERENCE.report,
144
+ shortEpilogue: `${PHASES}\n\n${MORE}`,
145
+ epilogue: REFERENCE.status,
120
146
  });
121
147
  const planCli = () => defineCli({
122
148
  name: `${NAME} plan`,
@@ -140,16 +166,33 @@ const planCli = () => defineCli({
140
166
  });
141
167
  const cleanCli = () => defineCli({
142
168
  name: `${NAME} clean`,
143
- summary: 'Delete what the sweep (or a saved plan) found: check each row again, show the steps, ask, ' +
144
- 'then delete, compare-and-swap, verifying each step. Without --pick, every row judged ' +
145
- 'delete runs.',
169
+ summary: 'Delete what status (or a saved plan) found: check each row again, show the steps, ask, ' +
170
+ 'then delete, compare-and-swap, verifying each step. Every row judged delete runs, and ' +
171
+ 'each row picked.',
146
172
  autoHelp: false,
147
173
  positionals: TARGETS,
148
174
  flags: {
149
175
  ...SWEEP_FLAGS,
150
- pick: rowList('row', 'work on exactly these rows; a review row runs only when picked; repeatable'),
151
- spare: rowList('row', 'leave this row alone; a spared remote branch that moved stops the run; repeatable'),
176
+ pick: rowList('row', 'also run this row; a review row runs only when picked; repeatable'),
177
+ spare: rowList('row|glob', 'leave these rows alone; a remote branch spared by name that moved stops the run; repeatable'),
178
+ interactive: {
179
+ kind: 'boolean',
180
+ short: 'i',
181
+ help: 'choose the rows from a checklist; needs a terminal',
182
+ },
152
183
  allow: rowList('risk[=row]', 'accept a risk for every row, or for one row; repeatable'),
184
+ archive: {
185
+ kind: 'boolean',
186
+ help: 'push unlanded work to an archive branch on the remote before deleting it; ' +
187
+ 'then --allow discard-archived stands for abandon-unmerged and discard-changes',
188
+ },
189
+ archiveExclude: {
190
+ kind: 'list',
191
+ valueName: 'glob',
192
+ default: [],
193
+ commaSeparated: false,
194
+ help: 'with --archive, leave files matching this glob out of a worktree snapshot; repeatable',
195
+ },
153
196
  plan: {
154
197
  kind: 'string',
155
198
  valueName: 'file',
@@ -201,6 +244,7 @@ const cacheCli = () => defineCli({
201
244
  epilogue: REFERENCE.cache,
202
245
  });
203
246
  const terminalConfirm = (question) => (canPrompt() ? askYesNo(question) : null);
247
+ const terminalChecklist = (question, items) => canPrompt() ? askChecklist(question, items) : null;
204
248
  const PAUSE = new Int32Array(new SharedArrayBuffer(4));
205
249
  /**
206
250
  * All of stdin, synchronously. A pipe can be non-blocking and still empty
@@ -241,13 +285,23 @@ function refusal(ctx, name, err) {
241
285
  }
242
286
  return failure(ctx, name, err);
243
287
  }
244
- /** Parse, and answer `--help` (and `--help --extended`) itself. */
245
- function parseWith(cli, name, argv, ctx) {
288
+ /** Flags only `status` takes, each with what `plan` and `clean` say when given it. */
289
+ const STATUS_ONLY = {
290
+ '--sizes': `--sizes is a status flag: run \`${NAME} status --sizes\``,
291
+ };
292
+ /**
293
+ * Parse, and answer `--help` (and `--help --extended`) itself. An unknown
294
+ * option named in `elsewhere` is refused with its message there instead of
295
+ * the parser's.
296
+ */
297
+ function parseWith(cli, name, argv, ctx, elsewhere = {}) {
246
298
  const parsed = cli.parse(argv, ctx.io);
247
299
  if (parsed.status === 'help')
248
300
  return { status: 'done', code: EXIT.ok };
249
301
  if (parsed.status === 'error') {
250
- return { status: 'done', code: usageError(ctx, name, parsed.message) };
302
+ const flag = /^unknown option '(--[^'=]+)/.exec(parsed.message)?.[1];
303
+ const message = (flag === undefined ? undefined : elsewhere[flag]) ?? parsed.message;
304
+ return { status: 'done', code: usageError(ctx, name, message) };
251
305
  }
252
306
  const v = parsed.values;
253
307
  if (v.help) {
@@ -259,14 +313,43 @@ function parseWith(cli, name, argv, ctx) {
259
313
  }
260
314
  return parsed;
261
315
  }
262
- /** The sweep options as typed, for {@link sweptWith} and {@link sweepTargets}. */
263
- function sweepOptions(v, ctx) {
264
- const only = v.only?.filter((s) => s !== '');
316
+ /**
317
+ * The kinds of row and the remotes the scope flags name. No scope flag is
318
+ * `--local`; `--worktrees` and `--branches` narrow the local rows; the flags
319
+ * add up. Throws a `conflict` for `--all` beside a named remote.
320
+ */
321
+ function scopeOf(v) {
322
+ // No scope flag: the library's default, which also lets a remote URL target
323
+ // sweep its remote branches.
324
+ if (!v.local && v.remote === undefined && !v.all && !v.worktrees && !v.branches) {
325
+ return { remotes: [] };
326
+ }
327
+ const remotes = [...(v.remote ?? [])];
328
+ if (v.all && remotes.some((r) => r !== '')) {
329
+ throw new RepoCleanerError('conflict', '--all is --local and the default remote; with other remotes, write them out: --local --remote=<name>');
330
+ }
331
+ if (v.all)
332
+ remotes.push('');
333
+ const narrowed = v.worktrees || v.branches;
334
+ const local = narrowed
335
+ ? KINDS.filter((k) => (k === 'worktree' && v.worktrees) || (k === 'branch' && v.branches))
336
+ : v.local || v.all || remotes.length === 0
337
+ ? ['worktree', 'branch']
338
+ : [];
339
+ return { only: remotes.length > 0 ? [...local, 'remote'] : local, remotes };
340
+ }
341
+ /**
342
+ * The sweep options as typed, for {@link sweptWith} and {@link sweepTargets}.
343
+ * Only `status` takes `--sizes`.
344
+ */
345
+ function sweepOptions(v, ctx, deps) {
265
346
  return {
347
+ ...deps.runners,
266
348
  cwd: ctx.cwd,
267
- remote: v.remote,
349
+ ...scopeOf(v),
350
+ fetch: v.fetch,
268
351
  offline: v.offline,
269
- ...(only === undefined ? {} : { only: only }),
352
+ sizes: v.sizes === true,
270
353
  ...(v.branch === undefined ? {} : { branch: v.branch }),
271
354
  ...(v.against === undefined ? {} : { against: v.against }),
272
355
  ...(v.provider === undefined ? {} : { provider: v.provider }),
@@ -284,21 +367,22 @@ function remoteNote(s, style) {
284
367
  return '';
285
368
  if (!s.repos.some((r) => r.repo?.remote != null))
286
369
  return '';
287
- return (style.muted('Local only: nothing fetched, no pull requests looked up, remote branches not checked; add --remote for all three.') + '\n');
370
+ const fetched = s.options.fetch ? '' : 'nothing fetched, ';
371
+ return (style.muted(`Local only: ${fetched}no pull requests looked up, remote branches not checked; --all adds the default remote's branches.`) + '\n');
288
372
  }
289
373
  /** Sweep, or answer with the exit code. */
290
- function doSweep(name, v, targets, ctx, status) {
291
- const opts = {
292
- ...sweepOptions(v, ctx),
293
- // Mid-walk, while the wait is happening: the totals come too late to
294
- // explain why the tool appeared to hang.
295
- onWarn: (message) => ctx.io.stderr(`${NAME}: ${message}\n`),
296
- ...(v.progress ? { onProgress: (p) => status.update(describeSweep(p)) } : {}),
297
- };
298
- if (v.progress)
299
- status.update(`${NAME}: finding repositories`);
374
+ function doSweep(name, v, targets, ctx, deps, status) {
300
375
  let result;
301
376
  try {
377
+ const opts = {
378
+ ...sweepOptions(v, ctx, deps),
379
+ // Mid-walk, while the wait is happening: the totals come too late to
380
+ // explain why the tool appeared to hang.
381
+ onWarn: (message) => ctx.io.stderr(`${NAME}: ${message}\n`),
382
+ ...(v.progress ? { onProgress: (p) => status.update(describeSweep(p)) } : {}),
383
+ };
384
+ if (v.progress)
385
+ status.update(`${NAME}: finding repositories`);
302
386
  result = sweepTargets(targets, opts);
303
387
  }
304
388
  catch (err) {
@@ -333,16 +417,17 @@ function writeNotes(ctx, name, notes) {
333
417
  for (const { repo, note } of notes)
334
418
  ctx.io.stderr(renderError(`${repo}: ${note}`, name));
335
419
  }
336
- function runReport(argv, ctx, status) {
337
- const parsed = parseWith(reportCli(), NAME, argv, ctx);
420
+ function runStatus(argv, ctx, deps, status) {
421
+ const name = `${NAME} status`;
422
+ const parsed = parseWith(statusCli(), name, argv, ctx);
338
423
  if (parsed.status === 'done')
339
424
  return parsed.code;
340
425
  const v = parsed.values;
341
- if (v.all && v.format !== 'text') {
342
- return usageError(ctx, NAME, `--all has no effect with --format ${v.format}: it shows keep rows in the text report`);
426
+ if (v.allRows && v.format !== 'text') {
427
+ return usageError(ctx, name, `--all-rows has no effect with --format ${v.format}: it shows keep rows in the text report`);
343
428
  }
344
429
  const style = styleFor(ctx, 'stdout');
345
- const swept = doSweep(NAME, v, parsed.positionals, ctx, status);
430
+ const swept = doSweep(name, v, parsed.positionals, ctx, deps, status);
346
431
  if (swept.kind === 'exit')
347
432
  return swept.code;
348
433
  const s = swept.sweep;
@@ -351,23 +436,23 @@ function runReport(argv, ctx, status) {
351
436
  else if (v.format === 'summary')
352
437
  ctx.io.stdout(renderSummary(s, style) + remoteNote(s, style));
353
438
  else if (v.format === 'commands') {
354
- reportNotes(ctx, NAME, s);
439
+ reportNotes(ctx, name, s);
355
440
  const commands = renderCommands(s);
356
441
  if (commands.length > 0)
357
442
  ctx.io.stdout(commands.join('\n') + '\n');
358
443
  }
359
444
  else {
360
- ctx.io.stdout(renderText(s, { all: v.all, style }) + remoteNote(s, style));
445
+ ctx.io.stdout(renderText(s, { all: v.allRows, style }) + remoteNote(s, style));
361
446
  }
362
447
  return swept.kind === 'nothing' ? EXIT_NOTHING_TO_SWEEP : EXIT.ok;
363
448
  }
364
- function runPlan(argv, ctx, status) {
449
+ function runPlan(argv, ctx, deps, status) {
365
450
  const name = `${NAME} plan`;
366
- const parsed = parseWith(planCli(), name, argv, ctx);
451
+ const parsed = parseWith(planCli(), name, argv, ctx, STATUS_ONLY);
367
452
  if (parsed.status === 'done')
368
453
  return parsed.code;
369
454
  const v = parsed.values;
370
- const swept = doSweep(name, v, parsed.positionals, ctx, status);
455
+ const swept = doSweep(name, v, parsed.positionals, ctx, deps, status);
371
456
  if (swept.kind === 'exit')
372
457
  return swept.code;
373
458
  // stdout carries only the plan, so the totals go to stderr either way.
@@ -399,31 +484,79 @@ const dropKey = (d) => JSON.stringify([d.repo, d.row]);
399
484
  /** The run's options that contradict each other, as a usage message, or null. */
400
485
  function cleanConflict(v, targets) {
401
486
  if (v.plan !== undefined) {
402
- const fixed = [
403
- targets.length > 0 ? 'targets' : null,
404
- v.only !== undefined ? '--only' : null,
405
- v.branch !== undefined ? '--branch' : null,
406
- v.remote ? '--remote' : null,
407
- v.offline ? '--offline' : null,
408
- v.against !== undefined ? '--against' : null,
409
- v.provider !== undefined ? '--provider' : null,
410
- ].filter((f) => f !== null);
487
+ // Every sweep flag given, so a new one cannot be missed here. `progress`
488
+ // only draws.
489
+ const given = Object.keys(SWEEP_FLAGS).filter((k) => k !== 'progress' && v[k] !== undefined && v[k] !== false);
490
+ const fixed = [...(targets.length > 0 ? ['targets'] : []), ...given.map((k) => `--${k}`)];
411
491
  if (fixed.length > 0)
412
492
  return `--plan already fixed what is swept; drop ${fixed.join(', ')}`;
413
493
  }
494
+ if (v.interactive && v.pick.length > 0) {
495
+ return '-i chooses the rows from a checklist; drop --pick, or drop -i';
496
+ }
497
+ if (v.interactive && v.plan === '-') {
498
+ return '-i asks on the terminal, and --plan - reads the plan from stdin; save the plan to a file';
499
+ }
414
500
  if (v.plan === '-' && !v.yes && !v.dryRun) {
415
501
  return '--plan - reads the plan from stdin, so nothing can ask; pass --yes or --dry-run';
416
502
  }
503
+ if (!v.archive && v.archiveExclude.length > 0) {
504
+ return '--archive-exclude has no effect without --archive';
505
+ }
417
506
  if (v.yes && v.dryRun)
418
507
  return '--yes and --dry-run contradict: one deletes without asking, the other deletes nothing';
419
508
  if (v.receipt !== undefined && v.dryRun)
420
509
  return '--receipt has no effect with --dry-run: nothing runs to record';
421
510
  return null;
422
511
  }
512
+ /**
513
+ * `-i`: the plan's rows as a checklist, `delete` rows ticked, rows that can
514
+ * never run shown but not selectable, spared rows left out; then each ticked
515
+ * row's risks, asked for by name. The answer is an approval that selects
516
+ * exactly the ticked rows, or null when there is no one to ask.
517
+ */
518
+ function chooseRows(plan, sweep, approval, ctx, deps) {
519
+ const given = resolveApproval(plan, { spare: approval.spare, allow: approval.allow }, ctx.cwd);
520
+ const left = new Set([...given.spare, ...given.spareMatched].map(keyOf));
521
+ const why = new Map((sweep?.repos ?? []).flatMap((r) => r.repo === null
522
+ ? []
523
+ : r.rows.map((row) => [keyOf({ repo: r.repo.root, id: row.id }), row.why])));
524
+ const rows = plan.repos.flatMap((r) => r.rows
525
+ .map((row) => ({ at: { repo: r.root, id: row.id }, row }))
526
+ .filter(({ at }) => !left.has(keyOf(at))));
527
+ if (rows.length === 0)
528
+ return { spare: approval.spare, allow: approval.allow };
529
+ const several = plan.repos.length > 1;
530
+ const items = rows.map(({ at, row }) => {
531
+ const reason = why.get(keyOf(at));
532
+ const label = `${row.id} ${row.verdict}${reason === undefined ? '' : `: ${reason}`}${several ? ` (${at.repo})` : ''}`;
533
+ const runs = runnable(row);
534
+ return {
535
+ label,
536
+ checked: runs && row.verdict === 'delete',
537
+ ...(runs ? {} : { disabled: row.verdict }),
538
+ };
539
+ });
540
+ const ticked = (deps.checklist ?? terminalChecklist)('Clean which rows?', items);
541
+ if (ticked === null)
542
+ return null;
543
+ const allow = [...(approval.allow ?? [])];
544
+ const ask = deps.confirm ?? terminalConfirm;
545
+ for (const i of ticked) {
546
+ const { at, row } = rows[i];
547
+ for (const risk of row.risks) {
548
+ if (allowed(given.allow, at, risk))
549
+ continue;
550
+ if (ask(`${row.id} carries ${risk}: allow it?`) === true)
551
+ allow.push({ risk, row: at });
552
+ }
553
+ }
554
+ return { select: ticked.map((i) => rows[i].at), spare: approval.spare, allow };
555
+ }
423
556
  function loadPlan(name, v, targets, ctx, deps, status, now) {
424
557
  const receiptPath = v.receipt === undefined ? undefined : resolve(ctx.cwd, v.receipt);
425
558
  if (v.plan === undefined) {
426
- const swept = doSweep(name, v, targets, ctx, status);
559
+ const swept = doSweep(name, v, targets, ctx, deps, status);
427
560
  if (swept.kind === 'exit')
428
561
  return swept.code;
429
562
  if (swept.kind === 'nothing') {
@@ -458,7 +591,7 @@ function loadPlan(name, v, targets, ctx, deps, status, now) {
458
591
  }
459
592
  function runClean(argv, ctx, deps, status) {
460
593
  const name = `${NAME} clean`;
461
- const parsed = parseWith(cleanCli(), name, argv, ctx);
594
+ const parsed = parseWith(cleanCli(), name, argv, ctx, STATUS_ONLY);
462
595
  if (parsed.status === 'done')
463
596
  return parsed.code;
464
597
  const v = parsed.values;
@@ -473,11 +606,14 @@ function runClean(argv, ctx, deps, status) {
473
606
  const conflict = cleanConflict(v, targets);
474
607
  if (conflict !== null)
475
608
  return usageError(ctx, name, conflict);
609
+ if (v.interactive && deps.checklist === undefined && !canPrompt()) {
610
+ return usageError(ctx, name, NO_TERMINAL_FOR_I);
611
+ }
476
612
  // Refuse what can be refused before sweeping; a saved plan's own options
477
613
  // are checked when the approval is resolved against it.
478
614
  if (v.plan === undefined) {
479
615
  try {
480
- checkApproval(sweptWith(targets, sweepOptions(v, ctx)), approval);
616
+ checkApproval(sweptWith(targets, sweepOptions(v, ctx, deps)), approval);
481
617
  }
482
618
  catch (err) {
483
619
  return refusal(ctx, name, err);
@@ -489,12 +625,26 @@ function runClean(argv, ctx, deps, status) {
489
625
  return loaded;
490
626
  const { plan, source, receiptPath } = loaded;
491
627
  const ok = () => (loaded.unreadable ? EXIT.error : EXIT.ok);
628
+ if (v.interactive) {
629
+ try {
630
+ const chosen = chooseRows(plan, loaded.sweep, approval, ctx, deps);
631
+ if (chosen === null) {
632
+ return usageError(ctx, name, NO_TERMINAL_FOR_I);
633
+ }
634
+ approval = chosen;
635
+ }
636
+ catch (err) {
637
+ return refusal(ctx, name, err);
638
+ }
639
+ }
492
640
  // On a terminal the run is shown live: every step first, then each one
493
641
  // checked off as it finishes.
494
642
  const live = v.format === 'text' && ctx.terminal?.stdout === true;
495
643
  const style = styleFor(ctx, 'stdout');
496
644
  const shared = {
645
+ ...deps.runners,
497
646
  cwd: ctx.cwd,
647
+ ...(v.archive ? { archive: { exclude: v.archiveExclude } } : {}),
498
648
  ...(v.progress
499
649
  ? {
500
650
  onProgress: (p) => status.update(`re-checking ${describeSweep(p)}`),
@@ -634,23 +784,11 @@ function confirm(ctx, name, preview, count, json, deps) {
634
784
  }
635
785
  return null;
636
786
  }
637
- /** `bytes` as a short size: `512 B`, `3.4 MB`. */
638
- function sizeText(bytes) {
639
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
640
- let value = bytes;
641
- let unit = 0;
642
- while (value >= 1024 && unit < units.length - 1) {
643
- value /= 1024;
644
- unit++;
645
- }
646
- return unit === 0 ? `${value} B` : `${value.toFixed(1)} ${units[unit]}`;
647
- }
648
787
  function cacheLine(m) {
649
788
  const why = m.partial ? 'left by a stopped clone' : m.problem;
650
789
  const note = why === null ? '' : ` (${why})`;
651
790
  // A URL, directory name or git message is outside text: no terminal controls.
652
- return (stripControls(`${sizeText(m.bytes).padStart(9)} ${m.url ?? '(no origin)'} ${m.dir}${note}`) +
653
- '\n');
791
+ return (stripControls(`${formatBytes(m.bytes).padStart(9)} ${m.url ?? '(no origin)'} ${m.dir}${note}`) + '\n');
654
792
  }
655
793
  function cacheList(ctx, dir, json) {
656
794
  const mirrors = listMirrors(dir);
@@ -666,7 +804,7 @@ function cacheList(ctx, dir, json) {
666
804
  ctx.io.stdout(cacheLine(m));
667
805
  const total = mirrors.reduce((sum, m) => sum + m.bytes, 0);
668
806
  const count = `${mirrors.length} clone${mirrors.length === 1 ? '' : 's'}`;
669
- ctx.io.stdout(`${count}, ${sizeText(total)}, in ${dir}\n`);
807
+ ctx.io.stdout(`${count}, ${formatBytes(total)}, in ${dir}\n`);
670
808
  return EXIT.ok;
671
809
  }
672
810
  /**
@@ -766,13 +904,24 @@ export function main(argv, ctx, deps = {}) {
766
904
  const c = { ...ctx, io };
767
905
  const [sub, ...rest] = argv;
768
906
  try {
907
+ if (sub === 'status')
908
+ return runStatus(rest, c, deps, status);
769
909
  if (sub === 'plan')
770
- return runPlan(rest, c, status);
910
+ return runPlan(rest, c, deps, status);
771
911
  if (sub === 'clean')
772
912
  return runClean(rest, c, deps, status);
773
913
  if (sub === 'cache')
774
914
  return runCache(rest, c);
775
- return runReport(argv, c, status);
915
+ if (sub === '-h' || sub === '--help') {
916
+ c.io.stdout(OVERVIEW);
917
+ return EXIT.ok;
918
+ }
919
+ // Nothing runs until a phase is named: the bare command explains them.
920
+ if (sub === undefined) {
921
+ c.io.stderr(OVERVIEW);
922
+ return EXIT.usage;
923
+ }
924
+ return usageError(c, NAME, `${JSON.stringify(sub)} is not a phase: name one of status, plan, clean or cache, then the targets`);
776
925
  }
777
926
  finally {
778
927
  status.clear();