-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
89 lines (75 loc) · 2.17 KB
/
index.ts
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
#!/usr/bin/env node
import { readdir, stat } from "fs/promises"
import { join, relative } from "path"
const fmtRed = "\x1b[31m"
const fmtReset = "\x1b[0m"
const fmtBold = "\x1b[1m"
const baseDirs = ["app", "src/app"]
let basePath = ""
let pathMap = new Map<string, string[]>()
let collisionsDetected = false
async function findAppDir(baseDirs: string[]) {
for (const dir of baseDirs) {
try {
await stat(dir)
return dir
} catch (error) {
continue
}
}
return ""
}
async function traverseDir(dir: string, baseUrl = "") {
const entries = await readdir(dir, { withFileTypes: true })
for (const entry of entries) {
if (entry.name.startsWith("_")) {
continue // Skip files starting with underscore
}
const fullPath = join(dir, entry.name)
if (entry.isDirectory()) {
await traverseDir(fullPath, join(baseUrl, entry.name))
} else if (entry.isFile() && entry.name.endsWith(".tsx")) {
const urlPath = convertPathToUrl(fullPath)
if (!pathMap.has(urlPath)) {
pathMap.set(urlPath, [])
}
pathMap.get(urlPath)!.push(fullPath)
}
}
}
function convertPathToUrl(filePath: string): string {
let url = "/" + relative(basePath, filePath)
// Remove segments within parentheses
url = url.replace(/\/\([^)]*\)/g, "")
// Replace index.tsx with /, and remove file extensions
url = url.replace(/\/index\.tsx$/, "/")
url = url.replace(/\.(tsx)$/, "")
return url
}
async function main() {
basePath = await findAppDir(baseDirs)
if (!basePath) {
console.error("Base directory not found")
return
}
await traverseDir(basePath)
let sortedUrls = Array.from(pathMap.keys()).sort()
sortedUrls.forEach((url) => {
const paths = pathMap.get(url)
if (paths!.length > 1) {
// Only log if there are collisions
console.log(url)
paths!.forEach((path) => console.log(` - ${fmtRed}${fmtBold}${path}${fmtReset}`))
collisionsDetected = true
} else {
console.log(url)
}
})
if (!collisionsDetected) {
console.log("\n✅ No route collisions detected.")
} else {
console.log(`\n${fmtRed}❌${fmtReset} Collisions detected!`)
process.exit(1)
}
}
main()