-
Notifications
You must be signed in to change notification settings - Fork 33
/
change-path-reducer-accessing-root-path.js
64 lines (54 loc) · 1.94 KB
/
change-path-reducer-accessing-root-path.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
module.exports = (file, api) => {
const j = api.jscodeshift;
const rootPathWithDotRegex = /\$\.(\s|$)/g;
const root = j(file.source);
function detectQuoteStyle(item, quoteRoot) {
let detectedQuoting = "single";
quoteRoot
.find(item.Literal, {
value: v => typeof v === "string",
raw: v => typeof v === "string"
})
.forEach(p => {
// The raw value is from the original babel source
if (p.value.raw[0] === "'") {
detectedQuoting = "single";
}
if (p.value.raw[0] === '"') {
detectedQuoting = "double";
}
});
return detectedQuoting;
}
// transforms a string from '$. | $. | $.' -> '$ | $ | $'
function transformLiteral(node) {
const originalValue = node.value.value;
if (rootPathWithDotRegex.test(originalValue)) {
// eslint-disable-next-line no-param-reassign
node.value.value = node.value.value.replace(rootPathWithDotRegex, "$$$1");
}
}
// transforms a template literal from `$. | $. | $.` -> `$ | $ | $`
function transformTemplateElement(node) {
const originalValue = node.value.value.raw;
if (rootPathWithDotRegex.test(originalValue)) {
// eslint-disable-next-line no-param-reassign
node.value.value.raw = node.value.value.raw.replace(
rootPathWithDotRegex,
"$$$1"
);
}
}
function refactorReducerMatches(nodeType, transform) {
root.find(nodeType).forEach(transform);
}
refactorReducerMatches(j.Literal, transformLiteral);
refactorReducerMatches(j.TemplateElement, transformTemplateElement);
// As Recast is not preserving original quoting, we try to detect it,
// and default to something sane.
// See https://github.com/benjamn/recast/issues/171
// and https://github.com/facebook/jscodeshift/issues/143
// credit to @skovhus: https://github.com/avajs/ava-codemods/pull/28
const quote = detectQuoteStyle(j, root);
return root.toSource({ quote });
};