@osdlc/repo-cleaner 0.20.5 → 0.24.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 (58) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +562 -167
  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/candidates.d.ts +42 -0
  10. package/dist/candidates.js +42 -0
  11. package/dist/clean.d.ts +66 -70
  12. package/dist/clean.js +386 -218
  13. package/dist/cli.d.ts +16 -10
  14. package/dist/cli.js +273 -102
  15. package/dist/discover.d.ts +28 -7
  16. package/dist/discover.js +185 -42
  17. package/dist/index.d.ts +12 -5
  18. package/dist/index.js +11 -4
  19. package/dist/landing.d.ts +10 -5
  20. package/dist/landing.js +15 -16
  21. package/dist/plan.d.ts +18 -11
  22. package/dist/plan.js +33 -13
  23. package/dist/processes.d.ts +19 -9
  24. package/dist/processes.js +51 -25
  25. package/dist/providers/github.d.ts +21 -3
  26. package/dist/providers/github.js +149 -27
  27. package/dist/providers/gitlab.js +37 -17
  28. package/dist/providers/index.d.ts +1 -1
  29. package/dist/providers/index.js +1 -1
  30. package/dist/providers/types.d.ts +15 -2
  31. package/dist/prs.d.ts +19 -10
  32. package/dist/prs.js +21 -13
  33. package/dist/receipt.d.ts +68 -3
  34. package/dist/receipt.js +30 -3
  35. package/dist/reference.d.ts +1 -1
  36. package/dist/reference.js +99 -51
  37. package/dist/remote-mirror.d.ts +2 -1
  38. package/dist/remote-mirror.js +3 -14
  39. package/dist/render.d.ts +17 -2
  40. package/dist/render.js +81 -14
  41. package/dist/resolve.d.ts +12 -1
  42. package/dist/resolve.js +15 -3
  43. package/dist/scope.d.ts +15 -0
  44. package/dist/scope.js +125 -0
  45. package/dist/size.d.ts +20 -0
  46. package/dist/size.js +34 -0
  47. package/dist/status-line.js +1 -0
  48. package/dist/step-board.js +6 -4
  49. package/dist/sweep.d.ts +50 -18
  50. package/dist/sweep.js +152 -127
  51. package/dist/types.d.ts +89 -10
  52. package/dist/types.js +50 -6
  53. package/dist/util.d.ts +2 -0
  54. package/dist/util.js +25 -0
  55. package/dist/version.generated.d.ts +1 -1
  56. package/dist/version.generated.js +1 -1
  57. package/dist/worktrees.js +87 -11
  58. 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,66 +13,90 @@
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 { DEFAULT_MAX_DEPTH } from "./resolve.js";
35
+ import { sweep as sweepTargets } from "./sweep.js";
36
36
  import { KINDS, RISKS, RepoCleanerError, sweepNotes, } from "./types.js";
37
37
  const EXIT_NOTHING_TO_SWEEP = 10;
38
38
  const EXIT_STEP_FAILED = 11;
39
39
  const NAME = 'repo-cleaner';
40
+ const NO_TERMINAL_FOR_I = '-i needs a terminal to ask on; name the rows with --pick and --spare instead';
40
41
  /** `--help` and its modifier: commander must not own `--help`, or it would never see `--extended`. */
41
42
  const HELP_FLAGS = {
42
43
  help: { kind: 'boolean', short: 'h', help: 'show this message' },
43
44
  extended: { kind: 'boolean', help: 'with --help: the full reference' },
44
45
  };
45
- /** The flags every command that sweeps takes. */
46
- const SWEEP_FLAGS = {
46
+ /** Which rows a phase looks at. With none of them, `--local`. */
47
+ const SCOPE_FLAGS = {
48
+ local: { kind: 'boolean', help: 'worktrees and local branches (the default)' },
47
49
  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
50
  kind: 'list',
54
- valueName: 'kinds',
55
- help: `only these kinds of row: ${KINDS.join(', ')} (default: worktree,branch; remote too with --remote)`,
51
+ valueName: 'name',
52
+ valueAfterEquals: true,
53
+ commaSeparated: false,
54
+ help: "branches on the default remote; --remote=<name> another, --remote='*' every remote; repeatable",
56
55
  },
56
+ all: { kind: 'boolean', help: '--local and --remote' },
57
+ worktrees: { kind: 'boolean', help: 'only worktrees, of the local rows' },
58
+ branches: { kind: 'boolean', help: 'only local branches, of the local rows' },
59
+ };
60
+ /** The flags every phase that looks takes. */
61
+ const SWEEP_FLAGS = {
62
+ ...SCOPE_FLAGS,
63
+ fetch: { kind: 'boolean', help: 'fetch the default remote before judging local rows' },
64
+ offline: { kind: 'boolean', help: 'no network: no fetch, judge from the refs on disk' },
57
65
  branch: {
58
66
  kind: 'string',
59
67
  valueName: 'name|HEAD',
60
- help: "only one branch's rows: its worktree, local branch, and remote branch with --remote",
68
+ help: "one branch's rows: its worktree, local branch, and remote branches",
61
69
  },
62
70
  against: {
63
71
  kind: 'string',
64
72
  valueName: 'remote',
65
- help: 'the remote whose default branch counts as merged into (default: origin)',
73
+ help: "judge every row against this remote's default branch (a fork against its parent)",
66
74
  },
67
75
  provider: {
68
76
  kind: 'enum',
69
77
  choices: PROVIDER_CHOICES,
70
78
  valueName: 'name',
71
- help: 'with --remote: where pull requests come from',
79
+ help: 'with remote rows: where pull requests come from',
80
+ },
81
+ maxDepth: {
82
+ kind: 'string',
83
+ valueName: 'n',
84
+ help: `how many levels below a directory target a checkout may sit (default ${DEFAULT_MAX_DEPTH})`,
72
85
  },
73
86
  progress: { kind: 'boolean', negatable: true, help: 'no progress line on stderr' },
74
87
  };
88
+ /**
89
+ * `--max-depth` as a number. Throws a `bad-input` for anything but a whole
90
+ * number, 1 or more, written in digits.
91
+ */
92
+ function maxDepthOf(raw) {
93
+ if (raw === undefined)
94
+ return undefined;
95
+ if (!/^[0-9]+$/.test(raw) || Number(raw) < 1) {
96
+ throw new RepoCleanerError('bad-input', `--max-depth takes a whole number, 1 or more; got ${JSON.stringify(raw)}`);
97
+ }
98
+ return Number(raw);
99
+ }
75
100
  /** A repeatable flag that takes a row (or `risk[=row]`) each time, never split on commas. */
76
101
  const rowList = (valueName, help) => ({
77
102
  kind: 'list',
@@ -88,16 +113,43 @@ const TARGETS = [
88
113
  },
89
114
  ];
90
115
  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.',
116
+ const PHASES = `phases:
117
+ ${NAME} status look: every row and its verdict, with the command that would delete it
118
+ ${NAME} plan save what status found, to clean later or hand over
119
+ ${NAME} clean check again, show the steps, ask, delete
120
+ ${NAME} cache list or remove the clones kept for remote URL targets`;
121
+ /** What the bare command prints: the phases, and that nothing ran. */
122
+ const OVERVIEW = `${NAME} finds worktrees and branches whose work has landed, and deletes them safely.
123
+
124
+ It works in phases. Nothing is deleted until clean, and only what is safe.
125
+
126
+ 1. status Look: each worktree and branch, with a verdict and the reason.
127
+ $ ${NAME} status this repository
128
+ $ ${NAME} status --all local and remote branches
129
+ 2. plan Optional: save what status found, to run later or hand on.
130
+ $ ${NAME} plan --all -o plan.json
131
+ 3. clean Delete what is safe: checks each row again, shows the steps, asks.
132
+ $ ${NAME} clean asks first
133
+ $ ${NAME} clean -y does not ask
134
+ $ ${NAME} clean --plan plan.json
135
+
136
+ Nothing ran. Name a phase; \`${NAME} <phase> --help\` shows its options.
137
+ \`${NAME} cache\` manages the clones of remote URL targets; \`${NAME} dev\` runs a
138
+ development checkout.
139
+ `;
140
+ const statusCli = () => defineCli({
141
+ name: `${NAME} status`,
142
+ summary: 'Sort every worktree and local branch (remote branches too, with --remote) into a ' +
143
+ 'verdict, with the evidence and the command that would delete each. Deletes nothing.',
96
144
  autoHelp: false,
97
145
  positionals: TARGETS,
98
146
  flags: {
99
147
  ...SWEEP_FLAGS,
100
- all: { kind: 'boolean', help: 'also show keep rows (with --format text)' },
148
+ sizes: {
149
+ kind: 'boolean',
150
+ help: "read each worktree's size on disk: rank rows largest first and total what can be freed; slower",
151
+ },
152
+ allRows: { kind: 'boolean', help: 'also show keep rows (with --format text)' },
101
153
  format: {
102
154
  kind: 'enum',
103
155
  choices: ['text', 'json', 'summary', 'commands'],
@@ -107,16 +159,8 @@ const reportCli = () => defineCli({
107
159
  },
108
160
  ...HELP_FLAGS,
109
161
  },
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,
162
+ shortEpilogue: `${PHASES}\n\n${MORE}`,
163
+ epilogue: REFERENCE.status,
120
164
  });
121
165
  const planCli = () => defineCli({
122
166
  name: `${NAME} plan`,
@@ -140,16 +184,33 @@ const planCli = () => defineCli({
140
184
  });
141
185
  const cleanCli = () => defineCli({
142
186
  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.',
187
+ summary: 'Delete what status (or a saved plan) found: check each row again, show the steps, ask, ' +
188
+ 'then delete, compare-and-swap, verifying each step. Every row judged delete runs, and ' +
189
+ 'each row picked.',
146
190
  autoHelp: false,
147
191
  positionals: TARGETS,
148
192
  flags: {
149
193
  ...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'),
194
+ pick: rowList('row', 'also run this row; a review row runs only when picked; repeatable'),
195
+ spare: rowList('row|glob', 'leave these rows alone; a remote branch spared by name that moved stops the run; repeatable'),
196
+ interactive: {
197
+ kind: 'boolean',
198
+ short: 'i',
199
+ help: 'choose the rows from a checklist; needs a terminal',
200
+ },
152
201
  allow: rowList('risk[=row]', 'accept a risk for every row, or for one row; repeatable'),
202
+ archive: {
203
+ kind: 'boolean',
204
+ help: 'push unlanded work to an archive branch on the remote before deleting it; ' +
205
+ 'then --allow discard-archived stands for abandon-unmerged and discard-changes',
206
+ },
207
+ archiveExclude: {
208
+ kind: 'list',
209
+ valueName: 'glob',
210
+ default: [],
211
+ commaSeparated: false,
212
+ help: 'with --archive, leave files matching this glob out of a worktree snapshot; repeatable',
213
+ },
153
214
  plan: {
154
215
  kind: 'string',
155
216
  valueName: 'file',
@@ -201,6 +262,7 @@ const cacheCli = () => defineCli({
201
262
  epilogue: REFERENCE.cache,
202
263
  });
203
264
  const terminalConfirm = (question) => (canPrompt() ? askYesNo(question) : null);
265
+ const terminalChecklist = (question, items) => canPrompt() ? askChecklist(question, items) : null;
204
266
  const PAUSE = new Int32Array(new SharedArrayBuffer(4));
205
267
  /**
206
268
  * All of stdin, synchronously. A pipe can be non-blocking and still empty
@@ -241,13 +303,23 @@ function refusal(ctx, name, err) {
241
303
  }
242
304
  return failure(ctx, name, err);
243
305
  }
244
- /** Parse, and answer `--help` (and `--help --extended`) itself. */
245
- function parseWith(cli, name, argv, ctx) {
306
+ /** Flags only `status` takes, each with what `plan` and `clean` say when given it. */
307
+ const STATUS_ONLY = {
308
+ '--sizes': `--sizes is a status flag: run \`${NAME} status --sizes\``,
309
+ };
310
+ /**
311
+ * Parse, and answer `--help` (and `--help --extended`) itself. An unknown
312
+ * option named in `elsewhere` is refused with its message there instead of
313
+ * the parser's.
314
+ */
315
+ function parseWith(cli, name, argv, ctx, elsewhere = {}) {
246
316
  const parsed = cli.parse(argv, ctx.io);
247
317
  if (parsed.status === 'help')
248
318
  return { status: 'done', code: EXIT.ok };
249
319
  if (parsed.status === 'error') {
250
- return { status: 'done', code: usageError(ctx, name, parsed.message) };
320
+ const flag = /^unknown option '(--[^'=]+)/.exec(parsed.message)?.[1];
321
+ const message = (flag === undefined ? undefined : elsewhere[flag]) ?? parsed.message;
322
+ return { status: 'done', code: usageError(ctx, name, message) };
251
323
  }
252
324
  const v = parsed.values;
253
325
  if (v.help) {
@@ -259,17 +331,47 @@ function parseWith(cli, name, argv, ctx) {
259
331
  }
260
332
  return parsed;
261
333
  }
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 !== '');
334
+ /**
335
+ * The kinds of row and the remotes the scope flags name. No scope flag is
336
+ * `--local`; `--worktrees` and `--branches` narrow the local rows; the flags
337
+ * add up. Throws a `conflict` for `--all` beside a named remote.
338
+ */
339
+ function scopeOf(v) {
340
+ // No scope flag: the library's default, which also lets a remote URL target
341
+ // sweep its remote branches.
342
+ if (!v.local && v.remote === undefined && !v.all && !v.worktrees && !v.branches) {
343
+ return { remotes: [] };
344
+ }
345
+ const remotes = [...(v.remote ?? [])];
346
+ if (v.all && remotes.some((r) => r !== '')) {
347
+ throw new RepoCleanerError('conflict', '--all is --local and the default remote; with other remotes, write them out: --local --remote=<name>');
348
+ }
349
+ if (v.all)
350
+ remotes.push('');
351
+ const narrowed = v.worktrees || v.branches;
352
+ const local = narrowed
353
+ ? KINDS.filter((k) => (k === 'worktree' && v.worktrees) || (k === 'branch' && v.branches))
354
+ : v.local || v.all || remotes.length === 0
355
+ ? ['worktree', 'branch']
356
+ : [];
357
+ return { only: remotes.length > 0 ? [...local, 'remote'] : local, remotes };
358
+ }
359
+ /**
360
+ * The sweep options as typed, for {@link sweptWith} and {@link sweepTargets}.
361
+ * Only `status` takes `--sizes`.
362
+ */
363
+ function sweepOptions(v, ctx, deps) {
265
364
  return {
365
+ ...deps.runners,
266
366
  cwd: ctx.cwd,
267
- remote: v.remote,
367
+ ...scopeOf(v),
368
+ fetch: v.fetch,
268
369
  offline: v.offline,
269
- ...(only === undefined ? {} : { only: only }),
370
+ sizes: v.sizes === true,
270
371
  ...(v.branch === undefined ? {} : { branch: v.branch }),
271
372
  ...(v.against === undefined ? {} : { against: v.against }),
272
373
  ...(v.provider === undefined ? {} : { provider: v.provider }),
374
+ ...(v.maxDepth === undefined ? {} : { maxDepth: maxDepthOf(v.maxDepth) }),
273
375
  cacheDir: defaultCacheDir(ctx.env),
274
376
  };
275
377
  }
@@ -284,21 +386,22 @@ function remoteNote(s, style) {
284
386
  return '';
285
387
  if (!s.repos.some((r) => r.repo?.remote != null))
286
388
  return '';
287
- return (style.muted('Local only: nothing fetched, no pull requests looked up, remote branches not checked; add --remote for all three.') + '\n');
389
+ const fetched = s.options.fetch ? '' : 'nothing fetched, ';
390
+ return (style.muted(`Local only: ${fetched}no pull requests looked up, remote branches not checked; --all adds the default remote's branches.`) + '\n');
288
391
  }
289
392
  /** 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`);
393
+ function doSweep(name, v, targets, ctx, deps, status) {
300
394
  let result;
301
395
  try {
396
+ const opts = {
397
+ ...sweepOptions(v, ctx, deps),
398
+ // Mid-walk, while the wait is happening: the totals come too late to
399
+ // explain why the tool appeared to hang.
400
+ onWarn: (message) => ctx.io.stderr(`${NAME}: ${message}\n`),
401
+ ...(v.progress ? { onProgress: (p) => status.update(describeSweep(p)) } : {}),
402
+ };
403
+ if (v.progress)
404
+ status.update(`${NAME}: finding repositories`);
302
405
  result = sweepTargets(targets, opts);
303
406
  }
304
407
  catch (err) {
@@ -333,16 +436,17 @@ function writeNotes(ctx, name, notes) {
333
436
  for (const { repo, note } of notes)
334
437
  ctx.io.stderr(renderError(`${repo}: ${note}`, name));
335
438
  }
336
- function runReport(argv, ctx, status) {
337
- const parsed = parseWith(reportCli(), NAME, argv, ctx);
439
+ function runStatus(argv, ctx, deps, status) {
440
+ const name = `${NAME} status`;
441
+ const parsed = parseWith(statusCli(), name, argv, ctx);
338
442
  if (parsed.status === 'done')
339
443
  return parsed.code;
340
444
  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`);
445
+ if (v.allRows && v.format !== 'text') {
446
+ return usageError(ctx, name, `--all-rows has no effect with --format ${v.format}: it shows keep rows in the text report`);
343
447
  }
344
448
  const style = styleFor(ctx, 'stdout');
345
- const swept = doSweep(NAME, v, parsed.positionals, ctx, status);
449
+ const swept = doSweep(name, v, parsed.positionals, ctx, deps, status);
346
450
  if (swept.kind === 'exit')
347
451
  return swept.code;
348
452
  const s = swept.sweep;
@@ -351,23 +455,23 @@ function runReport(argv, ctx, status) {
351
455
  else if (v.format === 'summary')
352
456
  ctx.io.stdout(renderSummary(s, style) + remoteNote(s, style));
353
457
  else if (v.format === 'commands') {
354
- reportNotes(ctx, NAME, s);
458
+ reportNotes(ctx, name, s);
355
459
  const commands = renderCommands(s);
356
460
  if (commands.length > 0)
357
461
  ctx.io.stdout(commands.join('\n') + '\n');
358
462
  }
359
463
  else {
360
- ctx.io.stdout(renderText(s, { all: v.all, style }) + remoteNote(s, style));
464
+ ctx.io.stdout(renderText(s, { all: v.allRows, style }) + remoteNote(s, style));
361
465
  }
362
466
  return swept.kind === 'nothing' ? EXIT_NOTHING_TO_SWEEP : EXIT.ok;
363
467
  }
364
- function runPlan(argv, ctx, status) {
468
+ function runPlan(argv, ctx, deps, status) {
365
469
  const name = `${NAME} plan`;
366
- const parsed = parseWith(planCli(), name, argv, ctx);
470
+ const parsed = parseWith(planCli(), name, argv, ctx, STATUS_ONLY);
367
471
  if (parsed.status === 'done')
368
472
  return parsed.code;
369
473
  const v = parsed.values;
370
- const swept = doSweep(name, v, parsed.positionals, ctx, status);
474
+ const swept = doSweep(name, v, parsed.positionals, ctx, deps, status);
371
475
  if (swept.kind === 'exit')
372
476
  return swept.code;
373
477
  // stdout carries only the plan, so the totals go to stderr either way.
@@ -399,31 +503,82 @@ const dropKey = (d) => JSON.stringify([d.repo, d.row]);
399
503
  /** The run's options that contradict each other, as a usage message, or null. */
400
504
  function cleanConflict(v, targets) {
401
505
  if (v.plan !== undefined) {
506
+ // Every sweep flag given, so a new one cannot be missed here. `progress`
507
+ // only draws.
508
+ const given = Object.keys(SWEEP_FLAGS).filter((k) => k !== 'progress' && v[k] !== undefined && v[k] !== false);
402
509
  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);
510
+ ...(targets.length > 0 ? ['targets'] : []),
511
+ ...given.map((k) => `--${k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`),
512
+ ];
411
513
  if (fixed.length > 0)
412
514
  return `--plan already fixed what is swept; drop ${fixed.join(', ')}`;
413
515
  }
516
+ if (v.interactive && v.pick.length > 0) {
517
+ return '-i chooses the rows from a checklist; drop --pick, or drop -i';
518
+ }
519
+ if (v.interactive && v.plan === '-') {
520
+ return '-i asks on the terminal, and --plan - reads the plan from stdin; save the plan to a file';
521
+ }
414
522
  if (v.plan === '-' && !v.yes && !v.dryRun) {
415
523
  return '--plan - reads the plan from stdin, so nothing can ask; pass --yes or --dry-run';
416
524
  }
525
+ if (!v.archive && v.archiveExclude.length > 0) {
526
+ return '--archive-exclude has no effect without --archive';
527
+ }
417
528
  if (v.yes && v.dryRun)
418
529
  return '--yes and --dry-run contradict: one deletes without asking, the other deletes nothing';
419
530
  if (v.receipt !== undefined && v.dryRun)
420
531
  return '--receipt has no effect with --dry-run: nothing runs to record';
421
532
  return null;
422
533
  }
534
+ /**
535
+ * `-i`: the plan's rows as a checklist, `delete` rows ticked, rows that can
536
+ * never run shown but not selectable, spared rows left out; then each ticked
537
+ * row's risks, asked for by name. The answer is an approval that selects
538
+ * exactly the ticked rows, or null when there is no one to ask.
539
+ */
540
+ function chooseRows(plan, sweep, approval, ctx, deps) {
541
+ const given = resolveApproval(plan, { spare: approval.spare, allow: approval.allow }, ctx.cwd);
542
+ const left = new Set([...given.spare, ...given.spareMatched].map(keyOf));
543
+ const why = new Map((sweep?.repos ?? []).flatMap((r) => r.repo === null
544
+ ? []
545
+ : r.rows.map((row) => [keyOf({ repo: r.repo.root, id: row.id }), row.why])));
546
+ const rows = plan.repos.flatMap((r) => r.rows
547
+ .map((row) => ({ at: { repo: r.root, id: row.id }, row }))
548
+ .filter(({ at }) => !left.has(keyOf(at))));
549
+ if (rows.length === 0)
550
+ return { spare: approval.spare, allow: approval.allow };
551
+ const several = plan.repos.length > 1;
552
+ const items = rows.map(({ at, row }) => {
553
+ const reason = why.get(keyOf(at));
554
+ const label = `${row.id} ${row.verdict}${reason === undefined ? '' : `: ${reason}`}${several ? ` (${at.repo})` : ''}`;
555
+ const runs = runnable(row);
556
+ return {
557
+ label,
558
+ checked: runs && row.verdict === 'delete',
559
+ ...(runs ? {} : { disabled: row.verdict }),
560
+ };
561
+ });
562
+ const ticked = (deps.checklist ?? terminalChecklist)('Clean which rows?', items);
563
+ if (ticked === null)
564
+ return null;
565
+ const allow = [...(approval.allow ?? [])];
566
+ const ask = deps.confirm ?? terminalConfirm;
567
+ for (const i of ticked) {
568
+ const { at, row } = rows[i];
569
+ for (const risk of row.risks) {
570
+ if (allowed(given.allow, at, risk))
571
+ continue;
572
+ if (ask(`${row.id} carries ${risk}: allow it?`) === true)
573
+ allow.push({ risk, row: at });
574
+ }
575
+ }
576
+ return { select: ticked.map((i) => rows[i].at), spare: approval.spare, allow };
577
+ }
423
578
  function loadPlan(name, v, targets, ctx, deps, status, now) {
424
579
  const receiptPath = v.receipt === undefined ? undefined : resolve(ctx.cwd, v.receipt);
425
580
  if (v.plan === undefined) {
426
- const swept = doSweep(name, v, targets, ctx, status);
581
+ const swept = doSweep(name, v, targets, ctx, deps, status);
427
582
  if (swept.kind === 'exit')
428
583
  return swept.code;
429
584
  if (swept.kind === 'nothing') {
@@ -458,7 +613,7 @@ function loadPlan(name, v, targets, ctx, deps, status, now) {
458
613
  }
459
614
  function runClean(argv, ctx, deps, status) {
460
615
  const name = `${NAME} clean`;
461
- const parsed = parseWith(cleanCli(), name, argv, ctx);
616
+ const parsed = parseWith(cleanCli(), name, argv, ctx, STATUS_ONLY);
462
617
  if (parsed.status === 'done')
463
618
  return parsed.code;
464
619
  const v = parsed.values;
@@ -473,11 +628,14 @@ function runClean(argv, ctx, deps, status) {
473
628
  const conflict = cleanConflict(v, targets);
474
629
  if (conflict !== null)
475
630
  return usageError(ctx, name, conflict);
631
+ if (v.interactive && deps.checklist === undefined && !canPrompt()) {
632
+ return usageError(ctx, name, NO_TERMINAL_FOR_I);
633
+ }
476
634
  // Refuse what can be refused before sweeping; a saved plan's own options
477
635
  // are checked when the approval is resolved against it.
478
636
  if (v.plan === undefined) {
479
637
  try {
480
- checkApproval(sweptWith(targets, sweepOptions(v, ctx)), approval);
638
+ checkApproval(sweptWith(targets, sweepOptions(v, ctx, deps)), approval);
481
639
  }
482
640
  catch (err) {
483
641
  return refusal(ctx, name, err);
@@ -489,12 +647,26 @@ function runClean(argv, ctx, deps, status) {
489
647
  return loaded;
490
648
  const { plan, source, receiptPath } = loaded;
491
649
  const ok = () => (loaded.unreadable ? EXIT.error : EXIT.ok);
650
+ if (v.interactive) {
651
+ try {
652
+ const chosen = chooseRows(plan, loaded.sweep, approval, ctx, deps);
653
+ if (chosen === null) {
654
+ return usageError(ctx, name, NO_TERMINAL_FOR_I);
655
+ }
656
+ approval = chosen;
657
+ }
658
+ catch (err) {
659
+ return refusal(ctx, name, err);
660
+ }
661
+ }
492
662
  // On a terminal the run is shown live: every step first, then each one
493
663
  // checked off as it finishes.
494
664
  const live = v.format === 'text' && ctx.terminal?.stdout === true;
495
665
  const style = styleFor(ctx, 'stdout');
496
666
  const shared = {
667
+ ...deps.runners,
497
668
  cwd: ctx.cwd,
669
+ ...(v.archive ? { archive: { exclude: v.archiveExclude } } : {}),
498
670
  ...(v.progress
499
671
  ? {
500
672
  onProgress: (p) => status.update(`re-checking ${describeSweep(p)}`),
@@ -634,23 +806,11 @@ function confirm(ctx, name, preview, count, json, deps) {
634
806
  }
635
807
  return null;
636
808
  }
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
809
  function cacheLine(m) {
649
810
  const why = m.partial ? 'left by a stopped clone' : m.problem;
650
811
  const note = why === null ? '' : ` (${why})`;
651
812
  // 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');
813
+ return (stripControls(`${formatBytes(m.bytes).padStart(9)} ${m.url ?? '(no origin)'} ${m.dir}${note}`) + '\n');
654
814
  }
655
815
  function cacheList(ctx, dir, json) {
656
816
  const mirrors = listMirrors(dir);
@@ -666,7 +826,7 @@ function cacheList(ctx, dir, json) {
666
826
  ctx.io.stdout(cacheLine(m));
667
827
  const total = mirrors.reduce((sum, m) => sum + m.bytes, 0);
668
828
  const count = `${mirrors.length} clone${mirrors.length === 1 ? '' : 's'}`;
669
- ctx.io.stdout(`${count}, ${sizeText(total)}, in ${dir}\n`);
829
+ ctx.io.stdout(`${count}, ${formatBytes(total)}, in ${dir}\n`);
670
830
  return EXIT.ok;
671
831
  }
672
832
  /**
@@ -766,13 +926,24 @@ export function main(argv, ctx, deps = {}) {
766
926
  const c = { ...ctx, io };
767
927
  const [sub, ...rest] = argv;
768
928
  try {
929
+ if (sub === 'status')
930
+ return runStatus(rest, c, deps, status);
769
931
  if (sub === 'plan')
770
- return runPlan(rest, c, status);
932
+ return runPlan(rest, c, deps, status);
771
933
  if (sub === 'clean')
772
934
  return runClean(rest, c, deps, status);
773
935
  if (sub === 'cache')
774
936
  return runCache(rest, c);
775
- return runReport(argv, c, status);
937
+ if (sub === '-h' || sub === '--help') {
938
+ c.io.stdout(OVERVIEW);
939
+ return EXIT.ok;
940
+ }
941
+ // Nothing runs until a phase is named: the bare command explains them.
942
+ if (sub === undefined) {
943
+ c.io.stderr(OVERVIEW);
944
+ return EXIT.usage;
945
+ }
946
+ return usageError(c, NAME, `${JSON.stringify(sub)} is not a phase: name one of status, plan, clean or cache, then the targets`);
776
947
  }
777
948
  finally {
778
949
  status.clear();