forked from webpack/webpack-cli
/
index.ts
207 lines (192 loc) · 7.74 KB
/
index.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { green, red } from 'colorette';
import { Change, diffLines } from 'diff';
import fs from 'fs';
import inquirer from 'inquirer';
import { logger } from 'webpack-cli';
import Listr from 'listr';
import pLazy = require('p-lazy');
import path from 'path';
import { validate, WebpackOptionsValidationError } from 'webpack';
import { runPrettier } from '@webpack-cli/utils';
import { transformations } from './migrate';
import { Node } from './types/NodePath';
import jscodeshift from 'jscodeshift';
declare let process: {
cwd: Function;
webpackModule: {
validate: Function;
WebpackOptionsValidationError: {
new: (
errors: string[],
) => {
message: string;
};
};
};
stdout: {
write: Function;
};
exitCode: number;
};
/**
*
* Runs migration on a given configuration using AST's and promises
* to sequentially transform a configuration file.
*
* @param {String} currentConfigPath - input path for config
* @param {String} outputConfigPath - output path for config
* @returns {Promise} Runs the migration using a promise that
* will throw any errors during each transform or output if the
* user decides to abort the migration
*/
function runMigration(currentConfigPath: string, outputConfigPath: string): Promise<void> | void {
const recastOptions: object = {
quote: 'single',
};
const tasks: Listr = new Listr([
{
task: (ctx: Node): string | void | Listr | Promise<{}> =>
new pLazy((resolve: (value?: object) => void, reject: (reason?: string | object, err?: object) => void): void => {
fs.readFile(currentConfigPath, 'utf8', (err: object, content: string): void => {
if (err) {
reject(err);
}
try {
ctx.source = content;
ctx.ast = jscodeshift(content);
resolve();
} catch (err) {
reject('Error generating AST', err);
}
});
}),
title: 'Reading webpack config',
},
{
task: (ctx: Node): string | void | Listr | Promise<{}> => {
return new Listr(
Object.keys(transformations).map((key: string): {
task: () => string;
title: string;
} => {
const transform: Function = transformations[key];
return {
task: (): string => transform(ctx.ast, ctx.source),
title: key,
};
}),
);
},
title: 'Migrating config to newest version',
},
]);
tasks
.run()
.then((ctx: Node): void | Promise<void> => {
const result: string = ctx.ast.toSource(recastOptions);
const diffOutput: Change[] = diffLines(ctx.source, result);
diffOutput.forEach((diffLine: Change): void => {
if (diffLine.added) {
process.stdout.write(green(`+ ${diffLine.value}`));
} else if (diffLine.removed) {
process.stdout.write(red(`- ${diffLine.value}`));
}
});
return inquirer
.prompt([
{
default: 'Y',
message: 'Are you sure these changes are fine?',
name: 'confirmMigration',
type: 'confirm',
},
])
.then(
(answers: { confirmMigration: boolean }): Promise<{}> => {
if (answers.confirmMigration) {
return inquirer.prompt([
{
default: 'Y',
message:
'Do you want to validate your configuration? ' +
"(If you're using webpack merge, validation isn't useful)",
name: 'confirmValidation',
type: 'confirm',
},
]);
} else {
logger.error('✖ Migration aborted');
}
},
)
.then(
async (answer: { confirmValidation: boolean }): Promise<void> => {
if (!answer) {
return;
}
runPrettier(outputConfigPath, result);
if (answer.confirmValidation) {
const outputConfig = (await import(outputConfigPath)).default;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const webpackOptionsValidationErrors: any = validate(outputConfig);
if (webpackOptionsValidationErrors && webpackOptionsValidationErrors.length) {
logger.error("\n✖ Your configuration validation wasn't successful\n");
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
logger.error(new WebpackOptionsValidationError(webpackOptionsValidationErrors));
}
}
logger.success(`\n✔︎ New webpack config file is at ${outputConfigPath}.`);
logger.success('✔︎ Heads up! Updating to the latest version could contain breaking changes.');
logger.success('✔︎ Plugin and loader dependencies may need to be updated.');
},
);
})
.catch((err: object): void => {
logger.error('\n ✖ ︎Migration aborted due to some errors:\n');
logger.error(err);
process.exitCode = 1;
});
}
/**
*
* Runs migration on a given configuration using AST's and promises
* to sequentially transform a configuration file.
*
* @param {Array} args - Migrate arguments such as input and
* output path
* @returns {Function} Runs the migration using the 'runMigrate'
* function.
*/
export default async function migrate(...args: string[]): Promise<void> {
const filePaths = args;
if (!filePaths.length) {
logger.error('\n ✖ Please specify a path to your webpack config\n');
return;
}
const currentConfigPath = path.resolve(filePaths[0]);
let outputConfigPath: string;
if (!filePaths[1]) {
try {
const { confirmPath } = await inquirer.prompt([
{
default: 'Y',
message: 'Migration output path not specified. Do you want to use your existing webpack configuration?',
name: 'confirmPath',
type: 'confirm',
},
]);
if (!confirmPath) {
logger.error('✖ ︎Migration aborted due to no output path');
return;
}
outputConfigPath = path.resolve(filePaths[0]);
return runMigration(currentConfigPath, outputConfigPath);
} catch (err) {
logger.error(err);
return;
}
}
outputConfigPath = path.resolve(filePaths[1]);
return runMigration(currentConfigPath, outputConfigPath);
}