UNPKG

2.75 kBJavaScriptView Raw
1/*
2 * Copyright (c) 2020 American Express Travel Related Services Company, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14
15/* eslint-disable class-methods-use-this */
16
17const fs = require('fs');
18const path = require('path');
19
20const TOUCHED_FILE_LIST_PATH = path.join(
21 process.cwd(),
22 '.jest-image-snapshot-touched-files'
23);
24
25const IS_ENABLED = !!process.env.JEST_IMAGE_SNAPSHOT_TRACK_OBSOLETE;
26
27class OutdatedSnapshotReporter {
28 /* istanbul ignore next - test coverage in child process */
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 /* istanbul ignore next - test coverage in child process */
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 /* istanbul ignore next - test coverage in child process */
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 /* istanbul ignore next - test coverage in child process */
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
84module.exports = OutdatedSnapshotReporter;