forked from webpack/webpack-cli
/
resolve-packages.ts
94 lines (83 loc) · 3.04 KB
/
resolve-packages.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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { bold } from 'colorette';
import { logger } from 'webpack-cli';
import path from 'path';
import { modifyHelperUtil } from './modify-config-helper';
import { getPathToGlobalPackages } from './global-packages-path';
import { spawnChild } from './spawn-child';
import { isLocalPath } from './path-utils';
import { ExecaSyncReturnValue } from 'execa';
interface ChildProcess {
status: number;
}
/**
*
* Attaches a promise to the installation of the package
*
* @param {Function} child - The function to attach a promise to
* @returns {Promise} promise - Returns a promise to the installation
*/
export function processPromise(child: ExecaSyncReturnValue): Promise<void> {
return new Promise((resolve: () => void, reject: () => void): void => {
if (child.exitCode !== 0) {
reject();
} else {
resolve();
}
});
}
/**
*
* Resolves and installs the packages, later sending them to @creator
*
* @param {String[]} pkg - The dependencies to be installed
* @returns {Function|Error} creator - Builds
* a webpack configuration through yeoman or throws an error
*/
export function resolvePackages(pkg: string[]): Function | void {
Error.stackTraceLimit = 30;
const packageLocations: string[] = [];
function invokeGeneratorIfReady(): void {
if (packageLocations.length === pkg.length) {
modifyHelperUtil('init', null, null, packageLocations);
}
}
pkg.forEach((scaffold: string): void => {
// Resolve paths to modules on local filesystem
if (isLocalPath(scaffold)) {
let absolutePath: string = scaffold;
try {
absolutePath = path.resolve(process.cwd(), scaffold);
require.resolve(absolutePath);
packageLocations.push(absolutePath);
} catch (err) {
logger.error(`Cannot find a generator at ${absolutePath}.\n`);
logger.error('Reason:\n');
logger.error(bold(err));
process.exitCode = 1;
}
invokeGeneratorIfReady();
return;
}
// Resolve modules on npm registry
processPromise(spawnChild(scaffold))
.then((): void => {
try {
const globalPath: string = getPathToGlobalPackages();
packageLocations.push(path.resolve(globalPath, scaffold));
} catch (err) {
logger.error("Package wasn't validated correctly...");
logger.error(`Submit an issue for ${pkg} if this persists\n`);
logger.error('Reason:\n');
logger.error(bold(err));
process.exitCode = 1;
}
})
.catch((err: string): void => {
logger.error("Package couldn't be installed, aborting...\n");
logger.error('Reason:\n');
logger.error(bold(err));
process.exitCode = 1;
})
.then(invokeGeneratorIfReady);
});
}