]>
git.r.bdr.sh - rbdr/blog/blob - lib/blog.js
27a440e651bbb485c4091a4e8de5ef5100e930f7
3 const { access
, mkdir
, readdir
, readFile
, rmdir
, writeFile
} = require('fs/promises');
4 const { ncp
} = require('ncp');
5 const { join
} = require('path');
6 const Marked
= require('marked');
7 const { debuglog
, promisify
} = require('util');
9 const StaticGenerator
= require('./generators/static');
10 const HTMLGenerator
= require('./generators/html');
11 const RSSGenerator
= require('./generators/rss');
12 const TXTGenerator
= require('./generators/txt');
16 // Promisified functions
19 debuglog: debuglog('blog'),
23 kFileNotFoundError: 'ENOENT',
24 kMarkdownRe: /\.md$/i,
25 kMetadataFilename: 'metadata.json',
30 markdownNotFound: 'Markdown file was not found in blog directory. Please update.'
35 * The Blog class is the blog generator, it's in charge of adding and
36 * updating posts, and handling the publishing.
39 * @param {Blog.tConfiguration} config the initialization options to
42 module
.exports
= class Blog
{
46 Object
.assign(this, config
);
50 * Shifts the blog posts, adds the passed path to slot 0, and
55 * @param {string} postLocation the path to the directory containing
57 * @return {Promise<undefined>} empty promise, returns no value
60 async
add(postLocation
) {
62 await
this._ensurePostsDirectoryExists();
64 await
this.update(postLocation
);
68 * Adds the passed path to slot 0, and generates files.
72 * @param {string} postLocation the path to the directory containing
74 * @return {Promise<undefined>} empty promise, returns no value
77 async
update(postLocation
) {
79 const metadata
= await
this._getMetadata();
80 await
this._ensurePostsDirectoryExists();
81 await
this._copyPost(postLocation
);
82 await
this._writeMetadata(metadata
);
84 await
this.generate();
88 * Publishes the files to a static host.
92 * @return {Promise<undefined>} empty promise, returns no value
97 console
.error('Publishing not yet implemented');
98 return Promise
.resolve();
101 // Parses markdown for each page, copies assets and generates index.
105 internals
.debuglog('Generating output');
107 const posts
= await
this._readPosts(this.postsDirectory
);
109 await
StaticGenerator(this.postsDirectory
, this.staticDirectory
, posts
);
110 await
HTMLGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
111 await
RSSGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
112 await
TXTGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
115 // Reads the posts into an array
117 async
_readPosts(source
) {
119 internals
.debuglog('Reading posts');
122 for (let i
= 0; i
< this.maxPosts
; ++i
) {
123 const postSourcePath
= join(source
, `${i}`);
125 internals
.debuglog(`Reading ${postSourcePath} into posts array`);
128 await
access(postSourcePath
);
130 const metadata
= await
this._getMetadata(i
);
132 const postContentPath
= await
this._findBlogContent(postSourcePath
);
133 internals
.debuglog(`Reading ${postContentPath}`);
134 const postContent
= await
readFile(postContentPath
, { encoding: 'utf8' });
136 internals
.debuglog('Parsing markdown');
140 html: Marked(postContent
),
145 if (error
.code
=== internals
.kFileNotFoundError
) {
146 internals
.debuglog(`Skipping ${i}`);
157 // Shift the posts, delete any remainder.
162 for (let i
= this.maxPosts
- 1; i
>= 0; --i
) {
163 const targetPath
= join(this.postsDirectory
, `${i}`);
164 const sourcePath
= join(this.postsDirectory
, `${i - 1}`);
167 internals
.debuglog(`Removing ${targetPath}`);
168 await
rmdir(targetPath
, { recursive: true });
170 await
access(sourcePath
); // check the source path
172 internals
.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
173 await internals
.ncp(sourcePath
, targetPath
);
176 if (error
.code
=== internals
.kFileNotFoundError
) {
177 internals
.debuglog(`Skipping ${sourcePath}: Does not exist.`);
186 // Attempts to read existing metadata. Otherwise generates new set.
188 async
_getMetadata(index
= 0) {
190 const metadataTarget
= join(this.postsDirectory
, String(index
), internals
.kMetadataFilename
);
193 internals
.debuglog(`Looking for metadata at ${metadataTarget}`);
194 return JSON
.parse(await
readFile(metadataTarget
, { encoding: 'utf8' }));
197 internals
.debuglog(`Metadata not found or unreadable. Generating new set.`);
198 const createdOn
= Date
.now();
200 id: String(createdOn
),
208 // Writes metadata. Assumes post 0 since it only gets written
211 async
_writeMetadata(metadata
) {
213 const metadataTarget
= join(this.postsDirectory
, '0', internals
.kMetadataFilename
);
214 internals
.debuglog(`Writing ${metadataTarget}`);
215 await
writeFile(metadataTarget
, JSON
.stringify(metadata
, null, 2));
218 // Copies a post directory to the latest slot.
220 async
_copyPost(postLocation
) {
222 const targetPath
= join(this.postsDirectory
, '0');
224 internals
.debuglog(`Removing ${targetPath}`);
225 await
rmdir(targetPath
, { recursive: true });
227 internals
.debuglog(`Adding ${postLocation} to ${targetPath}`);
228 await internals
.ncp(postLocation
, targetPath
);
231 // Ensures the posts directory exists.
233 async
_ensurePostsDirectoryExists() {
235 internals
.debuglog(`Checking if ${this.postsDirectory} exists.`);
237 await
access(this.postsDirectory
);
240 if (error
.code
=== internals
.kFileNotFoundError
) {
241 internals
.debuglog('Creating posts directory');
242 await
mkdir(this.postsDirectory
);
250 // Looks for a `.md` file in the blog directory, and returns the path
252 async
_findBlogContent(directory
) {
254 const entries
= await
readdir(directory
);
256 const markdownEntries
= entries
257 .filter((entry
) => internals
.kMarkdownRe
.test(entry
))
258 .map((entry
) => join(directory
, entry
));
260 if (markdownEntries
.length
> 0) {
261 internals
.debuglog(`Found markdown file: ${markdownEntries[0]}`);
262 return markdownEntries
[0];
265 throw new Error(internals
.strings
.markdownNotFound
);