Skip to content

Instantly share code, notes, and snippets.

@ajs139
Last active June 10, 2021 04:03
Show Gist options
  • Save ajs139/659ce8b37f5ab1c112d1b59ab6c66013 to your computer and use it in GitHub Desktop.
Save ajs139/659ce8b37f5ab1c112d1b59ab6c66013 to your computer and use it in GitHub Desktop.
const fs = require("fs");
const path = require("path");
function findInDir(dir, filter, fileList = []) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
const filePath = path.join(dir, file);
const fileStat = fs.lstatSync(filePath);
if (fileStat.isDirectory()) {
findInDir(filePath, filter, fileList);
} else if (filter.test(filePath)) {
fileList.push(filePath);
}
});
return fileList;
}
function getAndRemoveConfig(str = "") {
const config = {};
if (str) {
str = str
.replace(/^'/, "")
.replace(/'$/, "")
.replace(/(?:^|\s):([\w-]+:?)=?([\w-%]+)?/g, (m, key, value) => {
if (key.indexOf(":") === -1) {
config[key] = (value && value.replace(/"/g, "")) || true;
return "";
}
return m;
})
.trim();
}
return { str, config };
}
const referencedFilePaths = findInDir("./docs", /\.md$/).reduce(
(sourceLinkPaths, filePath) => {
const regex = /\[([^\[]+)\]\(([^\)]*)\)/gm;
const content = fs.readFileSync(filePath, "utf8");
// [filename](/Main.java ':include :type=code :fragment=main')
[...content.matchAll(regex)].forEach(([_, __, link]) => {
const { str, config } = getAndRemoveConfig(link);
if (config.fragment) {
const linkPath = link.replace(/'.*'/, "").trim();
if (fs.existsSync(path.join(__dirname, linkPath))) {
sourceLinkPaths.add(linkPath);
}
}
});
return sourceLinkPaths;
},
new Set()
);
[...referencedFilePaths].forEach((filePath) => {
const dir = path.dirname(filePath);
fs.mkdirSync(path.join(__dirname, "docs", dir), { recursive: true });
fs.copyFileSync(
path.join(__dirname, filePath),
path.join(__dirname, "docs", filePath)
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment