-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodemod-onwhen-to-the-top.js
47 lines (38 loc) · 1.13 KB
/
codemod-onwhen-to-the-top.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
const glob = require('fast-glob');
const fs = require('fs');
const is = (thing, line) => thing.test(line);
const get = (regex, line) => line.match(regex);
const BLOCK = /^([A-Z][a-zA-Z0-9]*)(\s+([A-Z][a-zA-Z0-9]*))?$/;
const PROP = /^([a-z][a-zA-Z0-9]*)(\s+(.+))?$/;
const getProp = line => get(PROP, line);
const isBlock = line => is(BLOCK, line);
const isProp = line => is(PROP, line);
function transform(rtext) {
const text = rtext.replace(/\r\n/g, '\n');
const lines = text.split('\n').map(line => line.trim());
const next = [];
let lastBlockIndex;
lines.forEach((line, i) => {
if (isBlock(line)) {
lastBlockIndex = i;
}
if (isProp(line)) {
const [_, prop, _1, value] = getProp(line);
if (prop === 'onWhen' && i !== lastBlockIndex + 1) {
next.splice(lastBlockIndex + 1, 0, line);
return;
}
}
next.push(line);
});
return next.join('\n');
}
glob(['src/**/*.view'], {
bashNative: ['linux'],
cwd: process.cwd(),
}).then(list => {
list.forEach(file => {
const content = fs.readFileSync(file, 'utf-8');
fs.writeFileSync(file, transform(content));
});
});