Skip to content

Commit e9bb991

Browse files
committed
apply changes from d3/d3#3673
1 parent ff61954 commit e9bb991

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

test/docs-test.js

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
import assert from "assert";
2-
import {readdirSync, readFileSync, statSync} from "fs";
2+
import {readdir, readFile, stat} from "fs/promises";
33

44
it("documentation links point to existing internal anchors", async () => {
55
const root = "docs";
66

77
// Crawl all files, read their links and anchors.
88
const anchors = new Map();
99
const links = [];
10-
for (const file of getMDFiles(root)) {
11-
const text = getSource(root + file);
10+
for await (const file of readMarkdownFiles(root)) {
11+
const text = await readMarkdownSource(root + file);
1212
anchors.set(file, getAnchors(text));
13-
for (const {pathname, hash} of getLinks(file, text)) links.push({source: file, target: pathname, hash});
13+
for (const {pathname, hash} of getLinks(file, text)) {
14+
links.push({source: file, target: pathname, hash});
15+
}
1416
}
1517

1618
// Check for broken links.
@@ -50,25 +52,23 @@ function getLinks(file, text) {
5052
const links = [];
5153
for (const match of text.matchAll(/\[[^\]]+\]\(([^)]+)\)/g)) {
5254
const [, link] = match;
53-
if (link.startsWith("http")) continue;
54-
const {pathname, hash} = new URL(link, new URL(file, "https://toplevel.tld/"));
55+
if (/^\w+:/.test(link)) continue; // absolute link with protocol
56+
const {pathname, hash} = new URL(link, new URL(file, "https://example.com/"));
5557
links.push({pathname, hash});
5658
}
5759
return links;
5860
}
5961

6062
// In source files, ignore comments.
61-
function getSource(f) {
62-
return readFileSync(f, "utf8").replaceAll(/<!-- .*? -->/gs, "");
63+
async function readMarkdownSource(f) {
64+
return (await readFile(f, "utf8")).replaceAll(/<!-- .*? -->/gs, "");
6365
}
6466

6567
// Recursively find all md files in the directory.
66-
function getMDFiles(root, subpath = "/") {
67-
const files = [];
68-
for (const fname of readdirSync(root + subpath)) {
69-
if (fname.startsWith(".") || fname.endsWith(".js")) continue;
70-
if (fname.endsWith(".md")) files.push(subpath + fname);
71-
else if (statSync(root + subpath + fname).isDirectory()) files.push(...getMDFiles(root, subpath + fname + "/"));
68+
async function* readMarkdownFiles(root, subpath = "/") {
69+
for (const fname of await readdir(root + subpath)) {
70+
if (fname.startsWith(".")) continue; // ignore .vitepress etc.
71+
if ((await stat(root + subpath + fname)).isDirectory()) yield* readMarkdownFiles(root, subpath + fname + "/");
72+
else if (fname.endsWith(".md")) yield subpath + fname;
7273
}
73-
return files;
7474
}

0 commit comments

Comments
 (0)