forked from risc0/risc0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremark-append-md.js
54 lines (45 loc) · 1.71 KB
/
remark-append-md.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
const url = require("url");
const path = require("path");
const fs = require("fs");
// this is a hand-written remark plugin that adds the .md extension to links that point to markdown files
// if it becomes annoying/wrong, we can always remove it
// if you end up removing it, also delete the `"./remark-append-md.js",` line from `package.json`
module.exports = function remarkAppendMd() {
return function transformer(tree, file) {
const baseDir = path.dirname(file.path);
for (const node of tree.children) {
if (node.type === "definition") {
const parsedUrl = url.parse(node.url);
// Check if the URL is internal and doesn't already have an extension
if (!parsedUrl.protocol && !path.extname(parsedUrl.pathname || "")) {
// Separate the path and the fragment (if any)
const [urlPath, fragment] = (parsedUrl.pathname || "").split("#");
let newPath = urlPath;
// Process if the path is not empty and doesn't end with '/'
if (urlPath && !urlPath.endsWith("/")) {
let fullPath;
if (!urlPath.startsWith("/")) {
// Relative path
fullPath = path.resolve(baseDir, urlPath);
}
const mdPath = `${fullPath}.md`;
if (fs.existsSync(mdPath) && fs.statSync(mdPath).isFile()) {
newPath += ".md";
}
}
// Reattach the fragment if it exists
if (fragment) {
newPath += `#${fragment}`;
}
// Reconstruct the URL
node.url = url.format({
...parsedUrl,
pathname: newPath,
search: null,
path: null,
});
}
}
}
};
};