]> git.r.bdr.sh - rbdr/blog/blob - lib/archivers/gemlog.js
d50d411bc8af23a4ff7777181cabc7c72cb3bcfd
[rbdr/blog] / lib / archivers / gemlog.js
1 const { mkdir, readdir, rm, writeFile } = require('fs/promises');
2 const { debuglog, promisify } = require('util');
3 const { ncp } = require('ncp');
4 const { join } = require('path');
5
6 const internals = {
7 kArchiveName: '.gemlog',
8 kIndexName: 'index.gmi',
9 kGeminiRe: /\.gmi$/i,
10
11 ncp: promisify(ncp),
12 debuglog: debuglog('blog'),
13 };
14
15 module.exports = async function(archiveDirectory) {
16 internals.debuglog(`Reading archive ${archiveDirectory}`);
17 const postIds = await readdir(archiveDirectory)
18 const posts = [];
19 for (const id of postIds) {
20 const postDirectory = join(archiveDirectory, id);
21 const slug = (await readdir(postDirectory))
22 .filter((entry) => internals.kGeminiRe.test(entry))[0];
23
24 posts.push({ id, slug })
25 };
26
27 internals.debuglog(`Read ${posts.length} posts`);
28
29 const index = ['# Unlimited Pizza Gemlog Archive', '',
30 ...posts.map((post) => `=> ./${post.id}/${post.slug}`)].join('\n');
31
32 try {
33 internals.debuglog('Removing index');
34 await rm(internals.kArchiveName, { recursive: true });
35 }
36 finally {
37 internals.debuglog('Creating index');
38 await mkdir(internals.kArchiveName);
39 const indexFile = join(internals.kArchiveName, internals.kIndexName);
40 await writeFile(indexFile, index);
41
42 internals.debuglog('Copying posts to archive');
43 await internals.ncp(archiveDirectory, internals.kArchiveName);
44 }
45 };