create-test-data.js
2.63 KB
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
const fs = require('fs');
const path = require('path');
const baseDir = path.join(__dirname, '..');
const formatDir = path.join(baseDir, 'test', 'fixtures', 'formats');
const parsingDir = path.join(baseDir, 'test', 'fixtures', 'parsing');
const getFiles = (dir) => (fs.readdirSync(dir) || []).reduce((acc, d) => {
d = path.resolve(dir, d);
const stat = fs.statSync(d);
if (!stat.isDirectory()) {
return acc;
}
const subfiles = fs.readdirSync(d).map((f) => path.resolve(d, f));
return acc.concat(subfiles);
}, []);
const buildDataString = function(files, id) {
const data = {};
files.forEach((file) => {
// read the file directly as a buffer before converting to base64
const base64 = fs.readFileSync(file).toString('base64');
data[path.basename(file)] = base64;
});
const dataExportStrings = Object.keys(data).reduce((acc, key) => {
// use a function since the segment may be cleared out on usage
acc.push(`${id}Files['${key}'] = () => {
cache['${key}'] = cache['${key}'] || base64ToUint8Array('${data[key]}');
const dest = new Uint8Array(cache['${key}'].byteLength);
dest.set(cache['${key}']);
return dest;
};`);
return acc;
}, []);
const file =
'/* istanbul ignore file */\n' +
'\n' +
`import base64ToUint8Array from "${path.resolve(baseDir, 'src/decode-b64-to-uint8-array.js')}";\n` +
'const cache = {};\n' +
`const ${id}Files = {};\n` +
dataExportStrings.join('\n') +
`export default ${id}Files`;
return file;
};
/* we refer to them as .js, so that babel and other plugins can work on them */
const formatsKey = 'create-test-data!formats.js';
const parsingKey = 'create-test-data!parsing.js';
module.exports = function() {
return {
name: 'createTestData',
buildStart() {
this.addWatchFile(formatDir);
this.addWatchFile(parsingDir);
getFiles(formatDir).forEach((file) => this.addWatchFile(file));
getFiles(parsingDir).forEach((file) => this.addWatchFile(file));
},
resolveId(importee, importer) {
// if this is not an id we can resolve return
if (importee.indexOf('create-test-data!') !== 0) {
return;
}
const name = importee.split('!')[1];
if (name.indexOf('formats') !== -1) {
return formatsKey;
}
if (name.indexOf('parsing') !== -1) {
return parsingKey;
}
return null;
},
load(id) {
if (id === formatsKey) {
return buildDataString.call(this, getFiles(formatDir), 'format');
}
if (id === parsingKey) {
return buildDataString.call(this, getFiles(parsingDir), 'parsing');
}
}
};
};