-
Notifications
You must be signed in to change notification settings - Fork 0
/
ext_regex.js
51 lines (45 loc) · 1.48 KB
/
ext_regex.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
44
45
46
47
48
49
50
51
const { argv, stdin } = require('process');
const { readFileSync } = require('fs');
const { parse } = require('@babel/parser');
const BABEL_OPTION = {
sourceType: "module",
tokens: true,
classProperties: true,
plugins: [
['classProperties', require('@babel/plugin-proposal-class-properties')],
],
};
const extractJS = (filename) => {
const source = readFileSync(filename, { encoding: 'utf-8' });
if (typeof filename === 'string' && filename.endsWith('.vue')) {
const lines = source.split('\n');
const trimmedLines = lines.map((ln) => ln.trim());
const begin = trimmedLines.indexOf('<script>');
const end = trimmedLines.indexOf('</script>', begin + 1);
if (begin < 0 && end < 0) {
return { source: '', base: 0 };
}
if (begin && end) {
const base = begin + 1;
return { source: lines.slice(base, end).join('\n'), base };
}
}
return { source, base: 0 };
};
const extractRegExpressions = (sourceFile) => {
try {
const { source, base } = extractJS(sourceFile);
const code = parse(source, BABEL_OPTION);
const list = code.tokens
.filter(({ type }) => type.label === 'regexp')
.map(({ start, end, loc: { start: { line: ln, column: col } } }) => ({
line: base + ln,
col,
val: source.slice(start, end),
}));
console.log(JSON.stringify(list, null, 2));
} catch (e) {
console.error(`Error when parsing file ${sourceFile}:`, e);
}
};
extractRegExpressions(argv[2] || stdin.fd);