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