-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodemod-v24.js
100 lines (93 loc) · 2.78 KB
/
codemod-v24.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
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
97
98
99
100
const glob = require("fast-glob");
const fs = require("fs");
const is = (thing, line) => thing.test(line);
const get = (regex, line) => line.match(regex);
const DATA = /^data(\s+(.+))?$/;
const DATA_FORMAT = /^dataFormat(\s+(.+))?$/;
const DATA_VALIDATE = /^dataValidate(\s+(.+))?$/;
let BLOCK = /^(\s*)([A-Z][a-zA-Z0-9]*)(\s+([A-Z][a-zA-Z0-9]*))?$/;
function transform(rtext) {
const text = rtext.replace(/\r\n/g, "\n");
const lines = text.split("\n");
let data = null;
let format = null;
let validate = null;
let dataAdded = false;
let next = [];
for (let index = 0; index < lines.length; index++) {
let l = lines[index];
let line = l.trim();
if (is(BLOCK, l)) {
// reset it so that it could be assigned to multiple blocks
dataAdded = false;
}
if (is(DATA, line)) {
if (
lines[index - 1].startsWith("is") ||
lines[index - 1].endsWith("View")
) {
data = line;
} else {
next.push(l);
}
} else if (data && is(DATA_FORMAT, line)) {
format = line.replace(/dataFormat/g, "format");
} else if (data && is(DATA_VALIDATE, line)) {
validate = line.replace(/dataValidate/g, "validate");
} else if (data && !dataAdded && isDataAssignment(line)) {
let [, indentation] = get(/^(\s+).+$/, l);
next.push(indentation + data);
if (format) {
next.push(indentation + format);
}
if (validate) {
next.push(indentation + validate);
}
next.push(l);
dataAdded = true;
} else {
next.push(l);
}
}
return next.join("\n");
}
function isDataAssignment(line) {
return (
line === "value <" ||
line === "originalValue <" ||
line === "isSubmitting <" ||
line === "isValid <" ||
line === "isValidInitial <" ||
line === "isInvalid <" ||
line === "isInvalidInitial <" ||
line === "onChange <" ||
line === "onSubmit <" ||
line.endsWith("<value") ||
line.endsWith("<!value") ||
line.endsWith("<!originalValue") ||
line.endsWith("<originalValue") ||
line.endsWith("<!isValid") ||
line.endsWith("<isValid") ||
line.endsWith("<isValidInitial") ||
line.endsWith("<!isValidInitial") ||
line.endsWith("<isInvalid") ||
line.endsWith("<!isInvalid") ||
line.endsWith("<isInvalidInitial") ||
line.endsWith("<!isInvalidInitial") ||
line.endsWith("<isSubmitting") ||
line.endsWith("<!isSubmitting") ||
line.endsWith("<isSelected") ||
line.endsWith("<!isSelected") ||
line.endsWith("<onChange") ||
line.endsWith("<onSubmit")
);
}
glob(["src/**/view.blocks"], {
bashNative: ["linux"],
cwd: process.cwd(),
}).then((list) => {
list.forEach((file) => {
const content = fs.readFileSync(file, "utf-8");
fs.writeFileSync(file, transform(content));
});
});