Created
April 17, 2024 13:52
-
-
Save jmduke/30f5c6873163a80af8403fe359d7cb67 to your computer and use it in GitHub Desktop.
Basic test to check for internal links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const extractInternalLinks = (content: string): string[] => { | |
// Check for internal links only, in the form of [text](/path). | |
const internalLinks = content.match(/\[.*?\]\(\/.*?\)/g); | |
return ( | |
(internalLinks | |
?.map((link) => { | |
const path = link.match(/\(\/.*?\)/) | |
? link.match(/\(\/.*?\)/)![0].slice(2, -1) | |
: null; | |
// For now, we'll filter out any images or other non-page links under | |
// the assumption that they can be caught elsewhere (e.g. the build step.) | |
if (path && path.match(/\.(png|jpg|jpeg|gif|svg|webp|ico|pdf)$/)) { | |
return null; | |
} | |
return path; | |
}) | |
.filter((link) => link !== null) as string[]) || [] | |
); | |
}; | |
const MARKDOC_DIRECTORY = "content/pages"; | |
// Make sure all mdoc files with internal links are valid. | |
fs.readdirSync(MARKDOC_DIRECTORY).forEach((filename) => { | |
test("Check internal links in " + filename, () => { | |
const fullyQualifiedFilename = `${MARKDOC_DIRECTORY}/${filename}`; | |
const content = fs.readFileSync(fullyQualifiedFilename, "utf-8"); | |
const internalLinks = extractInternalLinks(content); | |
internalLinks.forEach((outboundPath) => { | |
const mungedOutboundPath = mungeInternalLinks(outboundPath); | |
const expectedOutboundFilename = `${MARKDOC_DIRECTORY}/${mungedOutboundPath}.mdoc`; | |
expect( | |
fs.existsSync(expectedOutboundFilename), | |
`Internal link to "/${outboundPath}" in "${filename}" does not exist.` | |
).toBeTruthy(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment