From f23406462b5aff526900ef99638d82ad1ef06dd9 Mon Sep 17 00:00:00 2001 From: Joey Perrott Date: Tue, 30 Mar 2021 16:11:54 -0700 Subject: [PATCH] feat(dev-infra): create dry-run environment variable flag utils (#41387) Create utility functions for adding a dry-run flag and checking the environment for a dry run mode. PR Close #41387 --- dev-infra/utils/dry-run.ts | 43 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 dev-infra/utils/dry-run.ts diff --git a/dev-infra/utils/dry-run.ts b/dev-infra/utils/dry-run.ts new file mode 100644 index 0000000000..06421a4c26 --- /dev/null +++ b/dev-infra/utils/dry-run.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import {Argv} from 'yargs'; + +/** + * Add a --dry-run flag to the available options for the yargs argv object. When present, sets an + * environment variable noting dry run mode. + */ +export function addDryRunFlag(args: Argv) { + return args.option('dry-run' as 'dryRun', { + type: 'boolean', + default: false, + description: 'Whether to do a dry run', + coerce: (dryRun: boolean) => { + if (dryRun) { + process.env['DRY_RUN'] = '1'; + } + return dryRun; + } + }); +} + +/** Whether the current environment is in dry run mode. */ +export function isDryRun(): boolean { + return process.env['DRY_RUN'] !== undefined; +} + +/** Error to be thrown when a function or method is called in dryRun mode and shouldn't be. */ +export class DryRunError extends Error { + constructor() { + super('Cannot call this function in dryRun mode.'); + // Set the prototype explicitly because in ES5, the prototype is accidentally lost due to + // a limitation in down-leveling. + // https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work. + Object.setPrototypeOf(this, DryRunError.prototype); + } +}