Skip to content

Instantly share code, notes, and snippets.

@jmerle
Created August 5, 2019 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmerle/027a6276d447063ad067e51273c427d9 to your computer and use it in GitHub Desktop.
Save jmerle/027a6276d447063ad067e51273c427d9 to your computer and use it in GitHub Desktop.
Parsing the Markdown files in https://github.com/docker/docker.github.io to extract the redirect_from url's for use in DevDocs
const fs = require('fs');
const path = require('path');
const fg = require('fast-glob');
const fm = require('front-matter');
(async () => {
const files = await fg('**/*.md');
const redirects = {};
for (const file of files) {
const content = await fs.promises.readFile(file, 'utf-8');
const data = fm(content);
const redirectFrom = data.attributes.redirect_from;
if (redirectFrom === undefined || redirectFrom === null) {
continue;
}
const redirectTo = path.dirname(file);
if (redirectTo.includes('.')) {
continue;
}
const urls = Array.isArray(redirectFrom) ? redirectFrom : [redirectFrom];
for (const url of urls) {
const urlWithSlash = url.substring(1) + (url.endsWith('/') ? '' : '/');
const urlWithoutSlash = urlWithSlash.substring(0, urlWithSlash.length - 1);
if (urlWithSlash === redirectTo || urlWithoutSlash === redirectTo) {
continue;
}
redirects[urlWithSlash] = redirectTo;
redirects[urlWithoutSlash] = redirectTo;
}
}
for (const url of Object.keys(redirects).sort().reverse()) {
console.log(`'${url}' => '${redirects[url]}',`);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment