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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
|
'use strict';
const { access, mkdir, readdir, readFile, rmdir, writeFile } = require('fs/promises');
const { ncp } = require('ncp');
const { join } = require('path');
const Marked = require('marked');
const { debuglog, promisify } = require('util');
const StaticGenerator = require('./generators/static');
const HTMLGenerator = require('./generators/html');
const RSSGenerator = require('./generators/rss');
const TXTGenerator = require('./generators/txt');
const internals = {
// Promisified functions
ncp: promisify(ncp),
debuglog: debuglog('blog'),
// constants
kFileNotFoundError: 'ENOENT',
kMarkdownRe: /\.md$/i,
kMetadataFilename: 'metadata.json',
// Strings
strings: {
markdownNotFound: 'Markdown file was not found in blog directory. Please update.'
}
};
/**
* The Blog class is the blog generator, it's in charge of adding and
* updating posts, and handling the publishing.
*
* @class Blog
* @param {Blog.tConfiguration} config the initialization options to
* extend the instance
*/
module.exports = class Blog {
constructor(config) {
Object.assign(this, config);
}
/**
* Shifts the blog posts, adds the passed path to slot 0, and
* generates files.
*
* @function add
* @memberof Blog
* @param {string} postLocation the path to the directory containing
* the post structure
* @return {Promise<undefined>} empty promise, returns no value
* @instance
*/
async add(postLocation) {
await this._ensurePostsDirectoryExists();
await this._shift();
await this.update(postLocation);
}
/**
* Adds the passed path to slot 0, and generates files.
*
* @function update
* @memberof Blog
* @param {string} postLocation the path to the directory containing
* the post structure
* @return {Promise<undefined>} empty promise, returns no value
* @instance
*/
async update(postLocation) {
const metadata = await this._getMetadata();
await this._ensurePostsDirectoryExists();
await this._copyPost(postLocation);
await this._writeMetadata(metadata);
await this._generate();
}
/**
* Publishes the files to a static host.
*
* @function publish
* @memberof Blog
* @return {Promise<undefined>} empty promise, returns no value
* @instance
*/
publish() {
console.error('Publishing not yet implemented');
return Promise.resolve();
}
// Parses markdown for each page, copies assets and generates index.
async _generate() {
internals.debuglog('Generating output');
const posts = await this._readPosts(this.postsDirectory);
await StaticGenerator(this.postsDirectory, this.staticDirectory, posts);
await HTMLGenerator(this.templatesDirectory, this.staticDirectory, posts);
await RSSGenerator(this.templatesDirectory, this.staticDirectory, posts);
await TXTGenerator(this.templatesDirectory, this.staticDirectory, posts);
}
// Reads the posts into an array
async _readPosts(source) {
internals.debuglog('Reading posts');
const posts = [];
for (let i = 0; i < this.maxPosts; ++i) {
const postSourcePath = join(source, `${i}`);
internals.debuglog(`Reading ${postSourcePath} into posts array`);
try {
await access(postSourcePath);
const metadata = await this._getMetadata(i);
const postContentPath = await this._findBlogContent(postSourcePath);
internals.debuglog(`Reading ${postContentPath}`);
const postContent = await readFile(postContentPath, { encoding: 'utf8' });
internals.debuglog('Parsing markdown');
posts.push({
...metadata,
html: Marked(postContent),
raw: postContent
});
}
catch (error) {
if (error.code === internals.kFileNotFoundError) {
internals.debuglog(`Skipping ${i}`);
continue;
}
throw error;
}
}
return posts;
}
// Shift the posts, delete any remainder.
async _shift() {
for (let i = this.maxPosts - 1; i >= 0; --i) {
const targetPath = join(this.postsDirectory, `${i}`);
const sourcePath = join(this.postsDirectory, `${i - 1}`);
try {
internals.debuglog(`Removing ${targetPath}`);
await rmdir(targetPath, { recursive: true });
await access(sourcePath); // check the source path
internals.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
await internals.ncp(sourcePath, targetPath);
}
catch (error) {
if (error.code === internals.kFileNotFoundError) {
internals.debuglog(`Skipping ${sourcePath}: Does not exist.`);
continue;
}
throw error;
}
}
}
// Attempts to read existing metadata. Otherwise generates new set.
async _getMetadata(index = 0) {
const metadataTarget = join(this.postsDirectory, String(index), internals.kMetadataFilename);
try {
internals.debuglog(`Looking for metadata at ${metadataTarget}`);
return JSON.parse(await readFile(metadataTarget, { encoding: 'utf8' }));
}
catch (e) {
internals.debuglog(`Metadata not found or unreadable. Generating new set.`);
const createdOn = Date.now();
const metadata = {
id: String(createdOn),
createdOn
};
return metadata;
}
}
// Writes metadata. Assumes post 0 since it only gets written
// on create
async _writeMetadata(metadata) {
const metadataTarget = join(this.postsDirectory, '0', internals.kMetadataFilename);
internals.debuglog(`Writing ${metadataTarget}`);
await writeFile(metadataTarget, JSON.stringify(metadata, null, 2));
}
// Copies a post directory to the latest slot.
async _copyPost(postLocation) {
const targetPath = join(this.postsDirectory, '0');
internals.debuglog(`Removing ${targetPath}`);
await rmdir(targetPath, { recursive: true });
internals.debuglog(`Adding ${postLocation} to ${targetPath}`);
await internals.ncp(postLocation, targetPath);
}
// Ensures the posts directory exists.
async _ensurePostsDirectoryExists() {
internals.debuglog(`Checking if ${this.postsDirectory} exists.`);
try {
await access(this.postsDirectory);
}
catch (error) {
if (error.code === internals.kFileNotFoundError) {
internals.debuglog('Creating posts directory');
await mkdir(this.postsDirectory);
return;
}
throw error;
}
}
// Looks for a `.md` file in the blog directory, and returns the path
async _findBlogContent(directory) {
const entries = await readdir(directory);
const markdownEntries = entries
.filter((entry) => internals.kMarkdownRe.test(entry))
.map((entry) => join(directory, entry));
if (markdownEntries.length > 0) {
internals.debuglog(`Found markdown file: ${markdownEntries[0]}`);
return markdownEntries[0];
}
throw new Error(internals.strings.markdownNotFound);
}
};
|