@canonical/summon 0.37.0 → 0.38.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/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +16 -0
- package/dist/src/index.js.map +1 -0
- package/package.json +17 -12
- package/src/bin.tsx +238 -0
- package/src/completion.test.ts +202 -0
- package/src/completion.ts +492 -0
- package/src/components/App.askMissing.test.tsx +164 -0
- package/src/components/App.confirmGate.test.tsx +111 -0
- package/src/components/App.escBack.test.tsx +98 -0
- package/src/components/App.invalidAnswer.test.tsx +71 -0
- package/src/components/App.tsx +1305 -0
- package/src/components/ExecutionProgress.tsx +222 -0
- package/src/components/FileTreePreview.tsx +97 -0
- package/src/components/PromptSequence.tsx +558 -0
- package/src/components/Spinner.tsx +36 -0
- package/src/components/index.ts +16 -0
- package/src/components/undoPlan.test.ts +99 -0
- package/src/components/undoPlan.ts +70 -0
- package/src/discovery/index.ts +1 -0
- package/src/discovery/loadGenerator.ts +40 -0
- package/src/display/index.ts +2 -0
- package/src/display/printGeneratorHelp.ts +130 -0
- package/src/display/printNode.ts +76 -0
- package/src/index.ts +16 -0
- package/src/registration/buildCommandBarrel.test.ts +80 -0
- package/src/registration/buildCommandBarrel.ts +66 -0
- package/src/registration/conformance.subprocess.test.ts +192 -0
- package/src/registration/index.ts +2 -0
- package/src/registration/interaction.subprocess.test.ts +458 -0
- package/src/registration/registerFromBarrel.tsx +501 -0
- package/src/registration/resolveMode.test.ts +118 -0
- package/src/registration/resolveMode.ts +52 -0
- package/src/testing/globalSetup.test.ts +165 -0
- package/src/testing/globalSetup.ts +501 -0
- package/src/ui/index.tsx +31 -0
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Register commands from a command barrel onto a Commander program — the
|
|
3
|
+
* summon HOST over the shared registration path in
|
|
4
|
+
* `@canonical/summon-core/projection`.
|
|
5
|
+
*
|
|
6
|
+
* The projection owns everything derivable from the prompts (command specs,
|
|
7
|
+
* prompt options, grouped help, namespace parents); this module contributes
|
|
8
|
+
* only what is summon-shaped: the nine standard flags, the `--llm`/`--format
|
|
9
|
+
* json`/`SUMMON_LLM` mode expansions, and the action body that decides between
|
|
10
|
+
* the batch renderers and the Ink app.
|
|
11
|
+
*
|
|
12
|
+
* @note Impure — writes to stdout/stderr, renders Ink components.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
createGeneratorStamp,
|
|
17
|
+
formatEffectLine,
|
|
18
|
+
formatEffectWithContent,
|
|
19
|
+
formatLlmJson,
|
|
20
|
+
formatLlmMarkdown,
|
|
21
|
+
type GeneratorDefinition,
|
|
22
|
+
isInvalidAnswersError,
|
|
23
|
+
missingRequiredError,
|
|
24
|
+
type PromptEffect,
|
|
25
|
+
type StampConfig,
|
|
26
|
+
validateAnswers,
|
|
27
|
+
visiblePlanEffects,
|
|
28
|
+
} from "@canonical/summon-core";
|
|
29
|
+
import {
|
|
30
|
+
applyDefaults,
|
|
31
|
+
type CommandEntry,
|
|
32
|
+
extractAnswers,
|
|
33
|
+
type HostFlags,
|
|
34
|
+
hasAllRequiredAnswers,
|
|
35
|
+
missingExplicitFlags,
|
|
36
|
+
refusalMessage,
|
|
37
|
+
} from "@canonical/summon-core/projection";
|
|
38
|
+
import {
|
|
39
|
+
type CommanderHost,
|
|
40
|
+
emitToProcess,
|
|
41
|
+
registerGeneratorCommands,
|
|
42
|
+
} from "@canonical/summon-core/projection/commander";
|
|
43
|
+
import {
|
|
44
|
+
collectUndos,
|
|
45
|
+
describeEffect,
|
|
46
|
+
dryRun,
|
|
47
|
+
type Effect,
|
|
48
|
+
type Task,
|
|
49
|
+
} from "@canonical/task";
|
|
50
|
+
import { hostExistsResolver, runCollectedUndos } from "@canonical/task/node";
|
|
51
|
+
import chalk from "chalk";
|
|
52
|
+
import type { Command } from "commander";
|
|
53
|
+
import { render } from "ink";
|
|
54
|
+
import { App } from "../components/App.js";
|
|
55
|
+
import {
|
|
56
|
+
describeUndoSteps,
|
|
57
|
+
isUnreversibleExec,
|
|
58
|
+
} from "../components/undoPlan.js";
|
|
59
|
+
import { resolveSummonMode, summonIsTTY } from "./resolveMode.js";
|
|
60
|
+
|
|
61
|
+
// =============================================================================
|
|
62
|
+
// The summon host: standard flags + help rows
|
|
63
|
+
// =============================================================================
|
|
64
|
+
|
|
65
|
+
/** Register summon's nine standard per-generator flags. */
|
|
66
|
+
function registerStandardFlags(cmd: Command): void {
|
|
67
|
+
cmd
|
|
68
|
+
.option("-d, --dry-run", "Preview without writing files")
|
|
69
|
+
.option("--undo", "Reverse a previously executed generator")
|
|
70
|
+
.option("-y, --yes", "Skip confirmation prompts and preview")
|
|
71
|
+
.option("-v, --verbose", "Show debug output")
|
|
72
|
+
.option("--show-files", "Show file contents in dry-run")
|
|
73
|
+
.option("--no-preview", "Skip the file preview")
|
|
74
|
+
.option("--no-generated-stamp", "Disable generated file stamp comments")
|
|
75
|
+
.option(
|
|
76
|
+
"-l, --llm",
|
|
77
|
+
"LLM mode: dry-run with markdown output, no prompts, no stamps",
|
|
78
|
+
)
|
|
79
|
+
.option(
|
|
80
|
+
"--format <type>",
|
|
81
|
+
"Output format: json (implies dry-run, no prompts, no stamps)",
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Summon's standard-flag rows for the grouped-help Global Options block. */
|
|
86
|
+
const STANDARD_FLAG_HELP: HostFlags = [
|
|
87
|
+
{ flags: "-d, --dry-run", description: "Preview without writing files" },
|
|
88
|
+
// `--undo` was registered but MISSING from the grouped help's hard-coded
|
|
89
|
+
// block for as long as the block existed; the parity set (prompt-derived ∪
|
|
90
|
+
// --dry-run/--undo/--yes) makes the omission a test failure, so it is fixed.
|
|
91
|
+
{ flags: "--undo", description: "Reverse a previously executed generator" },
|
|
92
|
+
{ flags: "-y, --yes", description: "Skip confirmation prompts and preview" },
|
|
93
|
+
{ flags: "-v, --verbose", description: "Show debug output" },
|
|
94
|
+
{ flags: "--show-files", description: "Show file contents in dry-run" },
|
|
95
|
+
{ flags: "--no-preview", description: "Skip the file preview" },
|
|
96
|
+
{
|
|
97
|
+
flags: "--no-generated-stamp",
|
|
98
|
+
description: "Disable generated file stamp comments",
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
flags: "-l, --llm",
|
|
102
|
+
description: "Dry-run with markdown output, no prompts, no stamps",
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
flags: "--format <type>",
|
|
106
|
+
description: "Output format: json (dry-run, no prompts, no stamps)",
|
|
107
|
+
},
|
|
108
|
+
{ flags: "-h, --help", description: "display help for command" },
|
|
109
|
+
];
|
|
110
|
+
|
|
111
|
+
// =============================================================================
|
|
112
|
+
// The summon action
|
|
113
|
+
// =============================================================================
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Generate the batch task, validating the SUCCESS path: `--generators` loads
|
|
117
|
+
* unchecked JS, so a `generate()` that forgot its `return` hands back
|
|
118
|
+
* undefined — named here as the same generator-bug class a throwing
|
|
119
|
+
* `generate` is (the action's catch renders the bare line, exit 1), instead
|
|
120
|
+
* of the interpreter's incidental TypeError
|
|
121
|
+
* (`undefined is not an object (evaluating 'cur._tag')`). The App's
|
|
122
|
+
* `generateTask` holds the run/wizard arms to the same message.
|
|
123
|
+
*/
|
|
124
|
+
function generateBatchTask(
|
|
125
|
+
generator: GeneratorDefinition,
|
|
126
|
+
answersWithDefaults: Record<string, unknown>,
|
|
127
|
+
): Task<void> {
|
|
128
|
+
const task: Task<void> | undefined | null =
|
|
129
|
+
generator.generate(answersWithDefaults);
|
|
130
|
+
if (task === undefined || task === null) {
|
|
131
|
+
throw new Error(`${generator.meta.name}'s generate returned no task`);
|
|
132
|
+
}
|
|
133
|
+
return task;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Run the batch (non-interactive) undo path. */
|
|
137
|
+
async function runBatchUndo(
|
|
138
|
+
generator: GeneratorDefinition,
|
|
139
|
+
answersWithDefaults: Record<string, unknown>,
|
|
140
|
+
dryRunOnly: boolean,
|
|
141
|
+
): Promise<void> {
|
|
142
|
+
const task = generateBatchTask(generator, answersWithDefaults);
|
|
143
|
+
try {
|
|
144
|
+
const unreversible: Effect[] = [];
|
|
145
|
+
const undos = collectUndos(task, {
|
|
146
|
+
resolveExists: hostExistsResolver(),
|
|
147
|
+
onForwardEffect: (effect) => {
|
|
148
|
+
if (isUnreversibleExec(effect)) unreversible.push(effect);
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
if (undos.length === 0) {
|
|
152
|
+
console.log("Nothing to undo.");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const planLines = describeUndoSteps(undos).map((effect) =>
|
|
156
|
+
effect._tag === "Log" ? effect.message : describeEffect(effect),
|
|
157
|
+
);
|
|
158
|
+
// Diagnostics go to stderr so stdout stays a clean data stream.
|
|
159
|
+
process.stderr.write(
|
|
160
|
+
`Undo will reverse ${undos.length} step${undos.length === 1 ? "" : "s"}:\n${planLines.map((line) => ` - ${line}`).join("\n")}\n`,
|
|
161
|
+
);
|
|
162
|
+
if (dryRunOnly) {
|
|
163
|
+
console.log("Dry-run complete. Nothing was reversed.");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const result = await runCollectedUndos(undos);
|
|
167
|
+
// A failed undo no longer aborts the ones still pending — every step is
|
|
168
|
+
// attempted and reported in `outcomes` — so the aggregate verdict is
|
|
169
|
+
// decided HERE, from the outcomes. Printing "Undo complete" over a
|
|
170
|
+
// partial reversal would claim work that did not happen.
|
|
171
|
+
const failed = result.outcomes.filter((o) => o.status === "failed");
|
|
172
|
+
if (failed.length > 0) {
|
|
173
|
+
process.stderr.write(
|
|
174
|
+
`${failed.length} step${failed.length === 1 ? "" : "s"} could not be reversed:\n${failed
|
|
175
|
+
.map((o) => ` - ${o.error.message}`)
|
|
176
|
+
.join("\n")}\n`,
|
|
177
|
+
);
|
|
178
|
+
console.error(
|
|
179
|
+
`Undo incomplete (${result.undoCount} of ${result.outcomes.length} step${result.outcomes.length === 1 ? "" : "s"} reversed).`,
|
|
180
|
+
);
|
|
181
|
+
process.exitCode = 1;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
console.log(
|
|
185
|
+
`Undo complete (${result.undoCount} step${result.undoCount === 1 ? "" : "s"} reversed).`,
|
|
186
|
+
);
|
|
187
|
+
if (unreversible.length > 0) {
|
|
188
|
+
process.stderr.write(
|
|
189
|
+
`Note: ${unreversible.length} exec step${unreversible.length === 1 ? "" : "s"} were not reversed (e.g. installs); their artifacts may remain.\n`,
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
} catch (err) {
|
|
193
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
194
|
+
console.error(`Undo failed: ${message}`);
|
|
195
|
+
process.exitCode = 1;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Render the batch (non-interactive) dry-run in plain, llm, or json form. */
|
|
200
|
+
function runBatchDryRun(
|
|
201
|
+
generator: GeneratorDefinition,
|
|
202
|
+
answersWithDefaults: Record<string, unknown>,
|
|
203
|
+
actualOptions: Record<string, unknown>,
|
|
204
|
+
): void {
|
|
205
|
+
const verbose = actualOptions.verbose === true;
|
|
206
|
+
const showFiles = actualOptions.showFiles === true;
|
|
207
|
+
|
|
208
|
+
const task = generateBatchTask(generator, answersWithDefaults);
|
|
209
|
+
const result = dryRun(task);
|
|
210
|
+
|
|
211
|
+
if (actualOptions.llm === true) {
|
|
212
|
+
const output = formatLlmMarkdown(
|
|
213
|
+
generator,
|
|
214
|
+
answersWithDefaults,
|
|
215
|
+
result.effects,
|
|
216
|
+
verbose,
|
|
217
|
+
);
|
|
218
|
+
process.stdout.write(output);
|
|
219
|
+
} else if (actualOptions.format === "json") {
|
|
220
|
+
const output = formatLlmJson(
|
|
221
|
+
generator,
|
|
222
|
+
answersWithDefaults,
|
|
223
|
+
result.effects,
|
|
224
|
+
verbose,
|
|
225
|
+
);
|
|
226
|
+
process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
|
|
227
|
+
} else {
|
|
228
|
+
console.log();
|
|
229
|
+
console.log(chalk.bold.magenta(generator.meta.name));
|
|
230
|
+
console.log(chalk.dim(generator.meta.description));
|
|
231
|
+
console.log();
|
|
232
|
+
|
|
233
|
+
// The visibility filter AND the MakeDir de-duplication are ONE rule with
|
|
234
|
+
// several readers — this bin's dry-run, summon-core's own `--llm` / JSON
|
|
235
|
+
// projections, and the pragma kernel's CLI and MCP previews. This is the
|
|
236
|
+
// REFERENCE renderer the others are required to agree with, so it consumes
|
|
237
|
+
// the shared rule rather than carrying the copy it used to.
|
|
238
|
+
const visibleEffects = visiblePlanEffects(result.effects, verbose);
|
|
239
|
+
|
|
240
|
+
console.log(chalk.dim.bold("Plan:"));
|
|
241
|
+
visibleEffects.forEach((effect, index) => {
|
|
242
|
+
const isLast = index === visibleEffects.length - 1;
|
|
243
|
+
if (showFiles) {
|
|
244
|
+
console.log(formatEffectWithContent(effect, isLast));
|
|
245
|
+
} else {
|
|
246
|
+
console.log(formatEffectLine(effect, isLast));
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
console.log();
|
|
251
|
+
console.log(chalk.dim("Dry-run complete. No files were modified."));
|
|
252
|
+
|
|
253
|
+
if (!showFiles) {
|
|
254
|
+
console.log(
|
|
255
|
+
chalk.dim("Tip: Use --show-files to see generated file contents"),
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The summon action body for one generator invocation. */
|
|
262
|
+
async function runGeneratorAction(
|
|
263
|
+
entry: CommandEntry,
|
|
264
|
+
positionalValue: string | undefined,
|
|
265
|
+
actualOptions: Record<string, unknown>,
|
|
266
|
+
): Promise<void> {
|
|
267
|
+
const generator = entry.generator;
|
|
268
|
+
/* v8 ignore next -- the projection calls the action only for generator entries. */
|
|
269
|
+
if (!generator) return;
|
|
270
|
+
|
|
271
|
+
// Support SUMMON_LLM=1 environment variable
|
|
272
|
+
if (process.env.SUMMON_LLM === "1" && actualOptions.llm !== true) {
|
|
273
|
+
actualOptions.llm = true;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Expand --llm flag into its component flags
|
|
277
|
+
if (actualOptions.llm === true) {
|
|
278
|
+
actualOptions.dryRun = true;
|
|
279
|
+
actualOptions.showFiles = true;
|
|
280
|
+
actualOptions.yes = true;
|
|
281
|
+
actualOptions.generatedStamp = false;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Expand --format json into its component flags
|
|
285
|
+
if (actualOptions.format === "json") {
|
|
286
|
+
actualOptions.dryRun = true;
|
|
287
|
+
actualOptions.showFiles = true;
|
|
288
|
+
actualOptions.yes = true;
|
|
289
|
+
actualOptions.generatedStamp = false;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Extract only explicitly provided CLI answers (not defaults)
|
|
293
|
+
const cliAnswers = extractAnswers(actualOptions, generator.prompts);
|
|
294
|
+
|
|
295
|
+
// If the positional argument was provided, add it to the answers
|
|
296
|
+
const positionalPrompt = generator.prompts.find((p) => p.positional);
|
|
297
|
+
if (positionalPrompt && positionalValue !== undefined) {
|
|
298
|
+
cliAnswers[positionalPrompt.name] = positionalValue;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Apply defaults once — the batch and run modes consume these.
|
|
302
|
+
const answersWithDefaults = applyDefaults(generator.prompts, cliAnswers);
|
|
303
|
+
|
|
304
|
+
// The ONE interaction decision (R2), shared verbatim with pragma, resolved
|
|
305
|
+
// through the testable seam (`resolveMode.ts`) with summon's TTY fact:
|
|
306
|
+
// stdin AND stdout are TTYs (the wizard renders to stdout).
|
|
307
|
+
const mode = resolveSummonMode(
|
|
308
|
+
generator.prompts,
|
|
309
|
+
actualOptions,
|
|
310
|
+
cliAnswers,
|
|
311
|
+
summonIsTTY(),
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
if (mode === "refuse") {
|
|
315
|
+
process.stderr.write(
|
|
316
|
+
`${refusalMessage(missingExplicitFlags(generator.prompts, cliAnswers))}\n`,
|
|
317
|
+
);
|
|
318
|
+
process.exitCode = 2;
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// An invalid EXPLICIT answer fails loudly before any UI or write — run and
|
|
323
|
+
// wizard arms included (previously only the batch arms checked, so `--yes`
|
|
324
|
+
// scaffolded a tree carrying the invalid value) — but AFTER the refuse
|
|
325
|
+
// arm: pragma's mount decides (and refuses) before its create runtime
|
|
326
|
+
// loads, so refuse must win over invalid input in BOTH hosts
|
|
327
|
+
// (the cross-CLI matrix). The batch arms re-check the defaults-applied set
|
|
328
|
+
// below (an invalid generator DEFAULT stays loud).
|
|
329
|
+
if (!failLoudInvalidAnswers(generator, cliAnswers)) return;
|
|
330
|
+
|
|
331
|
+
// Build stamp config if stamps are enabled (default: enabled)
|
|
332
|
+
const stampEnabled = actualOptions.generatedStamp !== false;
|
|
333
|
+
const stamp: StampConfig | undefined = stampEnabled
|
|
334
|
+
? createGeneratorStamp(generator)
|
|
335
|
+
: undefined;
|
|
336
|
+
|
|
337
|
+
// The batch modes run regardless of TTY, on defaults — but never on a
|
|
338
|
+
// missing or invalid answer: they error loudly (exit 2) where the previous
|
|
339
|
+
// decision block silently fell through to Ink.
|
|
340
|
+
if (mode === "batch-undo" || mode === "batch-dry-run") {
|
|
341
|
+
if (!failLoudBatchInput(generator, answersWithDefaults)) return;
|
|
342
|
+
try {
|
|
343
|
+
if (mode === "batch-undo") {
|
|
344
|
+
await runBatchUndo(
|
|
345
|
+
generator,
|
|
346
|
+
answersWithDefaults,
|
|
347
|
+
actualOptions.dryRun === true,
|
|
348
|
+
);
|
|
349
|
+
} else {
|
|
350
|
+
runBatchDryRun(generator, answersWithDefaults, actualOptions);
|
|
351
|
+
}
|
|
352
|
+
} catch (error) {
|
|
353
|
+
// A generator-raised typed invalid answer (a cross-answer constraint
|
|
354
|
+
// its `generate` enforces — two answers only valid together; no
|
|
355
|
+
// shipped generator raises one today)
|
|
356
|
+
// fails exactly like `validateAnswers` above: the bare message on
|
|
357
|
+
// stderr, exit 2. Any OTHER throw is a generator bug — still the bare
|
|
358
|
+
// message line, with the runtime class (exit 1), per §3's batch
|
|
359
|
+
// clause. Re-throwing (the old behavior) escaped the un-awaited async
|
|
360
|
+
// action as an unhandled rejection: a 1.2 KB source-frame stack
|
|
361
|
+
// instead of a line, and an exit code owned by the runtime, not the
|
|
362
|
+
// classification.
|
|
363
|
+
if (isInvalidAnswersError(error)) {
|
|
364
|
+
process.stderr.write(`${error.message}\n`);
|
|
365
|
+
process.exitCode = 2;
|
|
366
|
+
} else {
|
|
367
|
+
process.stderr.write(
|
|
368
|
+
`${error instanceof Error ? error.message : String(error)}\n`,
|
|
369
|
+
);
|
|
370
|
+
process.exitCode = 1;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (mode === "run") {
|
|
377
|
+
// A fully-determined run: defaults applied, no wizard, no preview gate
|
|
378
|
+
// (the confirm auto-resolves).
|
|
379
|
+
const { waitUntilExit } = render(
|
|
380
|
+
<App
|
|
381
|
+
generator={generator}
|
|
382
|
+
preview={false}
|
|
383
|
+
dryRunOnly={false}
|
|
384
|
+
undo={false}
|
|
385
|
+
verbose={actualOptions.verbose as boolean}
|
|
386
|
+
answers={answersWithDefaults}
|
|
387
|
+
stamp={stamp}
|
|
388
|
+
/>,
|
|
389
|
+
);
|
|
390
|
+
await waitUntilExit();
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// mode === "wizard": ask exactly pendingPrompts(prompts, explicit) — the
|
|
395
|
+
// contract's shared fact. Summon's PRESENTATION (host prose, not parity
|
|
396
|
+
// surface): the provided answers are pre-seeded and shown in the completed
|
|
397
|
+
// table, the step total counts only the pending prompts, and esc at the
|
|
398
|
+
// confirm gate goes BACK instead of cancelling.
|
|
399
|
+
const { waitUntilExit } = render(
|
|
400
|
+
<App
|
|
401
|
+
generator={generator}
|
|
402
|
+
preview={actualOptions.preview as boolean}
|
|
403
|
+
dryRunOnly={false}
|
|
404
|
+
undo={false}
|
|
405
|
+
verbose={actualOptions.verbose as boolean}
|
|
406
|
+
answers={cliAnswers}
|
|
407
|
+
askMissing
|
|
408
|
+
stamp={stamp}
|
|
409
|
+
/>,
|
|
410
|
+
);
|
|
411
|
+
await waitUntilExit();
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Fail loudly (stderr + exit 2) when an answer in `answers` fails its
|
|
416
|
+
* prompt's own constraint. The ONE invalid-answer rendering: the action runs
|
|
417
|
+
* it over the EXPLICIT answers downstream of the refuse arm (refuse wins,
|
|
418
|
+
* exactly as pragma's mount refuses before its runtime validates) and
|
|
419
|
+
* before any other arm runs, and {@link failLoudBatchInput} runs it again
|
|
420
|
+
* over the defaults-applied set. Returns true when the answers pass.
|
|
421
|
+
*/
|
|
422
|
+
function failLoudInvalidAnswers(
|
|
423
|
+
generator: GeneratorDefinition,
|
|
424
|
+
answers: Record<string, unknown>,
|
|
425
|
+
): boolean {
|
|
426
|
+
const invalid = validateAnswers(generator.prompts, answers);
|
|
427
|
+
if (invalid === null) return true;
|
|
428
|
+
process.stderr.write(`${invalid}\n`);
|
|
429
|
+
process.exitCode = 2;
|
|
430
|
+
return false;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Fail loudly (stderr + exit 2) when a batch mode's answer set is unusable: a
|
|
435
|
+
* required answer has no value even after defaults, or a provided answer fails
|
|
436
|
+
* its prompt's own constraint. Returns true when the batch may proceed.
|
|
437
|
+
*/
|
|
438
|
+
function failLoudBatchInput(
|
|
439
|
+
generator: GeneratorDefinition,
|
|
440
|
+
answersWithDefaults: Record<string, unknown>,
|
|
441
|
+
): boolean {
|
|
442
|
+
if (!hasAllRequiredAnswers(generator.prompts, answersWithDefaults)) {
|
|
443
|
+
const missing = generator.prompts.find(
|
|
444
|
+
(prompt) =>
|
|
445
|
+
!prompt.when &&
|
|
446
|
+
prompt.default === undefined &&
|
|
447
|
+
!(prompt.name in answersWithDefaults),
|
|
448
|
+
);
|
|
449
|
+
/* v8 ignore next -- hasAllRequiredAnswers false implies a missing prompt. */
|
|
450
|
+
if (missing) {
|
|
451
|
+
const effect = {
|
|
452
|
+
_tag: "Prompt",
|
|
453
|
+
question: {
|
|
454
|
+
type: "text",
|
|
455
|
+
name: missing.name,
|
|
456
|
+
message: missing.message,
|
|
457
|
+
},
|
|
458
|
+
} as PromptEffect;
|
|
459
|
+
process.stderr.write(`${missingRequiredError(effect, "flag").message}\n`);
|
|
460
|
+
}
|
|
461
|
+
process.exitCode = 2;
|
|
462
|
+
return false;
|
|
463
|
+
}
|
|
464
|
+
return failLoudInvalidAnswers(generator, answersWithDefaults);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** The summon host handed to the shared registration path. */
|
|
468
|
+
const summonHost: CommanderHost = {
|
|
469
|
+
registerFlags: registerStandardFlags,
|
|
470
|
+
helpFlags: STANDARD_FLAG_HELP,
|
|
471
|
+
action: (entry, positionalValue, options) =>
|
|
472
|
+
runGeneratorAction(entry, positionalValue, options),
|
|
473
|
+
// Summon's host spelling (the cross-CLI matrix): Commander's implicit
|
|
474
|
+
// `help` subcommand stays available on namespaces (`summon component
|
|
475
|
+
// help`, the `help [command]` row in the namespace help page). The
|
|
476
|
+
// projection's namespace action would otherwise suppress Commander's
|
|
477
|
+
// implicit default — and pragma deliberately does not declare it.
|
|
478
|
+
onNamespace: (cmd) => {
|
|
479
|
+
cmd.helpCommand(true);
|
|
480
|
+
},
|
|
481
|
+
// The projection's designed outcomes (usage errors, bare-namespace help)
|
|
482
|
+
// take the default presentation: the parity bytes on stderr, the
|
|
483
|
+
// outcome's exit code — the one shared process effect.
|
|
484
|
+
emit: emitToProcess,
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
// =============================================================================
|
|
488
|
+
// Public API
|
|
489
|
+
// =============================================================================
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Register all commands from a command barrel onto a Commander program.
|
|
493
|
+
*
|
|
494
|
+
* @note Impure — mutates the Commander program.
|
|
495
|
+
*/
|
|
496
|
+
export default function registerFromBarrel(
|
|
497
|
+
rootCmd: Command,
|
|
498
|
+
barrel: CommandEntry[],
|
|
499
|
+
): void {
|
|
500
|
+
registerGeneratorCommands(rootCmd, barrel, summonHost);
|
|
501
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The TTY rows of the interaction table, driven through the host seam with
|
|
3
|
+
* `tty: true` — the cells no subprocess test can reach (pipes are never
|
|
4
|
+
* TTYs). §L items 4a/4b live here: TTY `--dry-run` renders the batch plan
|
|
5
|
+
* and TTY `--undo` runs batch undo (the OLD decision block sent both to
|
|
6
|
+
* Ink), and a TTY with partial flags asks the missing prompts. The
|
|
7
|
+
* `summonIsTTY` expression itself (stdin AND STDOUT — the cross-CLI matrix) is
|
|
8
|
+
* pinned against patched streams.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { PromptLike } from "@canonical/summon-core/projection";
|
|
12
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
13
|
+
import { resolveSummonMode, summonIsTTY } from "./resolveMode.js";
|
|
14
|
+
|
|
15
|
+
const prompts: readonly PromptLike[] = [
|
|
16
|
+
{
|
|
17
|
+
name: "componentPath",
|
|
18
|
+
type: "text",
|
|
19
|
+
message: "Component path:",
|
|
20
|
+
default: "src/components/MyComponent",
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: "withStyles",
|
|
24
|
+
type: "confirm",
|
|
25
|
+
message: "Include styles?",
|
|
26
|
+
default: true,
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const options = (
|
|
31
|
+
dryRun: boolean,
|
|
32
|
+
undo: boolean,
|
|
33
|
+
yes: boolean,
|
|
34
|
+
): Record<string, unknown> => ({ dryRun, undo, yes });
|
|
35
|
+
|
|
36
|
+
describe("resolveSummonMode — the TTY-injected decision seam", () => {
|
|
37
|
+
it("TTY --dry-run is batch-dry-run, never an Ink preview (§L item 4a)", () => {
|
|
38
|
+
expect(
|
|
39
|
+
resolveSummonMode(prompts, options(true, false, false), {}, true),
|
|
40
|
+
).toBe("batch-dry-run");
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("TTY --undo is batch-undo, never a prompting App (§L item 4b)", () => {
|
|
44
|
+
expect(
|
|
45
|
+
resolveSummonMode(prompts, options(false, true, false), {}, true),
|
|
46
|
+
).toBe("batch-undo");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("TTY --dry-run outranks --undo (the shared precedence)", () => {
|
|
50
|
+
expect(
|
|
51
|
+
resolveSummonMode(prompts, options(true, true, false), {}, true),
|
|
52
|
+
).toBe("batch-dry-run");
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("a TTY with partial flags is a wizard (asks the missing prompts, §L item 5)", () => {
|
|
56
|
+
expect(
|
|
57
|
+
resolveSummonMode(
|
|
58
|
+
prompts,
|
|
59
|
+
options(false, false, false),
|
|
60
|
+
{ withStyles: false },
|
|
61
|
+
true,
|
|
62
|
+
),
|
|
63
|
+
).toBe("wizard");
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("the same partial input without a TTY refuses; complete input runs", () => {
|
|
67
|
+
expect(
|
|
68
|
+
resolveSummonMode(
|
|
69
|
+
prompts,
|
|
70
|
+
options(false, false, false),
|
|
71
|
+
{ withStyles: false },
|
|
72
|
+
false,
|
|
73
|
+
),
|
|
74
|
+
).toBe("refuse");
|
|
75
|
+
expect(
|
|
76
|
+
resolveSummonMode(
|
|
77
|
+
prompts,
|
|
78
|
+
options(false, false, false),
|
|
79
|
+
{ componentPath: "src/components/X", withStyles: false },
|
|
80
|
+
false,
|
|
81
|
+
),
|
|
82
|
+
).toBe("run");
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe("summonIsTTY — stdin AND stdout (the wizard renders to stdout)", () => {
|
|
87
|
+
const setTTY = (
|
|
88
|
+
stream: NodeJS.ReadStream | NodeJS.WriteStream,
|
|
89
|
+
value: boolean | undefined,
|
|
90
|
+
): void => {
|
|
91
|
+
(stream as { isTTY?: boolean }).isTTY = value;
|
|
92
|
+
};
|
|
93
|
+
const savedIn = process.stdin.isTTY;
|
|
94
|
+
const savedOut = process.stdout.isTTY;
|
|
95
|
+
const savedErr = process.stderr.isTTY;
|
|
96
|
+
|
|
97
|
+
afterEach(() => {
|
|
98
|
+
setTTY(process.stdin, savedIn);
|
|
99
|
+
setTTY(process.stdout, savedOut);
|
|
100
|
+
setTTY(process.stderr, savedErr);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("requires both streams; stderr is irrelevant (pragma's gate differs, deliberately)", () => {
|
|
104
|
+
const cases: Array<[boolean, boolean, boolean, boolean]> = [
|
|
105
|
+
[true, true, false, true], // stderr is irrelevant…
|
|
106
|
+
[true, true, true, true],
|
|
107
|
+
[false, true, true, false], // …stdin is required…
|
|
108
|
+
[true, false, true, false], // …and so is stdout.
|
|
109
|
+
[false, false, false, false],
|
|
110
|
+
];
|
|
111
|
+
for (const [stdin, stdout, stderr, expected] of cases) {
|
|
112
|
+
setTTY(process.stdin, stdin);
|
|
113
|
+
setTTY(process.stdout, stdout);
|
|
114
|
+
setTTY(process.stderr, stderr);
|
|
115
|
+
expect(summonIsTTY(), `stdin=${stdin} stdout=${stdout}`).toBe(expected);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The summon host's mode resolution — `decideInteraction` over the five
|
|
3
|
+
* inputs, with the TTY fact INJECTED so the resolution is testable with
|
|
4
|
+
* `tty: true` (no suite can hand a subprocess a real TTY). The action calls
|
|
5
|
+
* {@link resolveSummonMode} with {@link summonIsTTY}; the tests drive it with
|
|
6
|
+
* a literal, pinning the §L rows that only exist on a TTY (dry-run/undo stay
|
|
7
|
+
* batch, partial flags become a wizard).
|
|
8
|
+
*
|
|
9
|
+
* Deliberately UI-free (projection-only imports), so the seam itself never
|
|
10
|
+
* pulls Ink into a test that only asserts the decision.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
decideInteraction,
|
|
15
|
+
explicitAnswersComplete,
|
|
16
|
+
type InteractionMode,
|
|
17
|
+
type PromptLike,
|
|
18
|
+
} from "@canonical/summon-core/projection";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Summon's TTY fact (the cross-CLI matrix): stdin AND stdout are TTYs — the
|
|
22
|
+
* wizard renders to stdout, so a piped stdout must be non-interactive.
|
|
23
|
+
*
|
|
24
|
+
* @returns True when both streams are TTYs.
|
|
25
|
+
*/
|
|
26
|
+
export function summonIsTTY(): boolean {
|
|
27
|
+
return process.stdin.isTTY === true && process.stdout.isTTY === true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Resolve the interaction mode for one generator invocation.
|
|
32
|
+
*
|
|
33
|
+
* @param prompts - The generator's prompts.
|
|
34
|
+
* @param options - The parsed options AFTER the llm/json expansions.
|
|
35
|
+
* @param explicit - The explicitly provided answers (flags + positional).
|
|
36
|
+
* @param tty - The host TTY fact (the action passes {@link summonIsTTY}).
|
|
37
|
+
* @returns The mode the action routes on.
|
|
38
|
+
*/
|
|
39
|
+
export function resolveSummonMode(
|
|
40
|
+
prompts: readonly PromptLike[],
|
|
41
|
+
options: Record<string, unknown>,
|
|
42
|
+
explicit: Record<string, unknown>,
|
|
43
|
+
tty: boolean,
|
|
44
|
+
): InteractionMode {
|
|
45
|
+
return decideInteraction({
|
|
46
|
+
dryRun: options.dryRun === true,
|
|
47
|
+
undo: options.undo === true,
|
|
48
|
+
yes: options.yes === true,
|
|
49
|
+
isTTY: tty,
|
|
50
|
+
explicitComplete: explicitAnswersComplete(prompts, explicit),
|
|
51
|
+
}).mode;
|
|
52
|
+
}
|