-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.ts
More file actions
365 lines (327 loc) · 9.48 KB
/
list.ts
File metadata and controls
365 lines (327 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/**
* Implementation of the `probitas list` command
*
* @module
*/
import { parseArgs } from "@std/cli";
import { resolve } from "@std/path";
import { getLogger, type LogLevel } from "@logtape/logtape";
import { discoverScenarioFiles } from "@probitas/discover";
import { fromErrorObject, isErrorObject } from "@core/errorutil/error-object";
import { unreachable } from "@core/errorutil/unreachable";
import { EXIT_CODE } from "../constants.ts";
import { findProbitasConfigFile, loadConfig } from "../config.ts";
import {
createUnknownArgHandler,
extractKnownOptions,
formatUnknownArgError,
} from "../unknown_args.ts";
import { createDiscoveryProgress, writeStatus } from "../progress.ts";
import {
configureLogging,
extractDenoOptions,
loadEnvironment,
readAsset,
} from "../utils.ts";
import { runSubprocessToCompletion } from "../subprocess.ts";
import {
isListOutput,
type ListInput,
type ListOutput,
type ScenarioMeta,
} from "../_templates/list_protocol.ts";
const logger = getLogger(["probitas", "cli", "list"]);
/**
* parseArgs configuration for the list command
*/
const PARSE_ARGS_CONFIG = {
string: ["config", "include", "exclude", "selector", "env"],
boolean: [
"help",
"json",
"no-env",
"reload",
"quiet",
"verbose",
"debug",
],
collect: ["include", "exclude", "selector"],
alias: {
h: "help",
s: "selector",
r: "reload",
v: "verbose",
q: "quiet",
d: "debug",
},
default: {
include: undefined,
exclude: undefined,
selector: undefined,
},
} as const;
/**
* Execute the list command
*
* @param args - Command-line arguments
* @param cwd - Current working directory
* @returns Exit code (0 = success, 2 = usage error)
*
* @requires --allow-read Permission to read config and scenario files
*/
export async function listCommand(
args: string[],
cwd: string,
): Promise<number> {
try {
// Extract deno options first (before parseArgs)
const { denoArgs, remainingArgs } = extractDenoOptions(args);
// Setup unknown argument handler
const knownOptions = extractKnownOptions(PARSE_ARGS_CONFIG);
const { handler: unknownHandler, result: unknownResult } =
createUnknownArgHandler({
knownOptions,
commandName: "list",
});
// Parse command-line arguments
const parsed = parseArgs(remainingArgs, {
...PARSE_ARGS_CONFIG,
unknown: unknownHandler,
});
// Check for unknown arguments before showing help
if (unknownResult.hasErrors) {
for (const unknown of unknownResult.unknownArgs) {
console.error(
formatUnknownArgError(unknown, {
knownOptions,
commandName: "list",
}),
);
}
return EXIT_CODE.USAGE_ERROR;
}
// Show help if requested
if (parsed.help) {
try {
const helpText = await readAsset("usage-list.txt");
console.log(helpText);
return EXIT_CODE.SUCCESS;
} catch (error) {
// Use console.error here since logging is not yet configured
console.error(
"Error reading help file:",
error instanceof Error ? error.message : String(error),
);
return EXIT_CODE.USAGE_ERROR;
}
}
// Determine log level
const logLevel: LogLevel = parsed.debug
? "debug"
: parsed.verbose
? "info"
: parsed.quiet
? "fatal"
: "warning";
// Configure logging with determined log level
try {
await configureLogging(logLevel);
} catch {
// Silently ignore logging configuration errors (e.g., in test environments)
}
// Add --reload to denoArgs if -r/--reload is specified
const finalDenoArgs = parsed.reload ? [...denoArgs, "--reload"] : denoArgs;
logger.debug("List command started", {
args,
cwd,
logLevel,
denoArgs: finalDenoArgs,
});
// Load environment variables before loading configuration
// This allows config files to reference environment variables
await loadEnvironment(cwd, {
noEnv: parsed["no-env"],
envFile: parsed.env,
});
// Load configuration
const configPath = parsed.config ??
await findProbitasConfigFile(cwd, { parentLookup: true });
const config = configPath ? await loadConfig(configPath) : {};
// Determine includes/excludes: CLI > config
const includes = parsed.include ?? config?.includes;
const excludes = parsed.exclude ?? config?.excludes;
// Discover scenario files
const paths = parsed
._
.map(String)
.map((p) => resolve(cwd, p));
// Show progress during discovery (only in TTY, suppressed in quiet mode)
const discoveryProgress = parsed.quiet ? null : createDiscoveryProgress();
const scenarioFiles = await discoverScenarioFiles(
paths.length ? paths : [cwd],
{
includes,
excludes,
onProgress: discoveryProgress?.onProgress,
},
);
discoveryProgress?.complete(scenarioFiles.length);
logger.info("Discovered scenario files", {
count: scenarioFiles.length,
files: scenarioFiles,
});
// Build selectors
const selectors = parsed.selector ?? config?.selectors ?? [];
// Handle empty files case
if (scenarioFiles.length === 0) {
logger.debug("No files specified, returning empty list");
if (parsed.json) {
console.log("[]");
} else {
console.log("\nTotal: 0 scenarios in 0 files");
}
return EXIT_CODE.SUCCESS;
}
// Load scenarios via subprocess
// Show status during loading (only in TTY, suppressed in quiet mode)
logger.info("Loading scenarios via subprocess", {
fileCount: scenarioFiles.length,
});
const clearLoadingStatus = parsed.quiet
? null
: writeStatus(`Loading scenarios (${scenarioFiles.length} files)...`);
const { allScenarios, filteredScenarios } = await runListSubprocess(
scenarioFiles,
selectors,
finalDenoArgs,
cwd,
);
clearLoadingStatus?.();
logger.debug("Scenarios loaded", { scenarioCount: allScenarios.length });
if (selectors && selectors.length > 0) {
logger.debug("Applied selectors", {
selectors,
filteredCount: filteredScenarios.length,
});
}
// Output results
if (parsed.json) {
outputJson(filteredScenarios);
} else {
outputText(allScenarios, filteredScenarios);
}
logger.info("List completed", {
totalScenarios: allScenarios.length,
filteredScenarios: filteredScenarios.length,
});
return EXIT_CODE.SUCCESS;
} catch (err: unknown) {
const m = err instanceof Error ? err.message : String(err);
logger.error("Unexpected error in list command", { error: err });
console.error(`Error: ${m}`);
return EXIT_CODE.FAILURE;
}
}
/**
* Run list subprocess to load scenarios
*/
async function runListSubprocess(
filePaths: readonly string[],
selectors: readonly string[],
denoArgs: string[],
cwd: string,
): Promise<{
allScenarios: ScenarioMeta[];
filteredScenarios: ScenarioMeta[];
}> {
return await runSubprocessToCompletion<
ListInput,
ListOutput,
{ allScenarios: ScenarioMeta[]; filteredScenarios: ScenarioMeta[] }
>(
{
templateUrl: new URL("../_templates/list.ts", import.meta.url),
templateName: "list",
input: { filePaths, selectors },
denoArgs,
cwd,
},
isListOutput,
(output) => Promise.resolve(handleSubprocessOutput(output)),
);
}
/**
* Handle subprocess output message
*/
function handleSubprocessOutput(
output: ListOutput,
): { allScenarios: ScenarioMeta[]; filteredScenarios: ScenarioMeta[] } | void {
switch (output.type) {
case "result":
// The subprocess has already applied any selector filtering, so
// `output.scenarios` contains only scenarios that passed filtering.
// Both allScenarios and filteredScenarios refer to this filtered set.
// TODO: Consider returning unfiltered list from subprocess if needed.
return {
allScenarios: [...output.scenarios],
filteredScenarios: [...output.scenarios],
};
case "error": {
const error = isErrorObject(output.error)
? fromErrorObject(output.error)
: new Error(String(output.error));
throw error;
}
default:
unreachable(output);
}
}
/**
* Output scenarios in text format
*/
function outputText(
allScenarios: ScenarioMeta[],
filteredScenarios: ScenarioMeta[],
): void {
// Group scenarios by file
const byFile = new Map<string, ScenarioMeta[]>();
for (const scenario of allScenarios) {
const file = scenario.file;
if (!byFile.has(file)) {
byFile.set(file, []);
}
byFile.get(file)!.push(scenario);
}
// Output grouped scenarios
let outputCount = 0;
for (const [file, scenariosInFile] of byFile) {
console.log(file);
for (const scenario of scenariosInFile) {
if (
filteredScenarios.some((s) =>
s.name === scenario.name && s.file === scenario.file
)
) {
console.log(` ${scenario.name}`);
outputCount++;
}
}
}
console.log(
`\nTotal: ${outputCount} scenario${
outputCount === 1 ? "" : "s"
} in ${byFile.size} file${byFile.size === 1 ? "" : "s"}`,
);
}
/**
* Output scenarios in JSON format
*/
function outputJson(scenarios: ScenarioMeta[]): void {
const output = scenarios.map((scenario) => ({
name: scenario.name,
tags: scenario.tags,
steps: scenario.steps,
file: scenario.file,
}));
console.log(JSON.stringify(output, null, 2));
}