forked from mdn/content
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate-moved-file-links.js
145 lines (129 loc) · 3.91 KB
/
update-moved-file-links.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import fs from "node:fs/promises";
import path from "node:path";
import {
execGit,
getRootDir,
walkSync,
isImagePath,
IMG_RX,
SLUG_RX,
} from "./utils.js";
const HELP_MSG =
"Usage:\n\t" +
"node scripts/update-moved-file-links.js\n\t" +
"node scripts/update-moved-file-links.js --check\n";
/**
* Try to get slug for an image from file path
*/
export async function getImageSlug(imagePath, root) {
const nodePath = path.parse(imagePath);
const absolutePath = `${root}/files/en-us/${nodePath.dir}/index.md`;
let content;
try {
content = await fs.readFile(absolutePath, "utf-8");
} catch (e) {}
if (content) {
return `/en-US/docs/${(content.match(SLUG_RX) || [])[0]}/${nodePath.base}`;
} else {
return `/en-US/docs/${imagePath}`;
}
}
const rootDir = getRootDir();
let movedFiles = [];
let isCheckOnly = false;
if (process.argv[2] === "--help" || process.argv[2] === "-h") {
console.error(HELP_MSG);
process.exit(0);
} else if (process.argv[2] === "--check") {
isCheckOnly = true;
}
// get staged and unstaged changes
const result = execGit(["status", "--short", "--porcelain"], { cwd: "." });
if (result.trim()) {
movedFiles.push(
...result
.split("\n")
.filter(
(line) =>
/^\s*RM?\s+/gi.test(line) &&
line.includes("files/en-us") &&
(IMG_RX.test(line) || line.includes("index.md")),
)
.map((line) =>
line.replaceAll(/^\s*RM?\s+|files\/en-us\/|\/index.md/gm, ""),
)
.map((line) => line.split(/ -> /))
.map((tuple) => {
return { from: tuple[0], to: tuple[1] };
}),
);
}
if (movedFiles.length < 1) {
console.log("No content files were moved. Nothing to update! 🎉");
process.exit(0);
}
const redirectsText = await fs.readFile(
`${rootDir}/files/en-us/_redirects.txt`,
"utf-8",
);
// convert file paths to slugs
movedFiles = (
await Promise.all(
movedFiles.map(async (tuple) => {
const movedLineRg = new RegExp(`\n.*?${tuple.from}\\s+.*?\n`, "gmi");
const redirectLine = (redirectsText.match(movedLineRg) || [])[0];
if (redirectLine) {
const urls = redirectLine.trim().split(/\s+/);
return { from: urls[0], to: urls[1] };
}
if (isImagePath(tuple.from)) {
return {
from: await getImageSlug(tuple.from, rootDir),
to: await getImageSlug(tuple.to, rootDir),
};
}
console.warn("No redirect entry found for: ", tuple.from);
}),
)
).filter((e) => !!e);
console.log("Moved files:", movedFiles);
let totalNo = 0;
let updatedNo = 0;
for await (const filePath of walkSync(getRootDir())) {
if (filePath.endsWith("index.md")) {
try {
totalNo++;
const content = await fs.readFile(filePath, "utf-8");
let updated = String(content);
for (const moved of movedFiles) {
// [text](link)
updated = updated.replaceAll(`${moved.from})`, `${moved.to})`);
// <link>
updated = updated.replaceAll(`${moved.from}>`, `${moved.to}>`);
// [text](link#)
updated = updated.replaceAll(`${moved.from}#`, `${moved.to}#`);
// [text](link "tool tip")
updated = updated.replaceAll(`${moved.from} `, `${moved.to} `);
// <a href="link">
updated = updated.replaceAll(`${moved.from}"`, `${moved.to}"`);
// <a href='link'>
updated = updated.replaceAll(`${moved.from}'`, `${moved.to}'`);
}
if (content !== updated.valueOf()) {
if (isCheckOnly) {
console.error(
"File(s) have been moved. " +
"Run 'node scripts/update-moved-file-links.js' to update references.",
);
process.exit(1);
}
updatedNo++;
await fs.writeFile(filePath, updated);
}
} catch (e) {
console.error(`Error processing ${filePath}: ${e.message}`);
throw e;
}
}
}
console.log(`Updated moved file links in ${updatedNo}/${totalNo} files.`);