@canonical/summon 0.27.1-experimental.0 → 0.30.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 (72) hide show
  1. package/dist/generators/example/hello/index.js +104 -0
  2. package/dist/generators/example/hello/index.js.map +1 -0
  3. package/dist/generators/example/webapp/index.js +374 -0
  4. package/dist/generators/example/webapp/index.js.map +1 -0
  5. package/dist/generators/init/index.js +98 -0
  6. package/dist/generators/init/index.js.map +1 -0
  7. package/dist/src/bin.js +153 -0
  8. package/dist/src/bin.js.map +1 -0
  9. package/dist/src/completion.js +375 -0
  10. package/dist/src/completion.js.map +1 -0
  11. package/dist/src/components/App.js +621 -0
  12. package/dist/src/components/App.js.map +1 -0
  13. package/dist/src/components/ExecutionProgress.js +132 -0
  14. package/dist/src/components/ExecutionProgress.js.map +1 -0
  15. package/dist/src/components/FileTreePreview.js +55 -0
  16. package/dist/src/components/FileTreePreview.js.map +1 -0
  17. package/dist/src/components/PromptSequence.js +215 -0
  18. package/dist/src/components/PromptSequence.js.map +1 -0
  19. package/dist/src/components/Spinner.js +20 -0
  20. package/dist/src/components/Spinner.js.map +1 -0
  21. package/{src/components/index.ts → dist/src/components/index.js} +1 -6
  22. package/dist/src/components/index.js.map +1 -0
  23. package/{src/discovery/index.ts → dist/src/discovery/index.js} +1 -0
  24. package/dist/src/discovery/index.js.map +1 -0
  25. package/dist/src/discovery/loadGenerator.js +29 -0
  26. package/dist/src/discovery/loadGenerator.js.map +1 -0
  27. package/{src/display/index.ts → dist/src/display/index.js} +1 -0
  28. package/dist/src/display/index.js.map +1 -0
  29. package/dist/src/display/printGeneratorHelp.js +99 -0
  30. package/dist/src/display/printGeneratorHelp.js.map +1 -0
  31. package/dist/src/display/printNode.js +64 -0
  32. package/dist/src/display/printNode.js.map +1 -0
  33. package/dist/src/registration/buildCommandBarrel.js +45 -0
  34. package/dist/src/registration/buildCommandBarrel.js.map +1 -0
  35. package/{src/registration/index.ts → dist/src/registration/index.js} +1 -1
  36. package/dist/src/registration/index.js.map +1 -0
  37. package/dist/src/registration/registerFromBarrel.js +408 -0
  38. package/dist/src/registration/registerFromBarrel.js.map +1 -0
  39. package/dist/src/registration/types.js +2 -0
  40. package/dist/src/registration/types.js.map +1 -0
  41. package/package.json +13 -14
  42. package/generators/example/hello/index.ts +0 -126
  43. package/generators/example/webapp/index.ts +0 -511
  44. package/generators/init/index.ts +0 -119
  45. package/src/bin.tsx +0 -199
  46. package/src/completion.test.ts +0 -202
  47. package/src/completion.ts +0 -492
  48. package/src/components/App.tsx +0 -1053
  49. package/src/components/ExecutionProgress.tsx +0 -209
  50. package/src/components/FileTreePreview.tsx +0 -97
  51. package/src/components/PromptSequence.tsx +0 -483
  52. package/src/components/Spinner.tsx +0 -36
  53. package/src/discovery/loadGenerator.ts +0 -37
  54. package/src/display/printGeneratorHelp.ts +0 -128
  55. package/src/display/printNode.ts +0 -76
  56. package/src/registration/buildCommandBarrel.ts +0 -57
  57. package/src/registration/registerFromBarrel.tsx +0 -548
  58. package/src/registration/types.ts +0 -28
  59. /package/{generators → dist/generators}/example/hello/templates/README.md.ejs +0 -0
  60. /package/{generators → dist/generators}/example/hello/templates/index.ts.ejs +0 -0
  61. /package/{generators → dist/generators}/example/webapp/templates/ARCHITECTURE.md.ejs +0 -0
  62. /package/{generators → dist/generators}/example/webapp/templates/App.tsx.ejs +0 -0
  63. /package/{generators → dist/generators}/example/webapp/templates/README.md.ejs +0 -0
  64. /package/{generators → dist/generators}/example/webapp/templates/app.test.ts.ejs +0 -0
  65. /package/{generators → dist/generators}/example/webapp/templates/app.ts.ejs +0 -0
  66. /package/{generators → dist/generators}/example/webapp/templates/feature.ts.ejs +0 -0
  67. /package/{generators → dist/generators}/example/webapp/templates/index.html.ejs +0 -0
  68. /package/{generators → dist/generators}/example/webapp/templates/main.tsx.ejs +0 -0
  69. /package/{generators → dist/generators}/example/webapp/templates/styles.css.ejs +0 -0
  70. /package/{generators → dist/generators}/init/templates/generator.ts.ejs +0 -0
  71. /package/{generators → dist/generators}/init/templates/template-index.ts.ejs +0 -0
  72. /package/{generators → dist/generators}/init/templates/template-test.ts.ejs +0 -0
@@ -1,76 +0,0 @@
1
- /**
2
- * Print available generators/sub-generators at a tree node.
3
- *
4
- * @note Impure — writes to stdout.
5
- */
6
-
7
- import type { GeneratorNode, GeneratorOrigin } from "@canonical/summon-core";
8
- import chalk from "chalk";
9
-
10
- /**
11
- * Format origin badge for display.
12
- */
13
- const formatOrigin = (origin?: GeneratorOrigin): string => {
14
- switch (origin) {
15
- case "local":
16
- return chalk.green("[local]");
17
- case "global":
18
- return chalk.blue("[global]");
19
- case "package":
20
- return chalk.magenta("[pkg]");
21
- case "builtin":
22
- return chalk.dim("[builtin]");
23
- default:
24
- return "";
25
- }
26
- };
27
-
28
- export default function printNode(
29
- node: GeneratorNode,
30
- pathSegments: string[],
31
- ): void {
32
- const prefix = pathSegments.length > 0 ? `${pathSegments.join(" ")} ` : "";
33
- const isRoot = pathSegments.length === 0;
34
-
35
- if (node.children.size === 0) {
36
- console.log(chalk.yellow("No generators found"));
37
- console.log(chalk.dim("\nInstall a generator package:"));
38
- console.log(chalk.dim(" bun add @scope/summon-<name>"));
39
- console.log(chalk.dim("\nOr link globally (from the package directory):"));
40
- console.log(chalk.dim(" bun link # for bun users"));
41
- console.log(chalk.dim(" npm link # for npm users"));
42
- return;
43
- }
44
-
45
- if (isRoot) {
46
- console.log(chalk.bold("\nAvailable topics:\n"));
47
- } else {
48
- console.log(chalk.bold(`\nAvailable under '${pathSegments.join(" ")}':\n`));
49
- }
50
-
51
- for (const [name, child] of node.children) {
52
- const hasChildren = child.children.size > 0;
53
- const isRunnable = !!child.indexPath;
54
- const originBadge = child.origin ? ` ${formatOrigin(child.origin)}` : "";
55
-
56
- let suffix = "";
57
- if (hasChildren && isRunnable) {
58
- suffix = chalk.dim(" (runnable, has subtopics)");
59
- } else if (hasChildren) {
60
- suffix = chalk.dim(" (has subtopics)");
61
- }
62
-
63
- console.log(chalk.cyan(` ${name}`) + originBadge + suffix);
64
-
65
- // Show immediate children as hints
66
- if (hasChildren) {
67
- const childNames = [...child.children.keys()].slice(0, 5);
68
- const more =
69
- child.children.size > 5 ? `, +${child.children.size - 5} more` : "";
70
- console.log(chalk.dim(` └─ ${childNames.join(", ")}${more}`));
71
- }
72
- }
73
-
74
- console.log(chalk.dim(`\nUsage: summon ${prefix}<topic>`));
75
- console.log();
76
- }
@@ -1,57 +0,0 @@
1
- /**
2
- * Build a flat command list from a generator tree.
3
- *
4
- * Flattens the tree into a list of {@link CommandEntry} sorted by depth
5
- * so that parents are registered before children.
6
- *
7
- * @note Impure — loads generators via dynamic import.
8
- */
9
-
10
- import type { GeneratorNode } from "@canonical/summon-core";
11
- import chalk from "chalk";
12
- import { loadGenerator } from "../discovery/index.js";
13
- import type { CommandEntry } from "./types.js";
14
-
15
- export default async function buildCommandBarrel(
16
- node: GeneratorNode,
17
- pathSegments: string[] = [],
18
- ): Promise<CommandEntry[]> {
19
- const entries: CommandEntry[] = [];
20
-
21
- for (const [name, child] of node.children) {
22
- const childPath = [...pathSegments, name];
23
-
24
- if (child.indexPath) {
25
- // Runnable generator
26
- try {
27
- const generator = await loadGenerator(child.indexPath);
28
- entries.push({ path: childPath, generator });
29
-
30
- // If it also has children, we need to ensure parent exists and recurse
31
- if (child.children.size > 0) {
32
- const childEntries = await buildCommandBarrel(child, childPath);
33
- entries.push(...childEntries);
34
- }
35
- } catch (err) {
36
- console.error(
37
- chalk.yellow(`Warning: Could not load generator '${name}':`),
38
- (err as Error).message,
39
- );
40
- }
41
- } else if (child.children.size > 0) {
42
- // Namespace-only (no indexPath but has children)
43
- // Add a placeholder entry so we create the parent command
44
- entries.push({
45
- path: childPath,
46
- description: `${name} generators`,
47
- });
48
-
49
- // Recurse into children
50
- const childEntries = await buildCommandBarrel(child, childPath);
51
- entries.push(...childEntries);
52
- }
53
- }
54
-
55
- // Sort by path length so parents are registered before children
56
- return entries.sort((a, b) => a.path.length - b.path.length);
57
- }
@@ -1,548 +0,0 @@
1
- /**
2
- * Register commands from a command barrel onto a Commander program.
3
- *
4
- * Handles option wiring, grouped help, answer extraction, mode expansion
5
- * (--llm, --format json), and the action handler for each generator command.
6
- *
7
- * @note Impure — writes to stdout/stderr, renders Ink components.
8
- */
9
-
10
- import {
11
- formatEffectLine,
12
- formatEffectWithContent,
13
- formatLlmJson,
14
- formatLlmMarkdown,
15
- isVisibleEffect,
16
- } from "@canonical/cli-core";
17
- import type {
18
- GeneratorDefinition,
19
- PromptDefinition,
20
- StampConfig,
21
- } from "@canonical/summon-core";
22
- import { dryRun, runUndo } from "@canonical/task";
23
- import chalk from "chalk";
24
- import type { Command } from "commander";
25
- import { render } from "ink";
26
- import { App } from "../components/App.js";
27
- import type { CommandEntry, OptionInfo } from "./types.js";
28
-
29
- // =============================================================================
30
- // Internal helpers
31
- // =============================================================================
32
-
33
- /**
34
- * Convert camelCase to kebab-case.
35
- * withTests -> with-tests
36
- */
37
- const toKebabCase = (str: string): string =>
38
- str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
39
-
40
- const buildOptionInfo = (prompt: PromptDefinition): OptionInfo => {
41
- const kebabName = toKebabCase(prompt.name);
42
- const flagName = `--${kebabName}`;
43
-
44
- // NOTE: We intentionally do NOT pass defaultValue to Commander.
45
- // Defaults are handled by applyDefaults() after prompting, so we can
46
- // distinguish between "user didn't provide" vs "user provided default value".
47
-
48
- switch (prompt.type) {
49
- case "confirm": {
50
- const defaultVal = prompt.default === true;
51
- if (defaultVal) {
52
- return {
53
- flags: `--no-${kebabName}`,
54
- description: `${prompt.message}`,
55
- group: prompt.group,
56
- promptName: prompt.name,
57
- kebabName,
58
- };
59
- }
60
- return {
61
- flags: flagName,
62
- description: `${prompt.message}`,
63
- group: prompt.group,
64
- promptName: prompt.name,
65
- kebabName,
66
- };
67
- }
68
- case "select": {
69
- const choices = prompt.choices?.map((c) => c.value).join("|") ?? "";
70
- return {
71
- flags: `${flagName} <value>`,
72
- description: `${prompt.message} [${choices}]`,
73
- group: prompt.group,
74
- promptName: prompt.name,
75
- kebabName,
76
- };
77
- }
78
- case "multiselect": {
79
- return {
80
- flags: `${flagName} <values>`,
81
- description: `${prompt.message} (comma-separated)`,
82
- group: prompt.group,
83
- promptName: prompt.name,
84
- kebabName,
85
- };
86
- }
87
- default: {
88
- return {
89
- flags: `${flagName} <value>`,
90
- description: `${prompt.message}`,
91
- group: prompt.group,
92
- promptName: prompt.name,
93
- kebabName,
94
- };
95
- }
96
- }
97
- };
98
-
99
- /**
100
- * Add prompt-based options to a Commander command.
101
- */
102
- const addPromptOptions = (cmd: Command, prompts: PromptDefinition[]): void => {
103
- for (const prompt of prompts) {
104
- const info = buildOptionInfo(prompt);
105
- cmd.option(info.flags, info.description, info.defaultValue);
106
- }
107
- };
108
-
109
- /**
110
- * Configure custom help with grouped options for a command.
111
- */
112
- const configureGroupedHelp = (
113
- cmd: Command,
114
- prompts: PromptDefinition[],
115
- ): void => {
116
- // Collect option info by group
117
- const groups = new Map<string, OptionInfo[]>();
118
- const defaultGroupName = "Generator Options";
119
-
120
- for (const prompt of prompts) {
121
- const info = buildOptionInfo(prompt);
122
- const groupName = info.group ?? defaultGroupName;
123
- if (!groups.has(groupName)) {
124
- groups.set(groupName, []);
125
- }
126
- groups.get(groupName)?.push(info);
127
- }
128
-
129
- // Only configure custom help if there are grouped options
130
- if (groups.size <= 1 && !prompts.some((p) => p.group)) {
131
- return;
132
- }
133
-
134
- // Override help output using configureHelp
135
- cmd.configureHelp({
136
- formatHelp: (cmd, helper) => {
137
- const termWidth = 28; // Fixed width for option flags column
138
-
139
- const formatItem = (
140
- term: string,
141
- description: string,
142
- defaultVal?: string,
143
- ): string => {
144
- const fullDesc = defaultVal
145
- ? `${description} (default: ${JSON.stringify(defaultVal)})`
146
- : description;
147
-
148
- if (description) {
149
- const padding = " ".repeat(Math.max(termWidth - term.length, 2));
150
- return ` ${term}${padding}${fullDesc}`;
151
- }
152
- return ` ${term}`;
153
- };
154
-
155
- let output = "";
156
-
157
- // Usage
158
- output += `Usage: ${helper.commandUsage(cmd)}\n`;
159
-
160
- // Description
161
- const desc = helper.commandDescription(cmd);
162
- if (desc) {
163
- output += `\n${desc}\n`;
164
- }
165
-
166
- // Built-in options (Global Options group)
167
- output += "\nGlobal Options:\n";
168
- output += formatItem("-d, --dry-run", "Preview without writing files");
169
- output += "\n";
170
- output += formatItem(
171
- "-y, --yes",
172
- "Skip confirmation prompts and preview",
173
- );
174
- output += "\n";
175
- output += formatItem("-v, --verbose", "Show debug output");
176
- output += "\n";
177
- output += formatItem("--show-files", "Show file contents in dry-run");
178
- output += "\n";
179
- output += formatItem("--no-preview", "Skip the file preview");
180
- output += "\n";
181
- output += formatItem(
182
- "--no-generated-stamp",
183
- "Disable generated file stamp comments",
184
- );
185
- output += "\n";
186
- output += formatItem(
187
- "-l, --llm",
188
- "Dry-run with markdown output, no prompts, no stamps",
189
- );
190
- output += "\n";
191
- output += formatItem(
192
- "--format <type>",
193
- "Output format: json (dry-run, no prompts, no stamps)",
194
- );
195
- output += "\n";
196
- output += formatItem("-h, --help", "display help for command");
197
- output += "\n";
198
-
199
- // Grouped prompt options
200
- for (const [groupName, options] of groups) {
201
- output += `\n${groupName}:\n`;
202
- for (const opt of options) {
203
- output += formatItem(opt.flags, opt.description, opt.defaultValue);
204
- output += "\n";
205
- }
206
- }
207
-
208
- return output;
209
- },
210
- });
211
- };
212
-
213
- /**
214
- * Extract answers from Commander options based on prompts.
215
- */
216
- const extractAnswers = (
217
- options: Record<string, unknown>,
218
- prompts: PromptDefinition[],
219
- ): Record<string, unknown> => {
220
- const answers: Record<string, unknown> = {};
221
-
222
- for (const prompt of prompts) {
223
- const value = options[prompt.name];
224
-
225
- if (value !== undefined) {
226
- switch (prompt.type) {
227
- case "confirm": {
228
- const boolValue = Boolean(value);
229
- if (boolValue !== prompt.default) {
230
- answers[prompt.name] = boolValue;
231
- }
232
- break;
233
- }
234
- case "multiselect":
235
- answers[prompt.name] =
236
- typeof value === "string"
237
- ? value.split(",").map((v) => v.trim())
238
- : value;
239
- break;
240
- default:
241
- answers[prompt.name] = value;
242
- }
243
- }
244
- }
245
-
246
- return answers;
247
- };
248
-
249
- /**
250
- * Check if all required prompts have answers.
251
- */
252
- const hasAllRequiredAnswers = (
253
- prompts: GeneratorDefinition["prompts"],
254
- answers: Record<string, unknown>,
255
- ): boolean => {
256
- for (const prompt of prompts) {
257
- if (prompt.when) continue;
258
- if (!(prompt.name in answers) && prompt.default === undefined) {
259
- return false;
260
- }
261
- }
262
- return true;
263
- };
264
-
265
- /**
266
- * Apply defaults for prompts that don't have answers.
267
- */
268
- const applyDefaults = (
269
- prompts: GeneratorDefinition["prompts"],
270
- answers: Record<string, unknown>,
271
- ): Record<string, unknown> => {
272
- const result = { ...answers };
273
- for (const prompt of prompts) {
274
- if (!(prompt.name in result) && prompt.default !== undefined) {
275
- result[prompt.name] = prompt.default;
276
- }
277
- }
278
- return result;
279
- };
280
-
281
- /**
282
- * Configure a command with generator options and action.
283
- */
284
- const configureGeneratorCommand = (
285
- cmd: Command,
286
- generator: GeneratorDefinition,
287
- positionalPrompt?: PromptDefinition,
288
- ): void => {
289
- // Add prompt-based options
290
- addPromptOptions(cmd, generator.prompts);
291
-
292
- // Configure grouped help display
293
- configureGroupedHelp(cmd, generator.prompts);
294
-
295
- // Add action
296
- cmd.action(
297
- async (
298
- positionalArg: string | Record<string, unknown> | undefined,
299
- cmdOptions?: Record<string, unknown>,
300
- ) => {
301
- let actualOptions: Record<string, unknown>;
302
-
303
- if (positionalPrompt) {
304
- actualOptions = cmdOptions ?? {};
305
- } else {
306
- actualOptions = (positionalArg as Record<string, unknown>) ?? {};
307
- }
308
-
309
- // Support SUMMON_LLM=1 environment variable
310
- if (process.env.SUMMON_LLM === "1" && actualOptions.llm !== true) {
311
- actualOptions.llm = true;
312
- }
313
-
314
- // Expand --llm flag into its component flags
315
- if (actualOptions.llm === true) {
316
- actualOptions.dryRun = true;
317
- actualOptions.showFiles = true;
318
- actualOptions.yes = true;
319
- actualOptions.generatedStamp = false;
320
- }
321
-
322
- // Expand --format json into its component flags
323
- if (actualOptions.format === "json") {
324
- actualOptions.dryRun = true;
325
- actualOptions.showFiles = true;
326
- actualOptions.yes = true;
327
- actualOptions.generatedStamp = false;
328
- }
329
-
330
- // Extract only explicitly provided CLI answers (not defaults)
331
- const cliAnswers = extractAnswers(actualOptions, generator.prompts);
332
-
333
- // If positional argument was provided, add it to the answers
334
- if (
335
- positionalPrompt &&
336
- typeof positionalArg === "string" &&
337
- positionalArg
338
- ) {
339
- cliAnswers[positionalPrompt.name] = positionalArg;
340
- }
341
-
342
- // Apply defaults for checking if we have all required answers
343
- const answersWithDefaults = applyDefaults(generator.prompts, cliAnswers);
344
-
345
- // Determine execution mode
346
- const hasAllAnswers = hasAllRequiredAnswers(
347
- generator.prompts,
348
- answersWithDefaults,
349
- );
350
- const isTTY = process.stdin.isTTY === true;
351
- const skipPrompts = actualOptions.yes === true;
352
-
353
- // Build stamp config if stamps are enabled (default: enabled)
354
- const stampEnabled = actualOptions.generatedStamp !== false;
355
- const stamp: StampConfig | undefined = stampEnabled
356
- ? {
357
- generator: generator.meta.displayName,
358
- version: generator.meta.version,
359
- }
360
- : undefined;
361
-
362
- // Undo mode (non-interactive batch)
363
- if (hasAllAnswers && actualOptions.undo && !isTTY) {
364
- const task = generator.generate(answersWithDefaults);
365
- try {
366
- const result = await runUndo(task);
367
- if (result.undoCount === 0) {
368
- console.log("Nothing to undo.");
369
- } else {
370
- console.log(
371
- `Undo complete (${result.undoCount} step${result.undoCount === 1 ? "" : "s"} reversed).`,
372
- );
373
- }
374
- } catch (err) {
375
- const message = err instanceof Error ? err.message : String(err);
376
- console.error(`Undo failed: ${message}`);
377
- process.exitCode = 1;
378
- }
379
- return;
380
- }
381
-
382
- if (hasAllAnswers && actualOptions.dryRun && !isTTY) {
383
- // Batch dry-run mode (non-interactive)
384
- const verbose = actualOptions.verbose === true;
385
- const showFiles = actualOptions.showFiles === true;
386
-
387
- const task = generator.generate(answersWithDefaults);
388
- const result = dryRun(task);
389
-
390
- if (actualOptions.llm === true) {
391
- const output = formatLlmMarkdown(
392
- generator,
393
- answersWithDefaults,
394
- result.effects,
395
- verbose,
396
- );
397
- process.stdout.write(output);
398
- } else if (actualOptions.format === "json") {
399
- const output = formatLlmJson(
400
- generator,
401
- answersWithDefaults,
402
- result.effects,
403
- verbose,
404
- );
405
- process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
406
- } else {
407
- console.log();
408
- console.log(chalk.bold.magenta(generator.meta.name));
409
- console.log(chalk.dim(generator.meta.description));
410
- console.log();
411
-
412
- // Filter and deduplicate effects
413
- const seenDirPaths = new Set<string>();
414
- const visibleEffects = result.effects.filter((e) => {
415
- if (!isVisibleEffect(e, verbose)) return false;
416
- if (e._tag === "MakeDir") {
417
- if (seenDirPaths.has(e.path)) return false;
418
- seenDirPaths.add(e.path);
419
- }
420
- return true;
421
- });
422
-
423
- console.log(chalk.dim.bold("Plan:"));
424
- visibleEffects.forEach((effect, index) => {
425
- const isLast = index === visibleEffects.length - 1;
426
- if (showFiles) {
427
- console.log(formatEffectWithContent(effect, isLast));
428
- } else {
429
- console.log(formatEffectLine(effect, isLast));
430
- }
431
- });
432
-
433
- console.log();
434
- console.log(chalk.dim("Dry-run complete. No files were modified."));
435
-
436
- if (!showFiles) {
437
- console.log(
438
- chalk.dim("Tip: Use --show-files to see generated file contents"),
439
- );
440
- }
441
- }
442
- } else {
443
- // Interactive mode
444
- const shouldSkipPrompts =
445
- skipPrompts || Object.keys(cliAnswers).length > 0;
446
- const passedAnswers = shouldSkipPrompts
447
- ? answersWithDefaults
448
- : undefined;
449
-
450
- const shouldShowPreview = skipPrompts
451
- ? false
452
- : (actualOptions.preview as boolean);
453
-
454
- const { waitUntilExit } = render(
455
- <App
456
- generator={generator}
457
- preview={shouldShowPreview}
458
- dryRunOnly={actualOptions.dryRun as boolean}
459
- undo={actualOptions.undo as boolean}
460
- verbose={actualOptions.verbose as boolean}
461
- answers={passedAnswers}
462
- stamp={stamp}
463
- />,
464
- );
465
-
466
- await waitUntilExit();
467
- }
468
- },
469
- );
470
- };
471
-
472
- // =============================================================================
473
- // Public API
474
- // =============================================================================
475
-
476
- /**
477
- * Register all commands from a command barrel onto a Commander program.
478
- *
479
- * @note Impure — mutates the Commander program.
480
- */
481
- export default function registerFromBarrel(
482
- rootCmd: Command,
483
- barrel: CommandEntry[],
484
- ): void {
485
- const commandMap = new Map<string, Command>();
486
- commandMap.set("", rootCmd);
487
-
488
- for (const entry of barrel) {
489
- const name = entry.path[entry.path.length - 1];
490
- const parentPath = entry.path.slice(0, -1).join("/");
491
- const currentPath = entry.path.join("/");
492
-
493
- // Skip if already registered (can happen with namespace + runnable at same path)
494
- const existingCmd = commandMap.get(currentPath);
495
- if (existingCmd) {
496
- if (entry.generator) {
497
- configureGeneratorCommand(existingCmd, entry.generator);
498
- }
499
- continue;
500
- }
501
-
502
- // Get or create parent command
503
- const parentCmd = commandMap.get(parentPath) ?? rootCmd;
504
-
505
- if (entry.generator) {
506
- const positionalPrompt = entry.generator.prompts.find(
507
- (p) => p.positional,
508
- );
509
-
510
- const commandSpec = positionalPrompt
511
- ? `${name} [${toKebabCase(positionalPrompt.name)}]`
512
- : name;
513
-
514
- const cmd = parentCmd
515
- .command(commandSpec)
516
- .description(entry.generator.meta.description)
517
- .option("-d, --dry-run", "Preview without writing files")
518
- .option("--undo", "Reverse a previously executed generator")
519
- .option("-y, --yes", "Skip confirmation prompts and preview")
520
- .option("-v, --verbose", "Show debug output")
521
- .option("--show-files", "Show file contents in dry-run")
522
- .option("--no-preview", "Skip the file preview")
523
- .option("--no-generated-stamp", "Disable generated file stamp comments")
524
- .option(
525
- "-l, --llm",
526
- "LLM mode: dry-run with markdown output, no prompts, no stamps",
527
- )
528
- .option(
529
- "--format <type>",
530
- "Output format: json (implies dry-run, no prompts, no stamps)",
531
- );
532
-
533
- if (positionalPrompt) {
534
- const positionalName = toKebabCase(positionalPrompt.name);
535
- cmd.usage(`[${positionalName}] [options]`);
536
- }
537
-
538
- configureGeneratorCommand(cmd, entry.generator, positionalPrompt);
539
- commandMap.set(currentPath, cmd);
540
- } else {
541
- const cmd = parentCmd
542
- .command(name)
543
- .description(entry.description ?? `${name} commands`);
544
-
545
- commandMap.set(currentPath, cmd);
546
- }
547
- }
548
- }
@@ -1,28 +0,0 @@
1
- import type { GeneratorDefinition } from "@canonical/summon-core";
2
-
3
- /**
4
- * A flattened representation of a command to register.
5
- * Separates command discovery from registration.
6
- */
7
- export interface CommandEntry {
8
- /** Path segments to this command (e.g., ["component", "react"]) */
9
- path: string[];
10
- /** The generator definition if this is a runnable command */
11
- generator?: GeneratorDefinition;
12
- /** Description for namespace-only commands */
13
- description?: string;
14
- }
15
-
16
- /**
17
- * Option metadata built from a prompt definition for Commander.
18
- */
19
- export interface OptionInfo {
20
- flags: string;
21
- description: string;
22
- defaultValue?: string;
23
- group?: string;
24
- /** The original camelCase prompt name */
25
- promptName: string;
26
- /** The kebab-case flag name (without --) */
27
- kebabName: string;
28
- }