-
Notifications
You must be signed in to change notification settings - Fork 5
/
upgrade-router.js
99 lines (84 loc) · 2.63 KB
/
upgrade-router.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
const fs = require('fs');
const path = require('path');
// Whitelist of root directories to search
const rootDirs = [
'./apps/web',
'./packages/common/icons',
'./packages/common/mui',
'./packages/features',
'./packages/shared',
'./packages/util',
];
function updateFile(filePath) {
let content = fs.readFileSync(filePath, 'utf8');
let modified = false;
// Replace import when useHistory is mixed with other imports
const importRegex =
/import\s*{([^}]*)}\s*from\s*['"]react-router(?:-dom)?['"]/g;
content = content.replace(importRegex, (match, imports) => {
const importList = imports.split(',').map((i) => i.trim());
const updatedImports = importList
.filter((i) => i !== 'useHistory')
.concat(['useNavigate']);
if (importList.includes('useHistory')) {
modified = true;
return `import { ${updatedImports.join(', ')} } from 'react-router-dom'`;
}
return match;
});
// Replace useHistory() with useNavigate()
if (content.includes('useHistory()')) {
content = content.replace(
/const\s+(\w+)\s*=\s*useHistory\(\);/g,
'const navigate = useNavigate();'
);
modified = true;
}
// Replace history.push
if (content.includes('.push(')) {
content = content.replace(/(\w+)\.push\((.*?)\)/g, 'navigate($2)');
modified = true;
}
// Replace history.replace
if (content.includes('.replace(')) {
content = content.replace(
/(\w+)\.replace\((.*?)\)/g,
'navigate($2, { replace: true })'
);
modified = true;
}
// Replace history.goBack()
if (content.includes('.goBack()')) {
content = content.replace(/(\w+)\.goBack\(\)/g, 'navigate(-1)');
modified = true;
}
// Replace history in dependency arrays with navigate
const dependencyRegex = /\[([\s\S]*?history[\s\S]*?)\]/g;
content = content.replace(dependencyRegex, (match, dependencies) => {
// Preserve original formatting
const formattedDependencies = match.replace(/\bhistory\b/g, 'navigate');
return formattedDependencies;
});
if (modified) {
fs.writeFileSync(filePath, content, 'utf8');
console.log(`Updated: ${filePath}`);
}
}
function traverseDirectory(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
traverseDirectory(filePath);
} else if (path.extname(filePath) === '.tsx') {
updateFile(filePath);
}
}
}
// Traverse each whitelisted root directory
rootDirs.forEach((dir) => {
console.log(`Searching in ${dir}...`);
traverseDirectory(dir);
});
console.log('Finished updating files.');