aboutsummaryrefslogtreecommitdiff
path: root/lib/archivers/gemlog.js
blob: 3443c6654eb8faf14ee4d5afbe927c0971dc529b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const { cp, mkdir, readdir, writeFile } = require('fs/promises');
const { debuglog } = require('util');
const { resolve, join } = require('path');
const { rmIfExists } = require('../utils');

const internals = {
  kArchiveName: resolve(join(__dirname, '../..', '.gemlog')),
  kIndexName: 'index.gmi',
  kGeminiRe: /\.gmi$/i,

  debuglog: debuglog('blog'),

  buildUrl(id, slug) {
    return `./${id}/${slug}`;
  },

  buildTitle (id, slug) {
    const date = new Date(Number(id));
    const shortDate = date.toISOString().split('T')[0]
    const title = slug.split('-').join(' ');
    return `${shortDate} ${title}`
  },

  buildLink(id, slug) {
    return `=> ${internals.buildUrl(id,slug)} ${internals.buildTitle(id,slug)}`;
  }
};

module.exports = async function(archiveDirectory) {
  internals.debuglog(`Reading archive ${archiveDirectory}`);
  const postIds = (await readdir(archiveDirectory))
    .sort((a, b) => Number(b) - Number(a));
  const posts = [];
  for (const id of postIds) {
    const postDirectory = join(archiveDirectory, id);
    const slug = (await readdir(postDirectory))
        .filter((entry) => internals.kGeminiRe.test(entry))[0];

      posts.push({ id, slug })
  };

  internals.debuglog(`Read ${posts.length} posts`);

  const index = [
    '# Ruben\'s Gemlog Archive', '',
    '=> https://r.bdr.sh/gemlog/feed.xml 📰 RSS Feed',
    '=> https://r.bdr.sh/gemlog/index.txt 📑 http text version (latest 3 posts)',
    '',
    ...posts.map((post) => internals.buildLink(post.id, post.slug)),
    '', '=> ../ 🪴 Back to main page'
  ].join('\n');

  try {
    internals.debuglog('Removing index');
    await rmIfExists(internals.kArchiveName);
  }
  finally {
    internals.debuglog('Creating index');
    await mkdir(internals.kArchiveName);
    const indexFile = join(internals.kArchiveName, internals.kIndexName);
    await writeFile(indexFile, index);

    internals.debuglog('Copying posts to archive');
    await cp(archiveDirectory, internals.kArchiveName, { recursive: true });
  }
};