-
-
Notifications
You must be signed in to change notification settings - Fork 602
/
stats.ts
242 lines (227 loc) · 6.94 KB
/
stats.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/* eslint-disable no-control-regex */
import fs from "node:fs";
import path from "node:path";
import type { Compiler, Stats } from "@rspack/core";
import { escapeEOL } from "../helper";
import captureStdio from "../helper/legacy/captureStdio";
import type {
ECompilerType,
ITestContext,
ITestEnv,
TCompilerOptions
} from "../type";
import { type IMultiTaskProcessorOptions, MultiTaskProcessor } from "./multi";
export interface IStatsProcessorOptions<T extends ECompilerType>
extends Omit<IMultiTaskProcessorOptions<T>, "runable"> {}
const REG_ERROR_CASE = /error$/;
const quoteMeta = (str: string) => {
return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
};
export class StatsProcessor<
T extends ECompilerType
> extends MultiTaskProcessor<T> {
private stderr: any;
constructor(_statsOptions: IStatsProcessorOptions<T>) {
super({
defaultOptions: StatsProcessor.defaultOptions<T>,
overrideOptions: StatsProcessor.overrideOptions<T>,
runable: false,
..._statsOptions
});
}
async before(context: ITestContext) {
this.stderr = captureStdio(process.stderr, true);
}
async after(context: ITestContext) {
this.stderr.restore();
}
async compiler(context: ITestContext) {
await super.compiler(context);
const instance = this.getCompiler(context).getCompiler()! as any;
const compilers: Compiler[] = instance.compilers
? instance.compilers
: [instance];
for (const compiler of compilers) {
const ifs = compiler.inputFileSystem;
compiler.inputFileSystem = Object.create(ifs);
compiler.inputFileSystem.readFile = () => {
const args = Array.prototype.slice.call(arguments);
const callback = args.pop();
ifs.readFile.apply(
ifs,
args.concat([
(err: Error, result: Buffer) => {
if (err) return callback(err);
if (!/\.(js|json|txt)$/.test(args[0]))
return callback(null, result);
callback(null, escapeEOL(result.toString("utf-8")));
}
])
);
};
// CHANGE: The checkConstraints() function is currently not implemented in rspack
// compiler.hooks.compilation.tap("StatsTestCasesTest", compilation => {
// [
// "optimize",
// "optimizeModules",
// "optimizeChunks",
// "afterOptimizeTree",
// "afterOptimizeAssets",
// "beforeHash"
// ].forEach(hook => {
// compilation.hooks[hook].tap("TestCasesTest", () =>
// compilation.checkConstraints()
// );
// });
// });
}
}
async check(env: ITestEnv, context: ITestContext) {
const compiler = this.getCompiler(context);
const stats = compiler.getStats();
const c = compiler.getCompiler();
if (!stats || !c) return;
for (const compilation of []
.concat((stats as any).stats || stats)
.map((s: any) => s.compilation)) {
compilation.logging.delete("webpack.Compilation.ModuleProfile");
}
if (REG_ERROR_CASE.test(this._options.name)) {
env.expect(stats.hasErrors()).toBe(true);
} else if (stats.hasErrors()) {
throw new Error(
stats.toString({
all: false,
errors: true
// errorStack: true,
// errorDetails: true
})
);
} else {
fs.writeFileSync(
path.join(context.getDist(), "stats.txt"),
stats.toString({
preset: "verbose",
// context: context.getSource(),
colors: false
}),
"utf-8"
);
}
let toStringOptions: any = {
context: context.getSource(),
colors: false
};
let hasColorSetting = false;
if (typeof c.options.stats !== "undefined") {
toStringOptions = c.options.stats;
if (toStringOptions === null || typeof toStringOptions !== "object")
toStringOptions = { preset: toStringOptions };
if (!toStringOptions.context)
toStringOptions.context = context.getSource();
hasColorSetting = typeof toStringOptions.colors !== "undefined";
}
if (Array.isArray(c.options) && !toStringOptions.children) {
toStringOptions.children = c.options.map(o => o.stats);
}
// mock timestamps
for (const { compilation: s } of [].concat(
(stats as any).stats || stats
) as Stats[]) {
env.expect(s.startTime).toBeGreaterThan(0);
env.expect(s.endTime).toBeGreaterThan(0);
s.endTime = new Date("04/20/1970, 12:42:42 PM").getTime();
s.startTime = s.endTime - 1234;
}
let actual = stats.toString(toStringOptions);
env.expect(typeof actual).toBe("string");
if (!hasColorSetting) {
actual = this.stderr.toString() + actual;
actual = actual
.replace(/\u001b\[[0-9;]*m/g, "")
// CHANGE: The time unit display in Rspack is second
.replace(/[.0-9]+(\s?s)/g, "X$1");
} else {
actual = this.stderr.toStringRaw() + actual;
// eslint-disable-no-control-regex
actual = actual
.replace(/\u001b\[1m\u001b\[([0-9;]*)m/g, "<CLR=$1,BOLD>")
.replace(/\u001b\[1m/g, "<CLR=BOLD>")
.replace(/\u001b\[39m\u001b\[22m/g, "</CLR>")
.replace(/\u001b\[([0-9;]*)m/g, "<CLR=$1>")
// CHANGE: The time unit display in Rspack is second
.replace(/[.0-9]+(<\/CLR>)?(\s?s)/g, "X$1$2");
}
// cspell:ignore Xdir
const testPath = context.getSource();
actual = actual
.replace(/\r\n?/g, "\n")
// CHANGE: Remove potential line break and "|" caused by long text
.replace(/((ERROR|WARNING)([\s\S](?!╭|├))*?)(\n │ )/g, "$1")
// CHANGE: Update the regular expression to replace the 'Rspack' version string
.replace(/Rspack [^ )]+(\)?) compiled/g, "Rspack x.x.x$1 compiled")
.replace(
new RegExp(quoteMeta(testPath), "g"),
"Xdir/" + path.basename(this._options.name)
)
.replace(/(\w)\\(\w)/g, "$1/$2")
.replace(/, additional resolving: X ms/g, "")
.replace(/Unexpected identifier '.+?'/g, "Unexpected identifier");
env.expect(actual).toMatchSnapshot();
const testConfig = context.getTestConfig();
if (typeof testConfig?.validate === "function") {
testConfig.validate(stats, this.stderr.toString());
}
}
static defaultOptions<T extends ECompilerType>(
index: number,
context: ITestContext
): TCompilerOptions<T> {
if (fs.existsSync(path.join(context.getSource(), "rspack.config.js"))) {
return {
experiments: {
css: true,
rspackFuture: {
bundlerInfo: {
force: false
}
}
}
} as TCompilerOptions<T>;
}
return {
context: context.getSource(),
mode: "development",
entry: "./index.js",
output: {
filename: "bundle.js",
path: context.getDist()
},
optimization: {
minimize: false
},
experiments: {
css: true,
rspackFuture: {
bundlerInfo: {
force: false
}
}
}
} as TCompilerOptions<T>;
}
static overrideOptions<T extends ECompilerType>(
index: number,
context: ITestContext,
options: TCompilerOptions<T>
): void {
if (!options.context) options.context = context.getSource();
if (!options.output) options.output = options.output || {};
if (!options.output.path) options.output.path = context.getDist();
if (!options.plugins) options.plugins = [];
if (!options.optimization) options.optimization = {};
if (options.optimization.minimize === undefined) {
options.optimization.minimize = false;
}
}
}