-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathwrap-command.ts
More file actions
80 lines (76 loc) · 2.46 KB
/
Copy pathwrap-command.ts
File metadata and controls
80 lines (76 loc) · 2.46 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
import { Command } from "commander";
import { CLIError } from "../types/json-output.js";
import { formatError } from "../utils/error.js";
import {
ConsoleLogger,
fallbackLogger,
JsonLogger,
Logger,
warnOnConflictingFlags,
} from "../utils/logger.js";
export function createLogger({
name,
globalOpts,
getVersion,
}: {
name: string;
globalOpts: Record<string, unknown>;
getVersion: () => string;
}): Logger {
return globalOpts.json
? new JsonLogger({ command: name, version: getVersion() })
: new ConsoleLogger();
}
export function wrapCommand({
name,
errorCode,
handler,
getVersion,
loggerFactory = createLogger,
}: {
name: string;
errorCode: string;
handler: (
logger: Logger,
options: unknown,
globalOpts: Record<string, unknown>,
positionalArgs: unknown[],
) => Promise<void>;
getVersion: () => string;
loggerFactory?: (params: {
name: string;
globalOpts: Record<string, unknown>;
getVersion: () => string;
}) => Logger;
}) {
return async (...args: unknown[]) => {
// Commander passes variable args based on command signature:
// - No positional: (options, command)
// - With positional: (arg1, arg2, ..., options, command)
// The last two are always (options, command)
const command = args[args.length - 1] as Command;
const options = args[args.length - 2] as Record<string, unknown>;
const positionalArgs = args.slice(0, -2);
const globalOpts = command.parent?.opts() ?? {};
const logger = loggerFactory({ name, globalOpts, getVersion });
// Configure from CLI flags first; commands that resolve a config file
// re-configure via `ConfigResolver.resolve` so config-file
// `verbose`/`silent` also apply (CLI flags still win there).
const cliLoggerOptions = {
verbose: Boolean(globalOpts.verbose) || Boolean(options.verbose),
silent: Boolean(globalOpts.silent) || Boolean(options.silent),
};
warnOnConflictingFlags({ ...cliLoggerOptions, jsonMode: logger.jsonMode });
logger.configure(cliLoggerOptions);
fallbackLogger.configure(cliLoggerOptions);
try {
await handler(logger, options, globalOpts, positionalArgs);
logger.outputJson(true);
} catch (error) {
const code = error instanceof CLIError ? error.code : errorCode;
const errorArg = error instanceof Error ? error : formatError(error);
logger.error(errorArg, code);
process.exit(error instanceof CLIError ? error.exitCode : 1);
}
};
}