@theholocron/cli 5.4.0 → 5.5.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/README.md CHANGED
@@ -866,6 +866,17 @@ See the [command pages](https://theholocron.dev/holocron/commands/setup-notifica
866
866
  `readThread` (Discord); the release workflow's `announce` job runs it. See the
867
867
  [command page](../../docs/src/content/docs/commands/sync-releases.mdx).
868
868
 
869
+ ## Publishing templates
870
+
871
+ - **`holocron sync templates [--dry-run] [--yes]`** — publishes each `templates/<type>/` folder to
872
+ `<org>/<type>-template` (spec `tech-template-repos`, #2926): compares the folder with the repo's default branch,
873
+ writes only the difference through the `source` provider (files made, replaced, and removed when the folder no longer
874
+ has them), then tags the repo `templates-v<version>` with the version in `templates/package.json`. A rerun writes
875
+ nothing; a tag already at the same content is a success and one at other content is a failing row. It never creates
876
+ or deletes a repository (a missing one fails its row), and one failing template does not stop the others. Needs a
877
+ `source` provider with the optional `listFiles`, `deleteFile` and `ensureTag` beside `readFile` and `writeFile`
878
+ (GitHub). See the [command page](../../docs/src/content/docs/commands/sync-templates.mdx).
879
+
869
880
  ## Syncing issues
870
881
 
871
882
  - **`holocron sync issues --from <a> --to <b> [--since <time>] [--yes]`** — one direction of an issue sync between two
package/dist/cli.mjs CHANGED
@@ -148,6 +148,7 @@ const COMMAND_CONTEXTS = {
148
148
  "sync incidents": "workspace",
149
149
  "sync prs": "workspace",
150
150
  "sync releases": "workspace",
151
+ "sync templates": "workspace",
151
152
  "sync ideas": "workspace",
152
153
  "sync tooling": "workspace",
153
154
  "sync requests": "workspace",
@@ -2303,6 +2304,15 @@ const syncRequestsEntry = {
2303
2304
  ],
2304
2305
  supportsDryRun: true
2305
2306
  };
2307
+ // src/commands/sync-templates/sync-templates.entry.ts
2308
+ const syncTemplatesEntry = {
2309
+ name: "sync templates",
2310
+ description: "Publish each templates/<type>/ folder to its template repo and tag it with the templates version",
2311
+ positionals: [],
2312
+ options: [],
2313
+ skipOptions: ["yes"],
2314
+ supportsDryRun: true
2315
+ };
2306
2316
  // src/commands/sync-tooling/sync-tooling.entry.ts
2307
2317
  const syncToolingEntry = {
2308
2318
  name: "sync tooling",
@@ -2525,6 +2535,7 @@ const registry = createCommandRegistry([
2525
2535
  syncIncidentsEntry,
2526
2536
  syncPrsEntry,
2527
2537
  syncReleasesEntry,
2538
+ syncTemplatesEntry,
2528
2539
  ideasSyncEntry,
2529
2540
  syncToolingEntry,
2530
2541
  syncRequestsEntry,
@@ -34647,6 +34658,7 @@ async function runNew(input) {
34647
34658
  const readFn = input.readFile ?? defaultReadFile;
34648
34659
  const writeFn = input.writeFile ?? defaultWriteFile;
34649
34660
  const walkFn = input.walkFiles ?? defaultWalkFiles;
34661
+ const self = input.selfCommand ?? [process.execPath, process.argv[1]];
34650
34662
  preflight();
34651
34663
  const templateRepo = `${org}/${input.type}-template`;
34652
34664
  const newRepo = `${org}/${input.name}`;
@@ -34664,6 +34676,7 @@ async function runNew(input) {
34664
34676
  if (input.homepage) print(` Would replace <homepage> → "${input.homepage}"`);
34665
34677
  if (input.runtimeEnvironment) print(` Would replace <runtime_environment> → "${input.runtimeEnvironment}"`);
34666
34678
  print(` Would generate holocron.config.ts`);
34679
+ if (!input.noVerify) print(` Would run holocron sync in ${repoDir}`);
34667
34680
  logger.info({
34668
34681
  repo: newRepo,
34669
34682
  status: "dry-run"
@@ -34791,25 +34804,45 @@ async function runNew(input) {
34791
34804
  message: "pnpm install failed; inspect output above"
34792
34805
  };
34793
34806
  }
34807
+ const adminToken = input.token ?? keychainLookup("github.admin");
34808
+ const tokenEnv = {};
34809
+ if (!env$4.get("HOLOCRON_ORG_TOKEN")) {
34810
+ const orgToken = keychainLookup("github.org");
34811
+ if (orgToken) tokenEnv["HOLOCRON_ORG_TOKEN"] = orgToken;
34812
+ }
34813
+ if (!env$4.get("HOLOCRON_DEPLOY_TOKEN")) {
34814
+ const deployToken = keychainLookup("github.deploy");
34815
+ if (deployToken) tokenEnv["HOLOCRON_DEPLOY_TOKEN"] = deployToken;
34816
+ }
34817
+ const manualSync = `cd ${repoDir} && holocron sync`;
34818
+ print("");
34819
+ if (!adminToken) print(` ✗ holocron sync skipped — no GitHub admin token found. Run it by hand: ${manualSync}`);
34820
+ else {
34821
+ print(" Running holocron sync…");
34822
+ try {
34823
+ execFn(self[0], [
34824
+ ...self.slice(1),
34825
+ "sync",
34826
+ "--token",
34827
+ adminToken
34828
+ ], {
34829
+ cwd: repoDir,
34830
+ stdio: "inherit",
34831
+ env: tokenEnv
34832
+ });
34833
+ } catch (err) {
34834
+ print(` ✗ holocron sync failed (${errorMessage(err)}) — run it by hand: ${manualSync}`);
34835
+ }
34836
+ }
34794
34837
  print("");
34795
34838
  print(" Running holocron setup…");
34796
34839
  try {
34797
34840
  const setupArgs = ["setup"];
34798
- const setupEnv = {};
34799
- const adminToken = input.token ?? keychainLookup("github.admin");
34800
34841
  if (adminToken) setupArgs.push("--token", adminToken);
34801
- if (!env$4.get("HOLOCRON_ORG_TOKEN")) {
34802
- const orgToken = keychainLookup("github.org");
34803
- if (orgToken) setupEnv["HOLOCRON_ORG_TOKEN"] = orgToken;
34804
- }
34805
- if (!env$4.get("HOLOCRON_DEPLOY_TOKEN")) {
34806
- const deployToken = keychainLookup("github.deploy");
34807
- if (deployToken) setupEnv["HOLOCRON_DEPLOY_TOKEN"] = deployToken;
34808
- }
34809
34842
  execFn("holocron", setupArgs, {
34810
34843
  cwd: repoDir,
34811
34844
  stdio: "inherit",
34812
- env: setupEnv
34845
+ env: tokenEnv
34813
34846
  });
34814
34847
  } catch {
34815
34848
  print(" ✗ holocron setup failed — run it manually after checking your config");
@@ -34822,8 +34855,9 @@ async function runNew(input) {
34822
34855
  print(` 1. cd ${repoDir}`);
34823
34856
  if (input.noVerify) {
34824
34857
  print(` 2. pnpm install`);
34825
- print(` 3. holocron setup # wire up secrets, teams, labels, etc.`);
34826
- print(` 4. git push -u origin HEAD`);
34858
+ print(` 3. holocron sync # thin callers, org AGENTS.md block, generated files`);
34859
+ print(` 4. holocron setup # wire up secrets, teams, labels, etc.`);
34860
+ print(` 5. git push -u origin HEAD`);
34827
34861
  } else print(` 2. git push -u origin HEAD`);
34828
34862
  logger.info({
34829
34863
  repo: newRepo,
@@ -44283,6 +44317,274 @@ const syncRequestsCommand = {
44283
44317
  })).status === "fail") process.exitCode = 1;
44284
44318
  }
44285
44319
  };
44320
+ // src/commands/sync-templates/plan-template-sync/plan-template-sync.ts
44321
+ /** Compares a template folder with its repo and lists only what differs: files to create, to replace and to remove. */
44322
+ async function planTemplateSync(input) {
44323
+ const remote = new Set(input.remotePaths);
44324
+ const paths = Object.keys(input.files).sort();
44325
+ const plan = {
44326
+ create: [],
44327
+ update: [],
44328
+ remove: []
44329
+ };
44330
+ for (const path of paths) {
44331
+ if (!remote.has(path)) {
44332
+ plan.create.push(path);
44333
+ continue;
44334
+ }
44335
+ const file = await input.read(path);
44336
+ if (!file) plan.create.push(path);
44337
+ else if (file.content !== input.files[path]) plan.update.push({
44338
+ path,
44339
+ version: file.version
44340
+ });
44341
+ }
44342
+ plan.remove = [...remote].filter((p) => !(p in input.files)).sort();
44343
+ return plan;
44344
+ }
44345
+ // src/commands/sync-templates/template-files/template-files.ts
44346
+ /**
44347
+ * Every file of one template folder as `path from the folder -> text`, with `/` separators. `.git` and
44348
+ * `node_modules` are not entered. A file with a NUL byte is binary and throws: the `source` capability writes text, so
44349
+ * publishing it would corrupt it.
44350
+ */
44351
+ function templateFiles(dir) {
44352
+ const files = {};
44353
+ for (const full of walkFilesSync(dir)) {
44354
+ const path = relative(dir, full).split(sep).join("/");
44355
+ const bytes = readFileSync(full);
44356
+ if (bytes.includes(0)) throw new Error(`${path} is a binary file; templates publish text files only`);
44357
+ files[path] = bytes.toString("utf8");
44358
+ }
44359
+ return files;
44360
+ }
44361
+ // src/commands/sync-templates/template-folders/template-folders.ts
44362
+ /**
44363
+ * The template types under `templates/`: its subfolders, sorted. A file beside them (`package.json` and `README.md`
44364
+ * are the group's own) is not a template, and neither is a folder named `node_modules` or one that starts with a dot.
44365
+ * An absent `templates/` folder is no templates.
44366
+ */
44367
+ function templateFolders(templatesDir) {
44368
+ let entries;
44369
+ try {
44370
+ entries = readdirSync(templatesDir, { withFileTypes: true });
44371
+ } catch (err) {
44372
+ if (err.code === "ENOENT") return [];
44373
+ throw err;
44374
+ }
44375
+ return entries.filter((e) => e.isDirectory() && e.name !== "node_modules" && !e.name.startsWith(".")).map((e) => e.name).sort();
44376
+ }
44377
+ // src/commands/sync-templates/templates-version/templates-version.ts
44378
+ /** The `templates` group's version, from `package.json` in the templates folder. Throws when it is missing or has no version. */
44379
+ function templatesVersion(templatesDir) {
44380
+ const path = join(templatesDir, "package.json");
44381
+ let version;
44382
+ try {
44383
+ version = JSON.parse(readFileSync(path, "utf8")).version;
44384
+ } catch (err) {
44385
+ throw new Error(`cannot read the templates version from ${path}`, { cause: err });
44386
+ }
44387
+ if (typeof version !== "string" || version === "") throw new Error(`${path} has no version`);
44388
+ return version;
44389
+ }
44390
+ // src/commands/sync-templates/run-sync-templates/run-sync-templates.ts
44391
+ /**
44392
+ * `holocron sync templates` -- publish each `templates/<type>/` folder to `<org>/<type>-template` and tag that repo
44393
+ * `templates-v<version>` (spec `tech-template-repos`, rollout step 3, #2926).
44394
+ *
44395
+ * Each folder is compared with its repo's default branch; only the difference is written through the `source`
44396
+ * capability (files made, replaced, and removed when the repo has them and the folder no longer does), then the repo is
44397
+ * tagged with the `templates` group's version from `templates/package.json`. A rerun writes nothing and a tag already at
44398
+ * the same content is left alone. It never creates or deletes a repository: a missing template repo is a failing row.
44399
+ * One template failing does not stop the others. It writes, so it asks first; `--yes` skips the question and, without a
44400
+ * terminal, a run with neither `--yes` nor `--dry-run` refuses.
44401
+ */
44402
+ const counts = (p) => `${p.create.length} to create, ${p.update.length} to replace, ${p.remove.length} to remove`;
44403
+ async function runSyncTemplates(input) {
44404
+ const print = input.print ?? ((line) => console.log(line));
44405
+ const row = (status, ...parts) => print(statusRow$1(status, ["sync templates", ...parts]));
44406
+ const summary = (templates) => {
44407
+ const n = (s) => templates.filter((t) => t.status === s).length;
44408
+ print("");
44409
+ print(style.header(`${n("ok")} ok, ${n("fail")} fail, ${n("skip")} skipped`));
44410
+ };
44411
+ const stop = (status, reason) => {
44412
+ row(status, reason);
44413
+ return {
44414
+ status,
44415
+ reason,
44416
+ templates: []
44417
+ };
44418
+ };
44419
+ const dryRun = Boolean(input.context.dryRun);
44420
+ const dir = input.templatesDir ?? join(input.context.repoRoot, "templates");
44421
+ let names;
44422
+ let version;
44423
+ try {
44424
+ names = templateFolders(dir);
44425
+ if (names.length === 0) return stop("skip", `no template folders under ${dir}`);
44426
+ version = templatesVersion(dir);
44427
+ } catch (err) {
44428
+ return stop("fail", errorMessage(err));
44429
+ }
44430
+ const org = input.context.org;
44431
+ if (!org) return stop("fail", "no organization to publish to: set `org` in the config or pass --org");
44432
+ const tag = `templates-v${version}`;
44433
+ /* v8 ignore next -- the real loader is only built outside tests, which always inject one */
44434
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
44435
+ await loader.load();
44436
+ assertPluginsResolvable(loader, "sync templates");
44437
+ const source = loader.has("source") ? loader.get("source") : void 0;
44438
+ if (!source?.readFile || !source.writeFile || !source.listFiles || !source.deleteFile || !source.ensureTag) return stop("fail", whyMissing(loader, "source", "no `source` provider that can read, write, list and delete files and tag is available"));
44439
+ const { readFile, writeFile, listFiles, deleteFile, ensureTag } = source;
44440
+ const results = [];
44441
+ const planned = [];
44442
+ for (const name of names) {
44443
+ const repo = `${org}/${name}-template`;
44444
+ try {
44445
+ const files = templateFiles(join(dir, name));
44446
+ const plan = await planTemplateSync({
44447
+ files,
44448
+ remotePaths: await listFiles.call(source, repo),
44449
+ read: (path) => readFile.call(source, path, repo)
44450
+ });
44451
+ planned.push({
44452
+ name,
44453
+ repo,
44454
+ files,
44455
+ plan
44456
+ });
44457
+ } catch (err) {
44458
+ row("fail", name, repo, describeError(err));
44459
+ results.push({
44460
+ name,
44461
+ repo,
44462
+ status: "fail",
44463
+ created: 0,
44464
+ updated: 0,
44465
+ removed: 0,
44466
+ reason: errorMessage(err)
44467
+ });
44468
+ }
44469
+ }
44470
+ if (dryRun) {
44471
+ for (const p of planned) {
44472
+ row("skip", p.name, p.repo, `dry run, nothing written: ${counts(p.plan)}; would tag ${tag}`);
44473
+ results.push({
44474
+ name: p.name,
44475
+ repo: p.repo,
44476
+ status: "skip",
44477
+ created: p.plan.create.length,
44478
+ updated: p.plan.update.length,
44479
+ removed: p.plan.remove.length
44480
+ });
44481
+ }
44482
+ summary(results);
44483
+ return {
44484
+ status: results.some((r) => r.status === "fail") ? "fail" : "ok",
44485
+ version,
44486
+ templates: results
44487
+ };
44488
+ }
44489
+ if (planned.length > 0 && !input.yes) {
44490
+ if (!(input.interactive ?? Boolean(process.stdin.isTTY))) throw new NonInteractiveError("`sync templates` writes to the template repos; pass --yes to run it without asking, or --dry-run to look");
44491
+ if (!await (input.confirm ?? ((q) => confirm({
44492
+ message: q,
44493
+ default: false
44494
+ })))(`Publish ${planned.length} template(s) as ${tag}?`)) {
44495
+ for (const p of planned) {
44496
+ row("skip", p.name, p.repo, "cancelled; nothing was changed");
44497
+ results.push({
44498
+ name: p.name,
44499
+ repo: p.repo,
44500
+ status: "skip",
44501
+ created: 0,
44502
+ updated: 0,
44503
+ removed: 0
44504
+ });
44505
+ }
44506
+ summary(results);
44507
+ return {
44508
+ status: "cancelled",
44509
+ version,
44510
+ templates: results
44511
+ };
44512
+ }
44513
+ }
44514
+ const message = `chore: sync from ${HOLOCRON_REPO$1} ${tag}`;
44515
+ for (const { name, repo, files, plan } of planned) {
44516
+ const result = {
44517
+ name,
44518
+ repo,
44519
+ status: "ok",
44520
+ created: 0,
44521
+ updated: 0,
44522
+ removed: 0
44523
+ };
44524
+ try {
44525
+ for (const path of plan.create) {
44526
+ await writeFile.call(source, path, files[path], {
44527
+ message,
44528
+ repo
44529
+ });
44530
+ result.created++;
44531
+ }
44532
+ for (const { path, version: fileVersion } of plan.update) {
44533
+ await writeFile.call(source, path, files[path], {
44534
+ message,
44535
+ version: fileVersion,
44536
+ repo
44537
+ });
44538
+ result.updated++;
44539
+ }
44540
+ for (const path of plan.remove) {
44541
+ await deleteFile.call(source, path, {
44542
+ message,
44543
+ repo
44544
+ });
44545
+ result.removed++;
44546
+ }
44547
+ result.tagged = await ensureTag.call(source, tag, repo);
44548
+ row("ok", name, repo, `${result.created} created, ${result.updated} replaced, ${result.removed} removed; ${result.tagged ? `tagged ${tag}` : `${tag} already there`}`);
44549
+ } catch (err) {
44550
+ result.status = "fail";
44551
+ result.reason = errorMessage(err);
44552
+ row("fail", name, repo, describeError(err));
44553
+ }
44554
+ results.push(result);
44555
+ }
44556
+ summary(results);
44557
+ return {
44558
+ status: results.some((r) => r.status === "fail") ? "fail" : "ok",
44559
+ version,
44560
+ templates: results
44561
+ };
44562
+ }
44563
+ // src/commands/sync-templates/sync-templates.command.ts
44564
+ const syncTemplatesCommand = {
44565
+ command: "templates",
44566
+ describe: "Publish each templates/<type>/ folder to its <type>-template repo and tag that repo with the templates version",
44567
+ builder: (y) => y.option("yes", {
44568
+ type: "boolean",
44569
+ describe: "Write without asking (a workflow needs it)"
44570
+ }),
44571
+ handler: async (argv) => {
44572
+ const tokens = tokenContext(argv.token);
44573
+ if (!tokens) return;
44574
+ const loaded = await loadConfig(argv.cwd);
44575
+ applyResolvedConfig(argv, loaded.resolved);
44576
+ if ((await runSyncTemplates({
44577
+ loaded,
44578
+ context: {
44579
+ repoRoot: argv.cwd,
44580
+ dryRun: argv.dryRun,
44581
+ ...tokens,
44582
+ org: resolveOrg(argv, loaded.resolved)
44583
+ },
44584
+ ...argv.yes ? { yes: true } : {}
44585
+ })).status === "fail") process.exitCode = 1;
44586
+ }
44587
+ };
44286
44588
  // src/commands/sync-tooling/run-sync-tooling/run-sync-tooling.ts
44287
44589
  /**
44288
44590
  * `holocron sync tooling` — runs each `tooling` provider's `sync()` and nothing else.
@@ -45347,7 +45649,7 @@ async function syncApp(argv) {
45347
45649
  const syncCommand = {
45348
45650
  command: "sync [steps..]",
45349
45651
  describe: "Sync state from config to the provider and local files (labels, properties, teams, topics, keywords, description, homepage, readme, workflows, scripts, wiki)",
45350
- builder: (y) => syncArgs(y).command(syncGithubCommand).command(syncIssuesCommand).command(syncIncidentsCommand).command(syncPrsCommand).command(syncReleasesCommand).command(syncReadmeCommand).command(ideasSyncCommand).command(syncToolingCommand).command(syncRequestsCommand).command(specsSyncCommand).command(secretsSyncCommand).command(notificationsSyncRolesCommand),
45652
+ builder: (y) => syncArgs(y).command(syncGithubCommand).command(syncIssuesCommand).command(syncIncidentsCommand).command(syncPrsCommand).command(syncReleasesCommand).command(syncTemplatesCommand).command(syncReadmeCommand).command(ideasSyncCommand).command(syncToolingCommand).command(syncRequestsCommand).command(specsSyncCommand).command(secretsSyncCommand).command(notificationsSyncRolesCommand),
45351
45653
  handler: async (argv) => {
45352
45654
  if (argv.env !== void 0 || argv.steps?.[0] !== void 0) {
45353
45655
  if (await syncApp(argv)) return;