@canonical/summon 0.17.1 → 0.21.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 (41) hide show
  1. package/generators/example/hello/index.ts +3 -9
  2. package/generators/example/webapp/index.ts +7 -5
  3. package/generators/init/index.ts +3 -8
  4. package/generators/init/templates/generator.ts.ejs +3 -9
  5. package/package.json +25 -27
  6. package/src/bin.tsx +199 -0
  7. package/src/completion.test.ts +202 -0
  8. package/src/completion.ts +4 -1
  9. package/src/components/App.tsx +108 -15
  10. package/src/components/ExecutionProgress.tsx +8 -4
  11. package/src/components/FileTreePreview.tsx +1 -1
  12. package/src/components/PromptSequence.tsx +1 -1
  13. package/src/discovery/index.ts +1 -0
  14. package/src/discovery/loadGenerator.ts +37 -0
  15. package/src/display/index.ts +2 -0
  16. package/src/display/printGeneratorHelp.ts +128 -0
  17. package/src/display/printNode.ts +76 -0
  18. package/src/registration/buildCommandBarrel.ts +57 -0
  19. package/src/registration/index.ts +3 -0
  20. package/src/registration/registerFromBarrel.tsx +548 -0
  21. package/src/registration/types.ts +28 -0
  22. package/README.md +0 -446
  23. package/src/__tests__/combinators.test.ts +0 -895
  24. package/src/__tests__/dry-run.test.ts +0 -927
  25. package/src/__tests__/effect.test.ts +0 -816
  26. package/src/__tests__/interpreter.test.ts +0 -673
  27. package/src/__tests__/primitives.test.ts +0 -970
  28. package/src/__tests__/task.test.ts +0 -929
  29. package/src/__tests__/template.test.ts +0 -666
  30. package/src/cli-format.ts +0 -236
  31. package/src/cli-types.ts +0 -53
  32. package/src/cli.tsx +0 -1366
  33. package/src/combinators.ts +0 -294
  34. package/src/dry-run.ts +0 -434
  35. package/src/effect.ts +0 -224
  36. package/src/index.ts +0 -266
  37. package/src/interpreter.ts +0 -463
  38. package/src/primitives.ts +0 -442
  39. package/src/task.ts +0 -245
  40. package/src/template.ts +0 -537
  41. package/src/types.ts +0 -453
@@ -0,0 +1,548 @@
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
+ }
@@ -0,0 +1,28 @@
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
+ }