@theholocron/cli 5.0.0-alpha.261 → 5.0.0-alpha.262

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -111,7 +111,7 @@ Every command is tagged with how much of a repo it needs:
111
111
  | ------------ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
112
112
  | `global` | the CLI binary alone | `version`, `clone`, `new repo` / `plugin`, `repo upgrade …`, `auth set` / `check`, `package …`, `run lint commit-msg`, `skills …` |
113
113
  | `repo-aware` | `./holocron.config`, walking up from cwd, no plugins | `run`, `run ci`, `config show`, `repo sync readme`, `deploy on-release` |
114
- | `workspace` | the `@theholocron/holocron-plugin-*` packages resolvable | `doctor`, `repo setup`, `repo sync`, `secrets …`, `deploy`, `sync github` |
114
+ | `workspace` | the `@theholocron/holocron-plugin-*` packages resolvable | `doctor`, `repo setup`, `repo sync`, `repo cleanup branches`, `secrets …`, `deploy`, `sync github` |
115
115
 
116
116
  A `workspace` command run from a bare global install (no plugins next to the
117
117
  CLI) fails with one actionable line — install the plugins as devDependencies or
@@ -589,6 +589,16 @@ Provider credentials for Discord: `discord.holonet` is the **bot token** (Bot
589
589
 
590
590
  See the [command pages](https://theholocron.dev/holocron/commands/notifications-setup/) for each command's options.
591
591
 
592
+ ## Cleaning up
593
+
594
+ - **`holocron repo cleanup branches [--local | --remote]`** — lists the branches whose pull request is merged,
595
+ grouped, each saying whether it lives locally, on the remote or both; then asks, and offers a checklist with the
596
+ proven-merged ones ticked. Proven merged means an ancestor of `origin/alpha` or `origin/main`, or the head (or an
597
+ ancestor, or one of the commits) of a merged pull request. Branches with more commits than their merged PR, with
598
+ an open PR, checked out (here or in a worktree), or never merged are listed unticked. `--dry-run` only lists;
599
+ `--yes` deletes every proven-merged branch without asking. Pull requests and remote branches come from the
600
+ `source` provider (`Source.listPullRequests`, `listPullRequestCommits`, `listBranches`, `deleteBranch`).
601
+
592
602
  ## Upgrading
593
603
 
594
604
  - **`holocron repo upgrade node <to>`** — patches every Node.js version pin
@@ -719,7 +729,7 @@ same paths in `holocron.config`'s `eslint.browserPackages`:
719
729
  ```ts
720
730
  export default defineConfig({
721
731
  eslint: {
722
- browserPackages: ["packages/github-client/src/app-auth"],
732
+ browserPackages: ["clients/github-client/src/app-auth"],
723
733
  },
724
734
  });
725
735
  ```
package/dist/cli.mjs CHANGED
@@ -12,7 +12,7 @@ import chalk from "chalk";
12
12
  import search from "@inquirer/search";
13
13
  import { execFileSync, spawn, spawnSync } from "node:child_process";
14
14
  import ora from "ora";
15
- import { checkbox, confirm, input, password, select } from "@inquirer/prompts";
15
+ import { Separator, checkbox, confirm, input, password, select } from "@inquirer/prompts";
16
16
  import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
17
17
  import { homedir, hostname, tmpdir, userInfo } from "node:os";
18
18
  import { PostHogSink } from "@theholocron/observability/analytics";
@@ -221,6 +221,7 @@ const COMMAND_CONTEXTS = {
221
221
  "monitoring resolve-checks": "workspace",
222
222
  "monitoring run-resolved": "global",
223
223
  "repo sync": "workspace",
224
+ "repo cleanup branches": "workspace",
224
225
  "sync github": "workspace"
225
226
  };
226
227
  /**
@@ -1683,6 +1684,26 @@ const COMMAND_REGISTRY = [
1683
1684
  positionals: [],
1684
1685
  supportsDryRun: true
1685
1686
  },
1687
+ {
1688
+ name: "repo cleanup branches",
1689
+ description: "List the branches whose pull request is merged and delete the ones you pick",
1690
+ positionals: [],
1691
+ options: [{
1692
+ key: "local",
1693
+ flag: "--local",
1694
+ type: "confirm",
1695
+ default: false,
1696
+ message: "Only the branches in this checkout?"
1697
+ }, {
1698
+ key: "remote",
1699
+ flag: "--remote",
1700
+ type: "confirm",
1701
+ default: false,
1702
+ message: "Only the branches on the remote?"
1703
+ }],
1704
+ skipOptions: ["yes", "repo"],
1705
+ supportsDryRun: false
1706
+ },
1686
1707
  {
1687
1708
  name: "run ci",
1688
1709
  description: "Run the merge-gating checks locally, in CI order — 'will CI pass?'",
@@ -13136,6 +13157,361 @@ const setupCommand = {
13136
13157
  })).summary.fail > 0) process.exitCode = 1;
13137
13158
  }
13138
13159
  };
13160
+ // src/commands/repo-cleanup-branches/classify-branches.ts
13161
+ /** The merged PRs that had this branch as their head, newest first (the order the provider lists them). */
13162
+ function mergedFor(name, closed) {
13163
+ return closed.filter((pr) => pr.merged && pr.branch === name);
13164
+ }
13165
+ /**
13166
+ * Whether a merged PR accounts for a branch's tip: it is the PR's head, an ancestor of it, or (when the head
13167
+ * commit is not in the checkout) one of the PR's own commits. The provider is asked for the commits last, and
13168
+ * only for a branch the cheaper checks did not settle.
13169
+ */
13170
+ async function accounts(pr, tip, input) {
13171
+ if (pr.headSha === void 0) return (await input.pullRequestCommits(pr.number)).includes(tip);
13172
+ if (tip === pr.headSha || input.git.isAncestor(tip, pr.headSha)) return true;
13173
+ return (await input.pullRequestCommits(pr.number)).includes(tip);
13174
+ }
13175
+ async function classifyOne(ref, input) {
13176
+ if (input.git.isMergedIntoBase(ref.sha)) return {
13177
+ ref,
13178
+ group: "merged"
13179
+ };
13180
+ const merged = mergedFor(ref.name, input.closedPullRequests);
13181
+ for (const pr of merged) if (await accounts(pr, ref.sha, input)) return {
13182
+ ref,
13183
+ group: "squash-merged",
13184
+ pr: pr.number
13185
+ };
13186
+ const newest = merged[0];
13187
+ if (newest) return {
13188
+ ref,
13189
+ group: "has-extra",
13190
+ pr: newest.number
13191
+ };
13192
+ return {
13193
+ ref,
13194
+ group: input.closedPullRequests.some((pr) => pr.branch === ref.name) ? "closed-unmerged" : "no-pr"
13195
+ };
13196
+ }
13197
+ /**
13198
+ * Sorts branches, local and remote, into what is proven merged and what is not. A branch is skipped outright
13199
+ * when it is excluded (a base branch, or locally the checked-out one or one a worktree has out) or has an open
13200
+ * PR; the rest are classified by {@link BranchGroup}. Nothing here deletes.
13201
+ */
13202
+ async function classifyBranches(input) {
13203
+ const open = new Set(input.openPullRequests.map((pr) => pr.branch));
13204
+ const classification = {
13205
+ classified: [],
13206
+ skipped: []
13207
+ };
13208
+ for (const ref of input.branches) {
13209
+ const excluded = input.excluded(ref);
13210
+ if (excluded) classification.skipped.push({
13211
+ ref,
13212
+ reason: excluded
13213
+ });
13214
+ else if (open.has(ref.name)) classification.skipped.push({
13215
+ ref,
13216
+ reason: "open-pr"
13217
+ });
13218
+ else classification.classified.push(await classifyOne(ref, input));
13219
+ }
13220
+ return classification;
13221
+ }
13222
+ // src/commands/repo-cleanup-branches/group-branches.ts
13223
+ /**
13224
+ * One row per branch name and group: a branch on both sides that classifies the same on each is one entry
13225
+ * listing both places. A name whose two refs classify differently (the remote moved on) is two entries.
13226
+ * Newest first by local commit date; a remote-only branch has no date and follows, by name.
13227
+ */
13228
+ function groupBranches(classified) {
13229
+ const entries = /* @__PURE__ */ new Map();
13230
+ for (const { ref, group, pr } of classified) {
13231
+ const key = `${group}:${ref.name}`;
13232
+ const entry = entries.get(key) ?? {
13233
+ name: ref.name,
13234
+ group,
13235
+ ...pr === void 0 ? {} : { pr },
13236
+ locations: []
13237
+ };
13238
+ entry.locations.push(ref.where);
13239
+ if (ref.date !== void 0 && (entry.date === void 0 || ref.date > entry.date)) entry.date = ref.date;
13240
+ entries.set(key, entry);
13241
+ }
13242
+ return [...entries.values()].sort((a, b) => (b.date ?? "").localeCompare(a.date ?? "") || a.name.localeCompare(b.name));
13243
+ }
13244
+ // src/commands/repo-cleanup-branches/constants.ts
13245
+ /** The long-lived branches: never deleted, and what a branch must be an ancestor of (as `origin/<name>`) to count as merged. */
13246
+ const BASE_BRANCHES = ["alpha", "main"];
13247
+ // src/commands/repo-cleanup-branches/local-git.ts
13248
+ /** `git` run in `cwd`, no shell: its trimmed stdout and stderr, and whether it exited 0. */
13249
+ function git(cwd, args) {
13250
+ const r = spawnSync("git", args, {
13251
+ cwd,
13252
+ encoding: "utf8"
13253
+ });
13254
+ return {
13255
+ out: (r.stdout ?? "").trim(),
13256
+ ok: r.status === 0,
13257
+ err: (r.stderr ?? "").trim()
13258
+ };
13259
+ }
13260
+ /** {@link LocalGit} over the checkout at `cwd`. */
13261
+ function createLocalGit(cwd) {
13262
+ return {
13263
+ branches() {
13264
+ const { out } = git(cwd, [
13265
+ "for-each-ref",
13266
+ "--format=%(refname:short)%09%(objectname)%09%(committerdate:iso-strict)",
13267
+ "refs/heads"
13268
+ ]);
13269
+ return out.split("\n").filter(Boolean).map((line) => {
13270
+ const [name = "", sha = "", date = ""] = line.split(" ");
13271
+ return {
13272
+ name,
13273
+ sha,
13274
+ date,
13275
+ where: "local"
13276
+ };
13277
+ });
13278
+ },
13279
+ currentBranch() {
13280
+ return git(cwd, [
13281
+ "symbolic-ref",
13282
+ "--quiet",
13283
+ "--short",
13284
+ "HEAD"
13285
+ ]).out || void 0;
13286
+ },
13287
+ worktreeBranches() {
13288
+ return git(cwd, [
13289
+ "worktree",
13290
+ "list",
13291
+ "--porcelain"
13292
+ ]).out.split("\n").filter((line) => line.startsWith("branch refs/heads/")).map((line) => line.slice(18));
13293
+ },
13294
+ isMergedIntoBase(sha) {
13295
+ return BASE_BRANCHES.some((base) => git(cwd, [
13296
+ "merge-base",
13297
+ "--is-ancestor",
13298
+ sha,
13299
+ `origin/${base}`
13300
+ ]).ok);
13301
+ },
13302
+ isAncestor(sha, of) {
13303
+ return git(cwd, [
13304
+ "merge-base",
13305
+ "--is-ancestor",
13306
+ sha,
13307
+ of
13308
+ ]).ok;
13309
+ },
13310
+ deleteBranch(name) {
13311
+ const r = git(cwd, [
13312
+ "branch",
13313
+ "-D",
13314
+ "--",
13315
+ name
13316
+ ]);
13317
+ if (!r.ok) throw new Error(r.err || `git branch -D ${name} failed`);
13318
+ }
13319
+ };
13320
+ }
13321
+ // src/commands/repo-cleanup-branches/run-cleanup-branches.ts
13322
+ const GROUPS = [
13323
+ "merged",
13324
+ "squash-merged",
13325
+ "has-extra",
13326
+ "closed-unmerged",
13327
+ "no-pr"
13328
+ ];
13329
+ /** The two groups that are proven merged: ticked in the checklist, and what `--yes` deletes. */
13330
+ const SAFE = ["merged", "squash-merged"];
13331
+ const GROUP_LABEL = {
13332
+ merged: "merged (an ancestor of a base branch)",
13333
+ "squash-merged": "squash-merged (its PR merged and the branch holds nothing beyond it)",
13334
+ "has-extra": "merged PR, but the branch has more commits",
13335
+ "closed-unmerged": "PR closed without merging",
13336
+ "no-pr": "no PR and not merged"
13337
+ };
13338
+ const SKIP_LABEL = {
13339
+ base: "base branch",
13340
+ current: "checked out",
13341
+ worktree: "checked out in a worktree",
13342
+ "open-pr": "has an open PR"
13343
+ };
13344
+ /** A row's label: the name, where it lives, when it was last committed to (local only) and its PR. */
13345
+ function rowLabel(entry) {
13346
+ const detail = [entry.date?.slice(0, 10), entry.pr === void 0 ? void 0 : `PR #${entry.pr}`].filter(Boolean);
13347
+ return `${entry.name} [${entry.locations.join(", ")}]${detail.length > 0 ? ` ${style.dim(detail.join(" "))}` : ""}`;
13348
+ }
13349
+ /**
13350
+ * Classifies the branches against the provider's pull requests, shows them grouped, and deletes the ones
13351
+ * chosen. With no flag it covers local and remote branches, each row saying where the branch lives.
13352
+ *
13353
+ * - `--dry-run` stops after the list.
13354
+ * - `--yes` deletes every proven-merged branch without asking.
13355
+ * - Otherwise it asks, then offers a checklist of every branch with the proven-merged ones ticked.
13356
+ */
13357
+ async function runCleanupBranches(input) {
13358
+ const print = input.print ?? ((line) => console.log(line));
13359
+ const logger = input.logger ?? getLogger();
13360
+ const scope = input.scope ?? "both";
13361
+ const git = input.git ?? createLocalGit(input.context.repoRoot);
13362
+ // c8 ignore next -- real PluginLoader construction is integration-level; unit tests always supply loader
13363
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
13364
+ await loader.load();
13365
+ assertPluginsResolvable(loader, "repo cleanup branches");
13366
+ if (!loader.has("source")) throw new Error("source capability is not configured — add a source provider to holocron.config.json");
13367
+ const source = loader.get("source");
13368
+ const { listPullRequests, listPullRequestCommits, listBranches, deleteBranch } = source;
13369
+ if (!listPullRequests || !listPullRequestCommits) throw new Error(`${source.providerName} source provider does not support listing pull requests`);
13370
+ if (scope !== "local" && (!listBranches || !deleteBranch)) throw new Error(`${source.providerName} source provider does not support listing and deleting remote branches`);
13371
+ const worktrees = new Set(scope === "remote" ? [] : git.worktreeBranches());
13372
+ const current = scope === "remote" ? void 0 : git.currentBranch();
13373
+ const refs = [];
13374
+ if (scope !== "remote") refs.push(...git.branches());
13375
+ if (scope !== "local") {
13376
+ const remote = await listBranches.call(source, input.repo);
13377
+ refs.push(...remote.map((b) => ({
13378
+ name: b.name,
13379
+ sha: b.sha,
13380
+ where: "remote"
13381
+ })));
13382
+ }
13383
+ const [openPullRequests, closedPullRequests] = await Promise.all([listPullRequests.call(source, "open", input.repo), listPullRequests.call(source, "closed", input.repo)]);
13384
+ const classification = await classifyBranches({
13385
+ branches: refs,
13386
+ git,
13387
+ excluded: (ref) => {
13388
+ if (BASE_BRANCHES.includes(ref.name)) return "base";
13389
+ if (ref.where === "remote") return void 0;
13390
+ if (ref.name === current) return "current";
13391
+ return worktrees.has(ref.name) ? "worktree" : void 0;
13392
+ },
13393
+ openPullRequests,
13394
+ closedPullRequests,
13395
+ pullRequestCommits: (number) => listPullRequestCommits.call(source, number, input.repo)
13396
+ });
13397
+ const entries = groupBranches(classification.classified);
13398
+ const report = {
13399
+ classification,
13400
+ deleted: [],
13401
+ failed: [],
13402
+ status: "ok"
13403
+ };
13404
+ print("");
13405
+ for (const group of GROUPS) {
13406
+ const rows = entries.filter((e) => e.group === group);
13407
+ const line = `${rows.length} ${GROUP_LABEL[group]}`;
13408
+ print(SAFE.includes(group) ? style.success(line) : style.warn(line));
13409
+ for (const row of rows) print(` ${rowLabel(row)}`);
13410
+ }
13411
+ if (classification.skipped.length > 0) {
13412
+ print(style.dim(`${classification.skipped.length} skipped`));
13413
+ for (const { ref, reason } of classification.skipped) print(style.dim(` ${ref.name} [${ref.where}] ${SKIP_LABEL[reason]}`));
13414
+ }
13415
+ print("");
13416
+ const safe = entries.filter((e) => SAFE.includes(e.group));
13417
+ if (input.context.dryRun === true) {
13418
+ print(style.dim(`Dry run: ${safe.length} branches are proven merged. Nothing was deleted.`));
13419
+ logger.info({
13420
+ proven: safe.length,
13421
+ deleted: 0
13422
+ }, "repo cleanup branches: dry run");
13423
+ return report;
13424
+ }
13425
+ if (entries.length === 0) return report;
13426
+ let chosen = safe;
13427
+ if (input.yes !== true) {
13428
+ if (!process.stdin.isTTY) throw new NonInteractiveError("`repo cleanup branches` asks which branches to delete — run it in a terminal, or pass --yes to delete the proven-merged ones, or --dry-run to only list them");
13429
+ if (!await confirm({
13430
+ message: "Choose branches to delete?",
13431
+ default: true
13432
+ })) return report;
13433
+ chosen = (await checkbox({
13434
+ message: "Delete which branches? (the proven-merged ones are ticked)",
13435
+ pageSize: 20,
13436
+ choices: GROUPS.flatMap((group) => {
13437
+ const rows = entries.filter((e) => e.group === group);
13438
+ if (rows.length === 0) return [];
13439
+ return [new Separator(`── ${GROUP_LABEL[group]} (${rows.length})`), ...rows.map((row) => ({
13440
+ name: rowLabel(row),
13441
+ value: entries.indexOf(row),
13442
+ checked: SAFE.includes(group)
13443
+ }))];
13444
+ })
13445
+ })).map((index) => entries[index]);
13446
+ }
13447
+ for (const entry of chosen) for (const where of entry.locations) try {
13448
+ if (where === "local") git.deleteBranch(entry.name);
13449
+ else await deleteBranch.call(source, entry.name, input.repo);
13450
+ report.deleted.push({
13451
+ name: entry.name,
13452
+ where
13453
+ });
13454
+ } catch (err) {
13455
+ report.failed.push({
13456
+ name: entry.name,
13457
+ where,
13458
+ message: errorMessage(err)
13459
+ });
13460
+ }
13461
+ for (const { name, where, message } of report.failed) print(style.fail(`${name} [${where}]: ${message}`));
13462
+ print(`Deleted ${report.deleted.length} of ${report.deleted.length + report.failed.length} branches.`);
13463
+ if (report.failed.length > 0) report.status = "fail";
13464
+ logger.info({
13465
+ deleted: report.deleted.length,
13466
+ failed: report.failed.length
13467
+ }, "repo cleanup branches: done");
13468
+ return report;
13469
+ }
13470
+ // src/commands/repo-cleanup-branches/repo-cleanup-branches.args.ts
13471
+ const repoCleanupBranchesArgs = (y) => y.option("local", {
13472
+ type: "boolean",
13473
+ describe: "Only the branches in this checkout (with neither --local nor --remote: both)"
13474
+ }).option("remote", {
13475
+ type: "boolean",
13476
+ describe: "Only the branches on the remote (with neither --local nor --remote: both)"
13477
+ }).option("yes", {
13478
+ type: "boolean",
13479
+ describe: "Delete every branch proven merged without asking. Without it a checklist asks."
13480
+ }).option("repo", {
13481
+ type: "string",
13482
+ describe: "Repo coords (\"owner/name\") to look branches and pull requests up in. Defaults to plugin-specific resolution."
13483
+ });
13484
+ // src/commands/repo-cleanup-branches/repo-cleanup-branches.command.ts
13485
+ const repoCleanupBranchesCommand = {
13486
+ command: "branches",
13487
+ describe: "List the branches whose pull request is merged and delete the ones you pick (local, remote or both)",
13488
+ builder: repoCleanupBranchesArgs,
13489
+ handler: async (argv) => {
13490
+ const tokens = tokenContext(argv.token);
13491
+ if (!tokens) return;
13492
+ const loaded = await loadConfig(argv.cwd);
13493
+ applyResolvedConfig(argv, loaded.resolved);
13494
+ if ((await runCleanupBranches({
13495
+ loaded,
13496
+ context: {
13497
+ repoRoot: argv.cwd,
13498
+ dryRun: argv.dryRun,
13499
+ ...tokens,
13500
+ org: resolveOrg(argv, loaded.resolved)
13501
+ },
13502
+ scope: argv.local && !argv.remote ? "local" : argv.remote && !argv.local ? "remote" : "both",
13503
+ ...argv.yes ? { yes: true } : {},
13504
+ ...argv.repo ? { repo: argv.repo } : {}
13505
+ })).status === "fail") process.exitCode = 1;
13506
+ }
13507
+ };
13508
+ // src/commands/repo/repo-cleanup.command.ts
13509
+ const repoCleanupCommand = {
13510
+ command: "cleanup",
13511
+ describe: "Clean up what a repo accumulates (merged branches)",
13512
+ builder: (y) => y.command(repoCleanupBranchesCommand).command(groupMenu("repo cleanup")),
13513
+ handler: () => {}
13514
+ };
13139
13515
  // src/commands/sync-readme/generate-readme.ts
13140
13516
  const SCRIPT_ORDER = [
13141
13517
  "build",
@@ -14650,8 +15026,8 @@ const repoUpgradeCommand = {
14650
15026
  // src/commands/repo/repo.command.ts
14651
15027
  const repoCommand = {
14652
15028
  command: "repo",
14653
- describe: "Set up, sync and upgrade the current repo",
14654
- builder: (y) => y.command(setupCommand).command(repoSyncCommand).command(repoUpgradeCommand).command(groupMenu("repo")),
15029
+ describe: "Set up, sync, upgrade and clean up the current repo",
15030
+ builder: (y) => y.command(setupCommand).command(repoSyncCommand).command(repoUpgradeCommand).command(repoCleanupCommand).command(groupMenu("repo")),
14655
15031
  handler: () => {}
14656
15032
  };
14657
15033
  // src/commands/run/run.args.ts