Skip to content

Commit

Permalink
refactor: add utils package to webpack-cli
Browse files Browse the repository at this point in the history
  • Loading branch information
anshumanv committed Oct 9, 2020
1 parent ba5bdb3 commit b209dd5
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ export * from './validate-identifier';
export * from './prop-types';
export * from './global-packages-path';
export * from './get-package-manager';
export * from './package-exists';
export * from './run-command';
8 changes: 8 additions & 0 deletions packages/utils/src/package-exists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function packageExists(packageName: string): boolean {
try {
require(packageName);
return true;
} catch (err) {
return false;
}
}
34 changes: 34 additions & 0 deletions packages/utils/src/prompt-installation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { prompt } from 'enquirer';
import { green } from 'colorette';
import { runCommand } from './run-command';

/**
*
* @param packageName
* @param preMessage Message to show before the question
*/
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export async function promptInstallation(packageName: string, preMessage?: Function) {
const packageManager = exports.getPackageManager();
const options = [packageManager === 'yarn' ? 'add' : 'install', '-D', packageName];

const commandToBeRun = `${packageManager} ${options.join(' ')}`;
if (preMessage) {
preMessage();
}
const question = `Would you like to install ${packageName}? (That will run ${green(commandToBeRun)})`;
const { installConfirm } = await prompt([
{
type: 'confirm',
name: 'installConfirm',
message: question,
initial: 'Y',
},
]);
if (installConfirm) {
await runCommand(commandToBeRun);
return exports.packageExists(packageName);
}
// eslint-disable-next-line require-atomic-updates
process.exitCode = 2;
}
12 changes: 12 additions & 0 deletions packages/utils/src/run-command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import execa from 'execa';

export async function runCommand(command, args = []): Promise<void> {
try {
await execa(command, args, {
stdio: 'inherit',
shell: true,
});
} catch (e) {
throw new Error(e);
}
}

0 comments on commit b209dd5

Please sign in to comment.