-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate-redirects.ts
More file actions
59 lines (47 loc) · 1.67 KB
/
validate-redirects.ts
File metadata and controls
59 lines (47 loc) · 1.67 KB
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
import { existsSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import YAML from 'yaml'
import { siteSections } from './lib/config.js'
const gitbookConfig = YAML.parse(readFileSync('.gitbook.yaml', 'utf-8')) as {
redirects?: Record<string, string>
}
interface Redirect {
source: string
target: string
}
const redirects: Redirect[] = Object.entries(gitbookConfig.redirects ?? {}).map(
([source, target]) => ({ source, target }),
)
function pageExists(fullPath: string): boolean {
return existsSync(fullPath) && statSync(fullPath).isFile()
}
function resolveTarget(target: string): boolean {
for (const section of siteSections) {
if (section.urlPrefix === '') continue
const prefix = section.urlPrefix.replace(/^\//, '') + '/'
if (target.startsWith(prefix)) {
const relativePath = target.slice(prefix.length)
return pageExists(join(section.root, relativePath))
}
}
const guidesSection = siteSections.find((s) => s.urlPrefix === '')
if (guidesSection == null) return false
return pageExists(join(guidesSection.root, target))
}
const broken: Redirect[] = redirects.filter((r) => !resolveTarget(r.target))
if (broken.length > 0) {
// eslint-disable-next-line no-console
console.error(
`Found ${broken.length} redirect(s) with missing target(s) in .gitbook.yaml:\n`,
)
for (const { source, target } of broken) {
// eslint-disable-next-line no-console
console.error(` ${source}`)
// eslint-disable-next-line no-console
console.error(` target: ${target}\n`)
}
process.exit(1)
} else {
// eslint-disable-next-line no-console
console.log('All .gitbook.yaml redirect targets are valid.')
}