-
Notifications
You must be signed in to change notification settings - Fork 49
/
yargs.ts
34 lines (30 loc) · 1.04 KB
/
yargs.ts
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
import yargs, {Arguments, Argv} from 'yargs';
// A function to be called when the command completes.
type CompletedFn = (err: Error | null) => Promise<void> | void;
/** List of functions to be called upon command completion. */
const completedFunctions: CompletedFn[] = [];
/** Register a function to be called when the command completes. */
export function registerCompletedFunction(fn: CompletedFn) {
completedFunctions.push(fn);
}
/**
* Run the yargs process, as configured by the supplied function, calling a set of completion
* functions after the command completes.
*/
export async function runParserWithCompletedFunctions(applyConfiguration: (argv: Argv) => Argv) {
let err: Error | null = null;
try {
await applyConfiguration(yargs(process.argv.slice(2)))
.exitProcess(false)
.parse();
} catch (e) {
err = e as Error;
if ([undefined, 0].includes(process.exitCode)) {
process.exitCode = 1;
}
} finally {
for (const completedFunc of completedFunctions) {
await completedFunc(err);
}
}
}