-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
96 lines (78 loc) · 2.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* eslint no-console: 0 */
import path from "path";
import fs from "fs-extra";
import yaml from "yaml-front-matter";
import chalk from "chalk";
import cloneDeep from "lodash.clonedeep";
const REGEX_NEWLINES = /^\n+/;
const REGEX_NO_FOLDER = /^[^\/]+(\/index)?$/;
export default async function yamlMarkdownToHtml(cliParams) {
const files = cliParams.files || [];
const fileContents = await Promise.all(
files.map(getFileContents(cliParams.contentFolder))
);
const validFileContents = fileContents.filter(Boolean);
if (validFileContents.length === 0) {
console.log(chalk.green(`✅ no changed files`));
return;
}
const renderedFiles = await Promise.all(
validFileContents.map(
renderEachFile(cliParams.publicFolder, cliParams.renderFile)
)
);
await callPostRender(cliParams.postRenderFile, renderedFiles);
console.log(chalk.green(`✅ rendered ${renderedFiles.length} files`));
}
function getFileContents(markdownFolder) {
return async (filePath) => {
try {
const extension = path.extname(filePath);
const relativePath = path
.relative(markdownFolder, filePath)
.replace(new RegExp(extension + "$"), "");
console.log(chalk.blue("👓 reading " + filePath));
const contents = await fs.readFile(filePath, "utf-8");
const data = yaml.loadFront(contents, "markdown");
data.markdown = data.markdown.replace(REGEX_NEWLINES, "");
data.path = relativePath;
return data;
} catch (error) {
console.error(`⏩ skipped ${filePath}: ${error}`);
return false;
}
};
}
function renderEachFile(htmlFolder, renderFunction) {
return async (file, _, allFiles) => {
const currentFolder = path.join(file.path, "..");
const folderPattern =
currentFolder === "."
? REGEX_NO_FOLDER
: new RegExp("^" + currentFolder + "/[^/]+(/index)?$");
const filesInCurrentFolder = allFiles.filter(function (testedFile) {
return (
folderPattern.test(testedFile.path) && testedFile.path !== file.path
);
});
const destinationPath = path.join(htmlFolder, file.path + ".html");
const clonedFile = cloneDeep(file);
console.log(chalk.cyan("⚙️ rendering " + file.path));
const renderedHtml = await renderFunction.default(
clonedFile,
cloneDeep(filesInCurrentFolder),
cloneDeep(allFiles)
);
console.log(chalk.yellow("🖨 writing " + clonedFile.path));
await fs.outputFile(destinationPath, renderedHtml);
clonedFile.renderedPath = destinationPath;
return clonedFile;
};
}
async function callPostRender(postRenderFunction, renderedFiles) {
if (typeof postRenderFunction.default === "function") {
console.log(chalk.yellow("🏁 calling post render"));
postRenderFunction.default(cloneDeep(renderedFiles));
}
return renderedFiles;
}