-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathextract-imported-components.js
43 lines (37 loc) · 1.32 KB
/
extract-imported-components.js
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
const { readdirSync, readFileSync, statSync } = require('fs');
const { resolve } = require('path');
const FXA_REACT_IMPORT_REGEX =
/import(?:["'\s]*[\w*{}\n\r\t, ]+from\s*)?["'\s].*(fxa-react\/components\/[\w\\/.]+)["'\s].*$/gm;
function eligibleFile(file) {
return (
['.jsx', '.tsx', '.js', '.ts'].some((ext) => file.endsWith(ext)) &&
!file.includes('.test')
);
}
function getExtractableFiles(dir) {
const subdirs = readdirSync(dir);
return subdirs
.flatMap((subdir) => {
const res = resolve(dir, subdir);
return statSync(res).isDirectory() ? getExtractableFiles(res) : res;
})
.filter(eligibleFile);
}
function parseForImports(paths, prefix = '../', suffix = '/**/*.tsx') {
return paths.flatMap((path) => {
const contents = readFileSync(path, { encoding: 'utf-8' });
const matches = [];
let match = FXA_REACT_IMPORT_REGEX.exec(contents);
while (match != null) {
matches.push(prefix + match[1] + suffix);
match = FXA_REACT_IMPORT_REGEX.exec(contents);
}
return matches;
});
}
function extractImportedComponents(dirToScan, prefix, suffix) {
console.log('Extracting externally imported component paths...');
const filePaths = getExtractableFiles(dirToScan);
return parseForImports(filePaths, prefix, suffix);
}
module.exports = extractImportedComponents;