1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const fs = require('fs');
|
18 | const path = require('path');
|
19 |
|
20 | const TOUCHED_FILE_LIST_PATH = path.join(
|
21 | process.cwd(),
|
22 | '.jest-image-snapshot-touched-files'
|
23 | );
|
24 |
|
25 | const IS_ENABLED = !!process.env.JEST_IMAGE_SNAPSHOT_TRACK_OBSOLETE;
|
26 |
|
27 | class OutdatedSnapshotReporter {
|
28 |
|
29 | static markTouchedFile(filePath) {
|
30 | if (!IS_ENABLED) return;
|
31 | const touchedListFileDescriptor = fs.openSync(TOUCHED_FILE_LIST_PATH, 'as');
|
32 | fs.writeSync(touchedListFileDescriptor, `${filePath}\n`);
|
33 | fs.closeSync(touchedListFileDescriptor);
|
34 | }
|
35 |
|
36 |
|
37 | static readTouchedFileListFromDisk() {
|
38 | if (!fs.existsSync(TOUCHED_FILE_LIST_PATH)) return [];
|
39 |
|
40 | return Array.from(
|
41 | new Set(
|
42 | fs
|
43 | .readFileSync(TOUCHED_FILE_LIST_PATH, 'utf-8')
|
44 | .split('\n')
|
45 | .filter(file => file && fs.existsSync(file))
|
46 | )
|
47 | );
|
48 | }
|
49 |
|
50 |
|
51 | onRunStart() {
|
52 | if (!IS_ENABLED) return;
|
53 | if (fs.existsSync(TOUCHED_FILE_LIST_PATH)) {
|
54 | fs.unlinkSync(TOUCHED_FILE_LIST_PATH);
|
55 | }
|
56 | }
|
57 |
|
58 |
|
59 | onRunComplete() {
|
60 | if (!IS_ENABLED) return;
|
61 | const touchedFiles = OutdatedSnapshotReporter.readTouchedFileListFromDisk();
|
62 | const imageSnapshotDirectories = Array.from(
|
63 | new Set(touchedFiles.map(file => path.dirname(file)))
|
64 | );
|
65 | const allFiles = imageSnapshotDirectories
|
66 | .map(dir => fs.readdirSync(dir).map(file => path.join(dir, file)))
|
67 | .reduce((a, b) => a.concat(b), [])
|
68 | .filter(file => file.endsWith('-snap.png'));
|
69 | const obsoleteFiles = allFiles.filter(
|
70 | file => !touchedFiles.includes(file)
|
71 | );
|
72 |
|
73 | if (fs.existsSync(TOUCHED_FILE_LIST_PATH)) {
|
74 | fs.unlinkSync(TOUCHED_FILE_LIST_PATH);
|
75 | }
|
76 |
|
77 | obsoleteFiles.forEach((file) => {
|
78 | process.stderr.write(`Deleting outdated snapshot "${file}"...\n`);
|
79 | fs.unlinkSync(file);
|
80 | });
|
81 | }
|
82 | }
|
83 |
|
84 | module.exports = OutdatedSnapshotReporter;
|