]> git.r.bdr.sh - rbdr/blog/blob - lib/archivers/gemlog.js
d56a1f6d4c647f45609f34118d943aa24743b1a8
[rbdr/blog] / lib / archivers / gemlog.js
1 import Dot from 'dot';
2 import { cp, mkdir, readdir, readFile, writeFile } from 'fs/promises';
3 import { debuglog } from 'util';
4 import { join } from 'path';
5 import { rmIfExists } from '../utils.js';
6
7 const internals = {
8 kIndexName: 'index.gmi',
9 kGeminiRe: /\.gmi$/i,
10
11 debuglog: debuglog('blog'),
12
13 buildUrl(id, slug) {
14 return `./${id}/${slug}`;
15 },
16
17 buildTitle (id, slug) {
18 const date = new Date(Number(id));
19 const shortDate = date.toISOString().split('T')[0]
20 const title = slug.split('-').join(' ');
21 return `${shortDate} ${title}`
22 },
23
24 buildLink(id, slug) {
25 return `=> ${internals.buildUrl(id,slug)} ${internals.buildTitle(id,slug)}`;
26 }
27 };
28
29 export default async function(templateDirectory, source, target) {
30 internals.debuglog(`Reading archive ${source}`);
31 const postIds = (await readdir(source))
32 .sort((a, b) => Number(b) - Number(a));
33 const posts = [];
34 for (const id of postIds) {
35 const postDirectory = join(source, id);
36 const slug = (await readdir(postDirectory))
37 .filter((entry) => internals.kGeminiRe.test(entry))[0];
38
39 posts.push({ id, slug })
40 };
41
42 internals.debuglog(`Read ${posts.length} posts`);
43
44 internals.debuglog('Generating Archive Index');
45 const indexLocation = join(templateDirectory, internals.kIndexName);
46
47 internals.debuglog(`Reading ${indexLocation}`);
48 const indexTemplate = await readFile(indexLocation, { encoding: 'utf8' });
49
50 internals.debuglog('Writing Archive Index');
51 const index = Dot.template(indexTemplate, {
52 ...Dot.templateSettings,
53 strip: false
54 })({
55 posts: posts.map((post) => internals.buildLink(post.id, post.slug)).join('\n'),
56 });
57
58 try {
59 internals.debuglog('Removing index');
60 await rmIfExists(target);
61 }
62 finally {
63 internals.debuglog('Creating index');
64 await mkdir(target);
65 const indexFile = join(target, internals.kIndexName);
66 await writeFile(indexFile, index);
67
68 internals.debuglog('Copying posts to archive');
69 await cp(source, target, { recursive: true });
70 }
71 };