in scripts/link-checker.js [112:187]
function scanLinkInMDFile(filePath, project) {
const fileContent = fs.readFileSync(filePath, 'utf-8');
const regex = /\[[\s\S]*?\]\([\s\S]*?\)/g;
if (fileContent.match(regex)) {
const arrayOfLinks = fileContent.match(regex);
const links = arrayOfLinks.map((item) => {
const textHrefDivide = item.split('](');
const text = textHrefDivide[0].replace('[', '');
const url = textHrefDivide[1].replace(')', '');
return ({ url, text, file: filePath });
});
// filter out links to other Markdown files
const filteredList = []; // local files
const unfilteredList = links.filter((link) => { // web links
let url = link.url.trim();
if (url.startsWith('http://') || url.startsWith('https://')) {
// eslint-disable-next-line no-param-reassign
link.url = url;
return true;
}
// url preprocess
if (url.startsWith('#') || url.indexOf('#') > 0) { // such as "#abcd"
const split = url.split('#').filter((item) => item !== '');
if (split.length > 1) {
// eslint-disable-next-line no-param-reassign
link.anchor = `#${split[1]}`;
url = path.normalize(path.dirname(filePath) + path.sep + link.url);
} else {
// eslint-disable-next-line no-param-reassign
link.anchor = link.url;
url = filePath;
}
} else if (url === 'LICENSE' || url === 'logos/apache-apisix.png') {
url = `https://github.com/apache/${project}/blob/master/${url}`;
} else if (!url.endsWith('.md')) { // not end with ".md"
console.log(filePath, link.url, url, filePath.startsWith('website\\docs'));
const lang = !filePath.includes('i18n') ? 'en' : filePath.split(`i18n${path.sep}`)[1].split(path.sep)[0];
let subPath = !filePath.includes('i18n') ? path.dirname(filePath.split(`docs${path.sep}${project}${path.sep}`)[1]) : path.dirname(filePath.split(`docs-${project}${path.sep}current${path.sep}`)[1]);
subPath = subPath !== '.' ? subPath + path.sep : '';
const originPath = path.normalize(`docs${path.sep}${lang}${path.sep}latest${path.sep}${subPath}${url}`).replace(/\\/g, '/');
url = `https://github.com/apache/${project}/blob/master/${originPath}`;
} else { // such as "./abcd", "../abcd", "../../../abcd"
url = path.normalize(path.dirname(filePath) + path.sep + url);
}
// set url
const originLink = link.url;
// eslint-disable-next-line no-param-reassign
link.url = url;
// url postprocess
if (!url.startsWith('http://') && !url.startsWith('https://')) {
filteredList.push(link);
return false;
}
// replace the converted link with the original document
let documentContent = fs.readFileSync(filePath, 'utf8');
documentContent = documentContent.replace(new RegExp(originLink, 'g'), link.url);
fs.writeFileSync(filePath, documentContent, 'utf8');
return true;
});
return {
links: unfilteredList,
filteredLinks: filteredList,
};
}
return {
links: [],
filteredLinks: [],
};
}