]>
git.r.bdr.sh - rbdr/blog/blob - lib/blog.js
ff52554a07ed5faa44c817f4e12bceb35f7ee539
3 const { access
, mkdir
, readdir
, readFile
, rm
, writeFile
} = require('fs/promises');
4 const { exec
} = require('child_process');
5 const { ncp
} = require('ncp');
6 const { resolve
, join
} = require('path');
7 const ParseGemini
= require('gemini-to-html/parse');
8 const RenderGemini
= require('gemini-to-html/render');
9 const { debuglog
, promisify
} = require('util');
11 // Generators for the Blog
13 const StaticGenerator
= require('./generators/static');
14 const HTMLGenerator
= require('./generators/html');
15 const RSSGenerator
= require('./generators/rss');
16 const TXTGenerator
= require('./generators/txt');
20 const GemlogArchiver
= require('./archivers/gemlog');
24 // Promisified functions
25 exec: promisify(exec
),
28 debuglog: debuglog('blog'),
32 kFileNotFoundError: 'ENOENT',
34 kMetadataFilename: 'metadata.json',
39 geminiNotFound: 'Gemini file was not found in blog directory. Please update.'
44 * The Blog class is the blog generator, it's in charge of adding and
45 * updating posts, and handling the publishing.
48 * @param {Blog.tConfiguration} config the initialization options to
51 module
.exports
= class Blog
{
55 Object
.assign(this, config
);
59 * Shifts the blog posts, adds the passed path to slot 0, and
64 * @param {string} postLocation the path to the directory containing
66 * @return {Promise<undefined>} empty promise, returns no value
69 async
add(postLocation
) {
71 await
this._ensurePostsDirectoryExists();
73 await
mkdir(join(this.postsDirectory
, '0'));
74 await
this.update(postLocation
);
78 * Adds the passed path to slot 0, and generates files.
82 * @param {string} postLocation the path to the directory containing
84 * @return {Promise<undefined>} empty promise, returns no value
87 async
update(postLocation
) {
89 const metadata
= await
this._getMetadata();
90 await
this._ensurePostsDirectoryExists();
91 await
this._copyPost(postLocation
);
92 await
this._writeMetadata(metadata
);
94 await
this._archive(postLocation
);
96 await
this.generate();
100 * Publishes the files to a static host.
104 * @return {Promise<undefined>} empty promise, returns no value
107 async
publish(bucket
) {
109 internals
.debuglog(`Publishing to ${bucket}`);
111 await internals
.exec('which aws');
114 console
.error('Please install and configure AWS CLI to publish.');
118 await internals
.exec(`aws s3 sync --acl public-read --delete ${this.staticDirectory} s3://${bucket}`);
119 await internals
.exec(`aws s3 cp --content-type 'text/plain; charset=utf-8 ' --acl public-read ${this.staticDirectory}/index.txt s3://${bucket}`);
122 console
.error('Failed to publish');
123 console
.error(err
.stderr
);
126 internals
.debuglog('Finished publishing');
130 * Publishes the archive to a host using rsync. Currently assumes
133 * @function publishArchive
135 * @return {Promise<undefined>} empty promise, returns no value
138 async
publishArchive(host
) {
140 internals
.debuglog(`Publishing archive to ${host}`);
142 await internals
.exec('which rsync');
145 console
.error('Please install rsync to publish the archive.');
149 const gemlogPath
= resolve(join(__dirname
, '../', '.gemlog'));
150 internals
.debuglog(`Reading archive from ${gemlogPath}`);
151 await internals
.exec(`rsync -r ${gemlogPath}/ ${host}`);
154 console
.error('Failed to publish archive');
155 console
.error(err
.stderr
);
158 internals
.debuglog('Finished publishing');
161 // Parses Gemini for each page, copies assets and generates index.
165 internals
.debuglog('Generating output');
167 const posts
= await
this._readPosts();
169 await
StaticGenerator(this.postsDirectory
, this.staticDirectory
, posts
);
170 await
HTMLGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
171 await
RSSGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
172 await
TXTGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
174 await
GemlogArchiver(this.archiveDirectory
);
177 // Reads the posts into an array
181 internals
.debuglog('Reading posts');
184 for (let i
= 0; i
< this.maxPosts
; ++i
) {
186 posts
.push(await
this._readPost(i
));
189 if (error
.code
=== internals
.kFileNotFoundError
) {
190 internals
.debuglog(`Skipping ${i}`);
201 // Reads an individual post
203 async
_readPost(index
=0) {
204 const postSourcePath
= join(this.postsDirectory
, `${index}`);
206 internals
.debuglog(`Reading ${postSourcePath}`);
208 await
access(postSourcePath
);
210 const metadata
= await
this._getMetadata(index
);
212 const postContentPath
= await
this._findBlogContent(postSourcePath
);
213 internals
.debuglog(`Reading ${postContentPath}`);
214 const postContent
= await
readFile(postContentPath
, { encoding: 'utf8' });
216 internals
.debuglog('Parsing Gemini');
219 location: postSourcePath
,
221 html: RenderGemini(ParseGemini(postContent
)),
226 // Shift the posts, delete any remainder.
231 for (let i
= this.maxPosts
- 1; i
>= 0; --i
) {
232 const targetPath
= join(this.postsDirectory
, `${i}`);
233 const sourcePath
= join(this.postsDirectory
, `${i - 1}`);
236 internals
.debuglog(`Archiving ${targetPath}`);
237 await
rm(targetPath
, { recursive: true });
239 await
access(sourcePath
); // check the source path
241 internals
.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
242 await internals
.ncp(sourcePath
, targetPath
);
245 if (error
.code
=== internals
.kFileNotFoundError
) {
246 internals
.debuglog(`Skipping ${sourcePath}: Does not exist.`);
255 // Moves older posts to the archive
258 internals
.debuglog('Archiving post');
259 const post
= await
this._readPost(0);
260 await
this._ensureDirectoryExists(this.archiveDirectory
);
262 const targetPath
= join(this.archiveDirectory
, post
.id
);
265 internals
.debuglog(`Removing ${targetPath}`);
266 await
rm(targetPath
, { recursive: true });
269 internals
.debuglog(`Adding ${post.location} to ${targetPath}`);
270 await internals
.ncp(post
.location
, targetPath
);
271 internals
.debuglog(`Added ${post.location} to ${targetPath}`);
275 // Attempts to read existing metadata. Otherwise generates new set.
277 async
_getMetadata(index
= 0) {
279 const metadataTarget
= join(this.postsDirectory
, String(index
), internals
.kMetadataFilename
);
282 internals
.debuglog(`Looking for metadata at ${metadataTarget}`);
283 return JSON
.parse(await
readFile(metadataTarget
, { encoding: 'utf8' }));
286 internals
.debuglog(`Metadata not found or unreadable. Generating new set.`);
287 const createdOn
= Date
.now();
289 id: String(createdOn
),
297 // Writes metadata. Assumes post 0 since it only gets written
300 async
_writeMetadata(metadata
) {
302 const metadataTarget
= join(this.postsDirectory
, '0', internals
.kMetadataFilename
);
303 internals
.debuglog(`Writing ${metadataTarget}`);
304 await
writeFile(metadataTarget
, JSON
.stringify(metadata
, null, 2));
307 // Copies a post directory to the latest slot.
309 async
_copyPost(postLocation
) {
311 const targetPath
= join(this.postsDirectory
, '0');
313 internals
.debuglog(`Removing ${targetPath}`);
314 await
rm(targetPath
, { recursive: true });
316 internals
.debuglog(`Adding ${postLocation} to ${targetPath}`);
317 await internals
.ncp(postLocation
, targetPath
);
320 // Ensures a directory exists.
322 async
_ensureDirectoryExists(directory
) {
324 internals
.debuglog(`Checking if ${directory} exists.`);
326 await
access(directory
);
329 if (error
.code
=== internals
.kFileNotFoundError
) {
330 internals
.debuglog('Creating posts directory');
331 await
mkdir(directory
);
339 // Ensures posts directory exists
341 async
_ensurePostsDirectoryExists() {
343 return this._ensureDirectoryExists(this.postsDirectory
);
344 internals
.debuglog(`Checking if ${this.postsDirectory} exists.`);
346 await
access(this.postsDirectory
);
349 if (error
.code
=== internals
.kFileNotFoundError
) {
350 internals
.debuglog('Creating posts directory');
351 await
mkdir(this.postsDirectory
);
359 // Looks for a `.gmi` file in the blog directory, and returns the path
361 async
_findBlogContent(directory
) {
363 const entries
= await
readdir(directory
);
365 const geminiEntries
= entries
366 .filter((entry
) => internals
.kGeminiRe
.test(entry
))
367 .map((entry
) => join(directory
, entry
));
369 if (geminiEntries
.length
> 0) {
370 internals
.debuglog(`Found gemini file: ${geminiEntries[0]}`);
371 return geminiEntries
[0];
374 throw new Error(internals
.strings
.geminiNotFound
);