]>
Commit | Line | Data |
---|---|---|
6cd62e79 RBR |
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'; | |
fac54389 RBR |
6 | |
7 | const internals = { | |
fac54389 RBR |
8 | kIndexName: 'index.gmi', |
9 | kGeminiRe: /\.gmi$/i, | |
10 | ||
fac54389 | 11 | debuglog: debuglog('blog'), |
65d379f5 RBR |
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 | } | |
fac54389 RBR |
27 | }; |
28 | ||
6cd62e79 RBR |
29 | export default async function(templateDirectory, source, target) { |
30 | internals.debuglog(`Reading archive ${source}`); | |
31 | const postIds = (await readdir(source)) | |
65d379f5 | 32 | .sort((a, b) => Number(b) - Number(a)); |
fac54389 RBR |
33 | const posts = []; |
34 | for (const id of postIds) { | |
6cd62e79 | 35 | const postDirectory = join(source, id); |
fac54389 RBR |
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 | ||
6cd62e79 RBR |
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 | }); | |
fac54389 RBR |
57 | |
58 | try { | |
59 | internals.debuglog('Removing index'); | |
6cd62e79 | 60 | await rmIfExists(target); |
fac54389 RBR |
61 | } |
62 | finally { | |
63 | internals.debuglog('Creating index'); | |
6cd62e79 RBR |
64 | await mkdir(target); |
65 | const indexFile = join(target, internals.kIndexName); | |
fac54389 RBR |
66 | await writeFile(indexFile, index); |
67 | ||
68 | internals.debuglog('Copying posts to archive'); | |
6cd62e79 | 69 | await cp(source, target, { recursive: true }); |
fac54389 RBR |
70 | } |
71 | }; |