Skip to content

Commit

Permalink
fixup! feat(ng-dev): create system for registering functions to be ca…
Browse files Browse the repository at this point in the history
…lled on command completion
  • Loading branch information
josephperrott committed Aug 11, 2022
1 parent 3310e7c commit 1f12e8a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 27 deletions.
1 change: 1 addition & 0 deletions ng-dev/format/cli.ts
Expand Up @@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Argv} from 'yargs';
import {registerCompletedFunction} from '../utils/yargs.js';
import {AllFilesModule} from './all.js';
import {ChangedModule} from './changed.js';
import {FilesModule} from './files.js';
Expand Down
43 changes: 16 additions & 27 deletions ng-dev/utils/yargs.ts
@@ -1,5 +1,4 @@
import yargs, {Arguments, Argv} from 'yargs';
import {Log} from './logging.js';

// A function to be called when the command completes.
type CompletedFn = (err: Error | null) => Promise<void> | void;
Expand All @@ -12,34 +11,24 @@ export function registerCompletedFunction(fn: CompletedFn) {
completedFunctions.push(fn);
}

/** Error to be thrown when yargs completes without running a command. */
export class YargsError extends Error {
constructor() {
super('Error is parse or validation of command');
}
}

/**
* Run the yargs process, as configured by the supplied function, calling a set of completion
* functions after the command completes.
*/
export function runParserWithCompletedFunctions(applyConfiguration: (argv: Argv) => Argv) {
applyConfiguration(yargs([])).parse(
process.argv.slice(2),
async (err: Error | null, _: Arguments, output: string) => {
if (err && [undefined, 0].includes(process.exitCode)) {
process.exitCode = 1;
}
if (err) {
Log.debug(err);
}
if (output) {
err = err || new YargsError();
Log.log(output);
}
for (const completedFunc of completedFunctions) {
await completedFunc(err);
}
},
);
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);
}
}
}

0 comments on commit 1f12e8a

Please sign in to comment.