/
helpers.ts
437 lines (391 loc) · 20 KB
/
helpers.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
namespace ts {
export function getExpectedDiagnosticForProjectsInBuild(...projects: string[]): fakes.ExpectedDiagnostic {
return [Diagnostics.Projects_in_this_build_Colon_0, projects.map(p => "\r\n * " + p).join("")];
}
export function changeCompilerVersion(host: fakes.SolutionBuilderHost) {
const originalReadFile = host.readFile;
host.readFile = path => {
const value = originalReadFile.call(host, path);
if (!value || !isBuildInfoFile(path)) return value;
const buildInfo = getBuildInfo(value);
buildInfo.version = fakes.version;
return getBuildInfoText(buildInfo);
};
}
export function replaceText(fs: vfs.FileSystem, path: string, oldText: string, newText: string) {
if (!fs.statSync(path).isFile()) {
throw new Error(`File ${path} does not exist`);
}
const old = fs.readFileSync(path, "utf-8");
if (old.indexOf(oldText) < 0) {
throw new Error(`Text "${oldText}" does not exist in file ${path}`);
}
const newContent = old.replace(oldText, newText);
fs.writeFileSync(path, newContent, "utf-8");
}
export function prependText(fs: vfs.FileSystem, path: string, additionalContent: string) {
if (!fs.statSync(path).isFile()) {
throw new Error(`File ${path} does not exist`);
}
const old = fs.readFileSync(path, "utf-8");
fs.writeFileSync(path, `${additionalContent}${old}`, "utf-8");
}
export function appendText(fs: vfs.FileSystem, path: string, additionalContent: string) {
if (!fs.statSync(path).isFile()) {
throw new Error(`File ${path} does not exist`);
}
const old = fs.readFileSync(path, "utf-8");
fs.writeFileSync(path, `${old}${additionalContent}`);
}
export function getTime() {
let currentTime = 100;
return { tick, time, touch };
function tick() {
currentTime += 60_000;
}
function time() {
return currentTime;
}
function touch(fs: vfs.FileSystem, path: string) {
if (!fs.statSync(path).isFile()) {
throw new Error(`File ${path} does not exist`);
}
fs.utimesSync(path, new Date(time()), new Date(time()));
}
}
export const libContent = `${TestFSWithWatch.libFile.content}
interface ReadonlyArray<T> {}
declare const console: { log(msg: any): void; };`;
export function loadProjectFromDisk(root: string, time?: vfs.FileSystemOptions["time"]): vfs.FileSystem {
const resolver = vfs.createResolver(Harness.IO);
const fs = new vfs.FileSystem(/*ignoreCase*/ true, {
files: {
["/src"]: new vfs.Mount(vpath.resolve(Harness.IO.getWorkspaceRoot(), root), resolver)
},
cwd: "/",
meta: { defaultLibLocation: "/lib" },
time
});
fs.mkdirSync("/lib");
fs.writeFileSync("/lib/lib.d.ts", libContent);
fs.makeReadonly();
return fs;
}
function generateSourceMapBaselineFiles(fs: vfs.FileSystem, mapFileNames: ReadonlyArray<string>) {
for (const mapFile of mapFileNames) {
if (!fs.existsSync(mapFile)) continue;
const text = Harness.SourceMapRecorder.getSourceMapRecordWithVFS(fs, mapFile);
fs.writeFileSync(`${mapFile}.baseline.txt`, text);
}
}
// [tsbuildinfo, js, dts]
export type BuildInfoSectionBaselineFiles = [string, string | undefined, string | undefined];
function generateBuildInfoSectionBaselineFiles(fs: vfs.FileSystem, buildInfoFileNames: ReadonlyArray<BuildInfoSectionBaselineFiles>) {
for (const [file, jsFile, dtsFile] of buildInfoFileNames) {
if (!fs.existsSync(file)) continue;
const buildInfo = getBuildInfo(fs.readFileSync(file, "utf8"));
const bundle = buildInfo.bundle;
if (!bundle || (!length(bundle.js && bundle.js.sections) && !length(bundle.dts && bundle.dts.sections))) continue;
// Write the baselines:
const baselineRecorder = new Harness.Compiler.WriterAggregator();
generateBundleFileSectionInfo(fs, baselineRecorder, bundle.js, jsFile);
generateBundleFileSectionInfo(fs, baselineRecorder, bundle.dts, dtsFile);
baselineRecorder.Close();
const text = baselineRecorder.lines.join("\r\n");
fs.writeFileSync(`${file}.baseline.txt`, text, "utf8");
}
}
function generateBundleFileSectionInfo(fs: vfs.FileSystem, baselineRecorder: Harness.Compiler.WriterAggregator, bundleFileInfo: BundleFileInfo | undefined, outFile: string | undefined) {
if (!length(bundleFileInfo && bundleFileInfo.sections) && !outFile) return; // Nothing to baseline
const content = outFile && fs.existsSync(outFile) ? fs.readFileSync(outFile, "utf8") : "";
baselineRecorder.WriteLine("======================================================================");
baselineRecorder.WriteLine(`File:: ${outFile}`);
for (const section of bundleFileInfo ? bundleFileInfo.sections : emptyArray) {
baselineRecorder.WriteLine("----------------------------------------------------------------------");
writeSectionHeader(section);
if (section.kind !== BundleFileSectionKind.Prepend) {
writeTextOfSection(section.pos, section.end);
}
else {
Debug.assert(section.pos === first(section.texts).pos);
Debug.assert(section.end === last(section.texts).end);
for (const text of section.texts) {
baselineRecorder.WriteLine(">>--------------------------------------------------------------------");
writeSectionHeader(text);
writeTextOfSection(text.pos, text.end);
}
}
}
baselineRecorder.WriteLine("======================================================================");
function writeTextOfSection(pos: number, end: number) {
const textLines = content.substring(pos, end).split(/\r?\n/);
for (const line of textLines) {
baselineRecorder.WriteLine(line);
}
}
function writeSectionHeader(section: BundleFileSection) {
baselineRecorder.WriteLine(`${section.kind}: (${section.pos}-${section.end})${section.data ? ":: " + section.data : ""}${section.kind === BundleFileSectionKind.Prepend ? " texts:: " + section.texts.length : ""}`);
}
}
interface BuildInput {
fs: vfs.FileSystem;
tick: () => void;
rootNames: ReadonlyArray<string>;
expectedMapFileNames: ReadonlyArray<string>;
expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray<BuildInfoSectionBaselineFiles>;
modifyFs: (fs: vfs.FileSystem) => void;
}
function build({ fs, tick, rootNames, expectedMapFileNames, expectedBuildInfoFilesForSectionBaselines, modifyFs }: BuildInput) {
const actualReadFileMap = createMap<number>();
modifyFs(fs);
tick();
const host = new fakes.SolutionBuilderHost(fs);
const builder = createSolutionBuilder(host, rootNames, { dry: false, force: false, verbose: true });
host.clearDiagnostics();
const originalReadFile = host.readFile;
host.readFile = path => {
// Dont record libs
if (path.startsWith("/src/")) {
actualReadFileMap.set(path, (actualReadFileMap.get(path) || 0) + 1);
}
return originalReadFile.call(host, path);
};
builder.buildAllProjects();
generateSourceMapBaselineFiles(fs, expectedMapFileNames);
generateBuildInfoSectionBaselineFiles(fs, expectedBuildInfoFilesForSectionBaselines || emptyArray);
fs.makeReadonly();
return { fs, actualReadFileMap, host, builder };
}
function generateBaseline(fs: vfs.FileSystem, proj: string, scenario: string, subScenario: string, baseFs: vfs.FileSystem) {
const patch = fs.diff(baseFs);
// tslint:disable-next-line:no-null-keyword
Harness.Baseline.runBaseline(`tsbuild/${proj}/${subScenario.split(" ").join("-")}/${scenario.split(" ").join("-")}.js`, patch ? vfs.formatPatch(patch) : null);
}
function verifyReadFileCalls(actualReadFileMap: Map<number>, expectedReadFiles: ReadonlyMap<number>) {
TestFSWithWatch.verifyMapSize("readFileCalls", actualReadFileMap, arrayFrom(expectedReadFiles.keys()));
expectedReadFiles.forEach((expected, expectedFile) => {
const actual = actualReadFileMap.get(expectedFile);
assert.equal(actual, expected, `Mismatch in read file call number for: ${expectedFile}
Not in Actual: ${JSON.stringify(arrayFrom(mapDefinedIterator(expectedReadFiles.keys(), f => actualReadFileMap.has(f) ? undefined : f)))}
Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIterator(actualReadFileMap.entries(),
([p, v]) => expectedReadFiles.get(p) !== v ? [p, v, expectedReadFiles.get(p) || 0] : undefined)))}`);
});
}
export function getReadFilesMap(filesReadOnce: ReadonlyArray<string>, ...filesWithTwoReadCalls: string[]) {
const map = arrayToMap(filesReadOnce, identity, () => 1);
for (const fileWithTwoReadCalls of filesWithTwoReadCalls) {
map.set(fileWithTwoReadCalls, 2);
}
return map;
}
export interface ExpectedBuildOutput {
expectedDiagnostics?: ReadonlyArray<fakes.ExpectedDiagnostic>;
expectedReadFiles?: ReadonlyMap<number>;
}
export interface BuildState extends ExpectedBuildOutput {
modifyFs: (fs: vfs.FileSystem) => void;
}
export interface VerifyTsBuildInput {
scenario: string;
projFs: () => vfs.FileSystem;
time: () => number;
tick: () => void;
proj: string;
rootNames: ReadonlyArray<string>;
expectedMapFileNames: ReadonlyArray<string>;
expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray<BuildInfoSectionBaselineFiles>;
lastProjectOutputJs: string;
initialBuild: BuildState;
outputFiles?: ReadonlyArray<string>;
incrementalDtsChangedBuild?: BuildState;
incrementalDtsUnchangedBuild?: BuildState;
incrementalHeaderChangedBuild?: BuildState;
baselineOnly?: true;
verifyDiagnostics?: true;
}
export function verifyTsbuildOutput({
scenario, projFs, time, tick, proj, rootNames, outputFiles, baselineOnly, verifyDiagnostics,
expectedMapFileNames, expectedBuildInfoFilesForSectionBaselines, lastProjectOutputJs,
initialBuild, incrementalDtsChangedBuild, incrementalDtsUnchangedBuild, incrementalHeaderChangedBuild
}: VerifyTsBuildInput) {
describe(`tsc --b ${proj}:: ${scenario}`, () => {
let fs: vfs.FileSystem;
let actualReadFileMap: Map<number>;
let firstBuildTime: number;
let host: fakes.SolutionBuilderHost;
before(() => {
const result = build({
fs: projFs().shadow(),
tick,
rootNames,
expectedMapFileNames,
expectedBuildInfoFilesForSectionBaselines,
modifyFs: initialBuild.modifyFs,
});
({ fs, actualReadFileMap, host } = result);
firstBuildTime = time();
});
after(() => {
fs = undefined!;
actualReadFileMap = undefined!;
host = undefined!;
});
describe("initialBuild", () => {
if (!baselineOnly || verifyDiagnostics) {
it(`verify diagnostics`, () => {
host.assertDiagnosticMessages(...(initialBuild.expectedDiagnostics || emptyArray));
});
}
it(`Generates files matching the baseline`, () => {
generateBaseline(fs, proj, scenario, "initial Build", projFs());
});
if (!baselineOnly) {
it("verify readFile calls", () => {
verifyReadFileCalls(actualReadFileMap, Debug.assertDefined(initialBuild.expectedReadFiles));
});
}
});
function incrementalBuild(subScenario: string, incrementalModifyFs: (fs: vfs.FileSystem) => void, incrementalExpectedDiagnostics: ReadonlyArray<fakes.ExpectedDiagnostic> | undefined, incrementalExpectedReadFiles: ReadonlyMap<number> | undefined) {
describe(subScenario, () => {
let newFs: vfs.FileSystem;
let actualReadFileMap: Map<number>;
let host: fakes.SolutionBuilderHost;
let beforeBuildTime: number;
let afterBuildTime: number;
before(() => {
beforeBuildTime = fs.statSync(lastProjectOutputJs).mtimeMs;
tick();
newFs = fs.shadow();
tick();
({ actualReadFileMap, host } = build({
fs: newFs,
tick,
rootNames,
expectedMapFileNames,
expectedBuildInfoFilesForSectionBaselines,
modifyFs: incrementalModifyFs,
}));
afterBuildTime = newFs.statSync(lastProjectOutputJs).mtimeMs;
});
after(() => {
newFs = undefined!;
actualReadFileMap = undefined!;
host = undefined!;
});
it("verify build output times", () => {
assert.equal(beforeBuildTime, firstBuildTime, "First build timestamp is correct");
assert.equal(afterBuildTime, time(), "Second build timestamp is correct");
});
if (!baselineOnly || verifyDiagnostics) {
it(`verify diagnostics`, () => {
host.assertDiagnosticMessages(...(incrementalExpectedDiagnostics || emptyArray));
});
}
it(`Generates files matching the baseline`, () => {
generateBaseline(newFs, proj, scenario, subScenario, fs);
});
if (!baselineOnly) {
it("verify readFile calls", () => {
verifyReadFileCalls(actualReadFileMap, Debug.assertDefined(incrementalExpectedReadFiles));
});
}
it(`Verify emit output file text is same when built clean`, () => {
const expectedOutputFiles = Debug.assertDefined(outputFiles);
const { fs } = build({
fs: newFs.shadow(),
tick,
rootNames,
expectedMapFileNames: emptyArray,
modifyFs: fs => {
// Delete output files
for (const outputFile of expectedOutputFiles) {
if (fs.existsSync(outputFile)) {
fs.rimrafSync(outputFile);
}
}
},
});
for (const outputFile of expectedOutputFiles) {
const expectedText = fs.existsSync(outputFile) ? fs.readFileSync(outputFile, "utf8") : undefined;
const actualText = newFs.existsSync(outputFile) ? newFs.readFileSync(outputFile, "utf8") : undefined;
assert.equal(actualText, expectedText, `File: ${outputFile}`);
}
});
});
}
if (incrementalDtsChangedBuild) {
incrementalBuild(
"incremental declaration changes",
incrementalDtsChangedBuild.modifyFs,
incrementalDtsChangedBuild.expectedDiagnostics,
incrementalDtsChangedBuild.expectedReadFiles,
);
}
if (incrementalDtsUnchangedBuild) {
incrementalBuild(
"incremental declaration doesnt change",
incrementalDtsUnchangedBuild.modifyFs,
incrementalDtsUnchangedBuild.expectedDiagnostics,
incrementalDtsUnchangedBuild.expectedReadFiles
);
}
if (incrementalHeaderChangedBuild) {
incrementalBuild(
"incremental headers change without dts changes",
incrementalHeaderChangedBuild.modifyFs,
incrementalHeaderChangedBuild.expectedDiagnostics,
incrementalHeaderChangedBuild.expectedReadFiles
);
}
});
}
export function enableStrict(fs: vfs.FileSystem, path: string) {
replaceText(fs, path, `"strict": false`, `"strict": true`);
}
export function addTestPrologue(fs: vfs.FileSystem, path: string, prologue: string) {
prependText(fs, path, `${prologue}
`);
}
export function addShebang(fs: vfs.FileSystem, project: string, file: string) {
prependText(fs, `src/${project}/${file}.ts`, `#!someshebang ${project} ${file}
`);
}
export function restContent(project: string, file: string) {
return `function for${project}${file}Rest() {
const { b, ...rest } = { a: 10, b: 30, yy: 30 };
}`;
}
function nonrestContent(project: string, file: string) {
return `function for${project}${file}Rest() { }`;
}
export function addRest(fs: vfs.FileSystem, project: string, file: string) {
appendText(fs, `src/${project}/${file}.ts`, restContent(project, file));
}
export function removeRest(fs: vfs.FileSystem, project: string, file: string) {
replaceText(fs, `src/${project}/${file}.ts`, restContent(project, file), nonrestContent(project, file));
}
export function addStubFoo(fs: vfs.FileSystem, project: string, file: string) {
appendText(fs, `src/${project}/${file}.ts`, nonrestContent(project, file));
}
export function changeStubToRest(fs: vfs.FileSystem, project: string, file: string) {
replaceText(fs, `src/${project}/${file}.ts`, nonrestContent(project, file), restContent(project, file));
}
export function addSpread(fs: vfs.FileSystem, project: string, file: string) {
const path = `src/${project}/${file}.ts`;
const content = fs.readFileSync(path, "utf8");
fs.writeFileSync(path, `${content}
function ${project}${file}Spread(...b: number[]) { }
${project}${file}Spread(...[10, 20, 30]);`);
replaceText(fs, `src/${project}/tsconfig.json`, `"strict": false,`, `"strict": false,
"downlevelIteration": true,`);
}
export function getTripleSlashRef(project: string) {
return `/src/${project}/tripleRef.d.ts`;
}
export function addTripleSlashRef(fs: vfs.FileSystem, project: string, file: string) {
fs.writeFileSync(getTripleSlashRef(project), `declare class ${project}${file} { }`);
prependText(fs, `src/${project}/${file}.ts`, `///<reference path="./tripleRef.d.ts"/>
const ${file}Const = new ${project}${file}();
`);
}
}