-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
112 lines (90 loc) · 2.69 KB
/
build.js
File metadata and controls
112 lines (90 loc) · 2.69 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const fs = require("fs");
const path = require("path");
const showdown = require("showdown");
const handlebars = require("handlebars");
const matter = require("gray-matter");
// create docs if it doesn't exist
if (!fs.existsSync("docs")) {
fs.mkdirSync("docs");
}
const postsDir = path.join(__dirname, "posts");
const docsDir = path.join(__dirname, "docs");
const converter = new showdown.Converter({
ghCodeBlocks: true, // Enables fenced code blocks
tables: true, // Enables GitHub-style tables
});
const postTemplateHtml = fs.readFileSync(
path.join(__dirname, "post.template.html"),
"utf8",
);
const template = handlebars.compile(postTemplateHtml);
let posts = [];
try {
const files = fs.readdirSync(postsDir);
files.forEach((file) => {
if (path.extname(file) === ".md") {
const filePath = path.join(postsDir, file);
const fileName = `${path.basename(file, ".md")}.html`;
const markdownContent = fs.readFileSync(filePath, "utf8");
const { data, content } = matter(markdownContent);
const article = converter.makeHtml(content);
const html = template({ article, title: data.title });
switch (data.status) {
case "published": {
posts.push({ ...data, fileName });
fs.writeFileSync(path.join(docsDir, fileName), html);
break;
}
case "draft": {
// if the file exists, delete it
if (fs.existsSync(path.join(docsDir, fileName))) {
fs.unlinkSync(path.join(docsDir, fileName));
}
break;
}
case "unlisted": {
fs.writeFileSync(path.join(docsDir, fileName), html);
break;
}
default: {
break;
}
}
}
});
} catch (err) {
console.error({ err });
return;
}
//
// Generate index.html
//
// Make newest posts appear first
const sortByDate = (a, b) => new Date(b.date) - new Date(a.date);
// List the published posts in index.html
const createPostListItem = (post) => {
const description = converter.makeHtml(post.description);
return `
<li>
<fieldset>
<legend>${post.date.toISOString().split("T").at(0)}</legend>
<h3>${post.title}</h3>
${description}
<a href="${post.fileName}" class="button-link">Read post</a>
</fieldset>
</li>
`;
};
try {
const postsHtml = posts.toSorted(sortByDate).map(createPostListItem).join("");
const indexTemplateHtml = fs.readFileSync(
path.join(__dirname, "index.template.html"),
"utf8",
);
const indexTemplate = handlebars.compile(indexTemplateHtml);
const indexHtml = indexTemplate({ posts: postsHtml });
fs.writeFileSync(path.join(docsDir, "index.html"), indexHtml);
} catch (err) {
console.error(err);
return;
}