Unverified Commit a43b9ed6 authored by Delba de Oliveira's avatar Delba de Oliveira Committed by GitHub

[Docs] Update broken link validator (#51586)

- Add some basic error handling to the link validator action.
- Avoid unnecessarily creating a new bot comment when the validation is successful.
- Only scan .mdx files modified in the current PR for broken links.
parent 36a7aff6
@actions/core
MIT
The MIT License (MIT)
Copyright 2019 GitHub
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@actions/github @actions/github
MIT MIT
The MIT License (MIT) The MIT License (MIT)
...@@ -2137,6 +2149,19 @@ Permission to use, copy, modify, and/or distribute this software for any purpose ...@@ -2137,6 +2149,19 @@ Permission to use, copy, modify, and/or distribute this software for any purpose
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
uuid
MIT
The MIT License (MIT)
Copyright (c) 2010-2020 Robert Kieffer and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vfile vfile
MIT MIT
(The MIT License) (The MIT License)
......
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
"@vercel/ncc": "0.34.0" "@vercel/ncc": "0.34.0"
}, },
"dependencies": { "dependencies": {
"@actions/core": "^1.10.0",
"@actions/github": "^5.1.1", "@actions/github": "^5.1.1",
"github-slugger": "1.2.0", "github-slugger": "1.2.0",
"gray-matter": "4.0.2", "gray-matter": "4.0.2",
......
...@@ -8,6 +8,7 @@ import visit from 'unist-util-visit' ...@@ -8,6 +8,7 @@ import visit from 'unist-util-visit'
import GithubSlugger from 'github-slugger' import GithubSlugger from 'github-slugger'
import matter from 'gray-matter' import matter from 'gray-matter'
import * as github from '@actions/github' import * as github from '@actions/github'
import { setFailed } from '@actions/core'
import type { Node, Data } from 'unist' import type { Node, Data } from 'unist'
/** /**
...@@ -16,12 +17,12 @@ import type { Node, Data } from 'unist' ...@@ -16,12 +17,12 @@ import type { Node, Data } from 'unist'
* 1. Recursively traverses the docs and collects all .mdx files. * 1. Recursively traverses the docs and collects all .mdx files.
* 2. For each file, it extracts the content, metadata, and heading slugs. * 2. For each file, it extracts the content, metadata, and heading slugs.
* 3. It creates a document map to efficiently lookup documents by path. * 3. It creates a document map to efficiently lookup documents by path.
* 4. It then traverses each document: * 4. It then traverses each document modified in the PR and...
* - It checks if each internal link (links starting with "/docs/") points * - Checks if each internal link (links starting with "/docs/") points
* to an existing document * to an existing document
* - It validates hash links (links starting with "#") against the list of * - Validates hash links (links starting with "#") against the list of
* headings in the current document. * headings in the current document.
* - It checks the source and related links found in the metadata of each * - Checks the source and related links found in the metadata of each
* document. * document.
* 5. Any broken links discovered during these checks are categorized and a * 5. Any broken links discovered during these checks are categorized and a
* comment is added to the PR. * comment is added to the PR.
...@@ -63,7 +64,7 @@ const sha = pullRequest.head.sha ...@@ -63,7 +64,7 @@ const sha = pullRequest.head.sha
const slugger = new GithubSlugger() const slugger = new GithubSlugger()
// Recursively traverses DOCS_PATH and collects all .mdx files // Recursively traverses DOCS_PATH and collects all .mdx files
async function getMdxFiles( async function getAllMdxFiles(
dir: string, dir: string,
fileList: string[] = [] fileList: string[] = []
): Promise<string[]> { ): Promise<string[]> {
...@@ -74,7 +75,7 @@ async function getMdxFiles( ...@@ -74,7 +75,7 @@ async function getMdxFiles(
const stats = await fs.stat(filePath) const stats = await fs.stat(filePath)
if (stats.isDirectory()) { if (stats.isDirectory()) {
fileList = await getMdxFiles(filePath, fileList) fileList = await getAllMdxFiles(filePath, fileList)
} else if (path.extname(file) === '.mdx') { } else if (path.extname(file) === '.mdx') {
fileList.push(filePath) fileList.push(filePath)
} }
...@@ -83,6 +84,36 @@ async function getMdxFiles( ...@@ -83,6 +84,36 @@ async function getMdxFiles(
return fileList return fileList
} }
async function getFilesChangedInPR(): Promise<string[]> {
try {
const filesChanged = await octokit.rest.pulls.listFiles({
owner,
repo,
pull_number: pullRequest.number,
})
const mdxFilesChanged = filesChanged.data
.filter(
(file) =>
path.join('/', file.filename).startsWith(DOCS_PATH) &&
file.filename.endsWith('.mdx') &&
(file.status === 'added' || file.status === 'modified')
)
.map((file) => file.filename)
if (mdxFilesChanged.length === 0) {
console.log(
"PR doesn't include any changes to .mdx files within DOCS_PATH."
)
}
return mdxFilesChanged
} catch (error) {
setFailed(`Error fetching files changed in PR: ${error}`)
return []
}
}
// Returns the slugs of all headings in a tree // Returns the slugs of all headings in a tree
function getHeadingsFromMarkdownTree(tree: Node<Data>): string[] { function getHeadingsFromMarkdownTree(tree: Node<Data>): string[] {
const headings: string[] = [] const headings: string[] = []
...@@ -117,6 +148,17 @@ const markdownProcessor = unified() ...@@ -117,6 +148,17 @@ const markdownProcessor = unified()
} }
}) })
function normalizePath(filePath: string): string {
return (
path
.relative('.' + DOCS_PATH, filePath)
// Remove prefixed numbers used for ordering from the path
.replace(/(\d\d-)/g, '')
.replace('.mdx', '')
.replace('/index', '')
)
}
// use Map for faster lookup // use Map for faster lookup
let documentMap: Map<string, Document> let documentMap: Map<string, Document>
...@@ -125,20 +167,21 @@ let documentMap: Map<string, Document> ...@@ -125,20 +167,21 @@ let documentMap: Map<string, Document>
async function prepareDocumentMapEntry( async function prepareDocumentMapEntry(
filePath: string filePath: string
): Promise<[string, Document]> { ): Promise<[string, Document]> {
const relativePath = path.relative('.' + DOCS_PATH, filePath) try {
// Remove prefixed numbers used for ordering from the path
const normalizedPath = relativePath
.replace(/(\d\d-)/g, '')
.replace('.mdx', '')
.replace('/index', '')
const mdxContent = await fs.readFile(filePath, 'utf8') const mdxContent = await fs.readFile(filePath, 'utf8')
const { content, data } = matter(mdxContent) const { content, data } = matter(mdxContent)
const tree = markdownProcessor.parse(content) const tree = markdownProcessor.parse(content)
const headings = getHeadingsFromMarkdownTree(tree) const headings = getHeadingsFromMarkdownTree(tree)
const normalizedPath = normalizePath(filePath)
return [normalizedPath, { body: content, path: filePath, headings, ...data }] return [
normalizedPath,
{ body: content, path: filePath, headings, ...data },
]
} catch (error) {
setFailed(`Error preparing document map for file ${filePath}: ${error}`)
return ['', {} as Document] // Return a default document
}
} }
// Checks if the links point to existing documents // Checks if the links point to existing documents
...@@ -201,6 +244,7 @@ function traverseTreeAndValidateLinks(tree: any, doc: Document): Errors { ...@@ -201,6 +244,7 @@ function traverseTreeAndValidateLinks(tree: any, doc: Document): Errors {
brokenRelatedLinks: [], brokenRelatedLinks: [],
} }
try {
visit(tree, (node: any) => { visit(tree, (node: any) => {
if (node.type === 'element' && node.tagName === 'a') { if (node.type === 'element' && node.tagName === 'a') {
const href = node.properties.href const href = node.properties.href
...@@ -220,24 +264,33 @@ function traverseTreeAndValidateLinks(tree: any, doc: Document): Errors { ...@@ -220,24 +264,33 @@ function traverseTreeAndValidateLinks(tree: any, doc: Document): Errors {
validateSourceLinks(doc, errors) validateSourceLinks(doc, errors)
validateRelatedLinks(doc, errors) validateRelatedLinks(doc, errors)
} catch (error) {
setFailed('Error traversing tree: ' + error)
}
return errors return errors
} }
async function findBotComment(): Promise<Comment | undefined> { async function findBotComment(): Promise<Comment | undefined> {
try {
const { data: comments } = await octokit.rest.issues.listComments({ const { data: comments } = await octokit.rest.issues.listComments({
owner, owner,
repo, repo,
issue_number: context.payload.pull_request?.number!, issue_number: pullRequest.number,
}) })
return comments.find((c) => c.body?.includes(COMMENT_TAG)) return comments.find((c) => c.body?.includes(COMMENT_TAG))
} catch (error) {
setFailed('Error finding bot comment: ' + error)
return undefined
}
} }
async function updateComment( async function updateComment(
comment: string, comment: string,
botComment: Comment botComment: Comment
): Promise<string> { ): Promise<string> {
try {
const { data } = await octokit.rest.issues.updateComment({ const { data } = await octokit.rest.issues.updateComment({
owner, owner,
repo, repo,
...@@ -246,17 +299,26 @@ async function updateComment( ...@@ -246,17 +299,26 @@ async function updateComment(
}) })
return data.html_url return data.html_url
} catch (error) {
setFailed('Error updating comment: ' + error)
return ''
}
} }
async function createComment(comment: string): Promise<string> { async function createComment(comment: string): Promise<string> {
try {
const { data } = await octokit.rest.issues.createComment({ const { data } = await octokit.rest.issues.createComment({
owner, owner,
repo, repo,
issue_number: context.payload.pull_request?.number!, issue_number: pullRequest.number,
body: comment, body: comment,
}) })
return data.html_url return data.html_url
} catch (error) {
setFailed('Error creating comment: ' + error)
return ''
}
} }
const formatTableRow = (link: string, docPath: string) => { const formatTableRow = (link: string, docPath: string) => {
...@@ -283,20 +345,31 @@ async function createCommitStatus( ...@@ -283,20 +345,31 @@ async function createCommitStatus(
}) })
} }
// Main function that triggers link validation across all .mdx files // Main function that triggers link validation across .mdx files
async function validateAllInternalLinks(): Promise<void> { async function validateAllInternalLinks(): Promise<void> {
const mdxFilePaths = await getMdxFiles('.' + DOCS_PATH) try {
const allMdxFilePaths = await getAllMdxFiles('.' + DOCS_PATH)
const prMdxFilePaths = await getFilesChangedInPR()
documentMap = new Map( documentMap = new Map(
await Promise.all(mdxFilePaths.map(prepareDocumentMapEntry)) await Promise.all(allMdxFilePaths.map(prepareDocumentMapEntry))
) )
const docProcessingPromises = Array.from(documentMap.values()).map( const docProcessingPromises = prMdxFilePaths.map(async (filePath) => {
async (doc) => { const doc = documentMap.get(normalizePath(filePath))
if (doc) {
const tree = (await markdownProcessor.process(doc.body)).contents const tree = (await markdownProcessor.process(doc.body)).contents
return traverseTreeAndValidateLinks(tree, doc) return traverseTreeAndValidateLinks(tree, doc)
} else {
return {
doc: {} as Document,
brokenLinks: [],
brokenHashes: [],
brokenSourceLinks: [],
brokenRelatedLinks: [],
} as Errors
} }
) })
const allErrors = await Promise.all(docProcessingPromises) const allErrors = await Promise.all(docProcessingPromises)
...@@ -362,17 +435,16 @@ async function validateAllInternalLinks(): Promise<void> { ...@@ -362,17 +435,16 @@ async function validateAllInternalLinks(): Promise<void> {
const comment = `${COMMENT_TAG}\nAll broken links are now fixed, thank you!` const comment = `${COMMENT_TAG}\nAll broken links are now fixed, thank you!`
if (botComment) { if (botComment) {
commentUrl = await updateComment(comment, botComment) commentUrl = await updateComment(comment, botComment)
} else {
commentUrl = await createComment(comment)
} }
} }
console.log({ commentUrl, errorsExist, errorComment, botComment })
try { try {
await createCommitStatus(errorsExist, commentUrl) await createCommitStatus(errorsExist, commentUrl)
} catch (error) { } catch (error) {
console.error('Failed to create commit status: ', error) setFailed('Failed to create commit status: ' + error)
}
} catch (error) {
setFailed('Error validating internal links: ' + error)
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment