]> git.r.bdr.sh - rbdr/blog/blob - lib/archivers/gemlog.js
Remove bin and config files
[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
15 return `./${id}/${slug}`;
16 },
17
18 buildTitle(id, slug) {
19
20 const date = new Date(Number(id));
21 const shortDate = date.toISOString().split('T')[0];
22 const title = slug.split('-').join(' ');
23 return `${shortDate} ${title}`;
24 },
25
26 buildLink(id, slug) {
27
28 return `=> ${internals.buildUrl(id,slug)} ${internals.buildTitle(id,slug)}`;
29 }
30 };
31
32 export default async function (templateDirectory, source, target) {
33
34 internals.debuglog(`Reading archive ${source}`);
35 const postIds = (await readdir(source))
36 .sort((a, b) => Number(b) - Number(a));
37 const posts = [];
38 for (const id of postIds) {
39 const postDirectory = join(source, id);
40 const slug = (await readdir(postDirectory))
41 .filter((entry) => internals.kGeminiRe.test(entry))[0];
42
43 posts.push({ id, slug });
44 }
45
46 internals.debuglog(`Read ${posts.length} posts`);
47
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 })({
59 posts: posts.map((post) => internals.buildLink(post.id, post.slug)).join('\n')
60 });
61
62 try {
63 internals.debuglog('Removing index');
64 await rmIfExists(target);
65 }
66 finally {
67 internals.debuglog('Creating index');
68 await mkdir(target);
69 const indexFile = join(target, internals.kIndexName);
70 await writeFile(indexFile, index);
71
72 internals.debuglog('Copying posts to archive');
73 await cp(source, target, { recursive: true });
74 }
75 }