aboutsummaryrefslogtreecommitdiff
path: root/lib/generators/static.js
blob: 45f5a04ed1c1a763bc8e6b128ac5c6a80984934a (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
import { access, cp, readdir } from 'fs/promises';
import { constants } from 'fs';
import { join } from 'path';
import { debuglog } from 'util';
import { kFileNotFoundError } from '../constants.js';

const internals = {
  debuglog: debuglog('blog'),
  kAssetsDirectoryName: 'assets'
};

/**
 * Generates the static assets required for the blog
 *
 * @name StaticGenerator
 * @param {string} source the source directory
 * @param {string} target the target directory
 * @param {Array.<Blog.tPost>} posts the list of posts
 */
export default async function StaticGenerator(source, target, _) {

  try {
    await access(source, constants.R_OK);

    const entries = await readdir(source, { withFileTypes: true });
    for (const entry of entries) {
      const sourceAsset = join(source, entry.name);
      const targetAsset = join(target, entry.name);

      internals.debuglog(`Copying ${sourceAsset} to ${targetAsset}`);

      if (entry.isDirectory()) {
        await cp(sourceAsset, targetAsset, { recursive: true });
      }
      else {
        await cp(sourceAsset, targetAsset);
      }
    }
  }
  catch (error) {
    if (error.code === kFileNotFoundError) {
      internals.debuglog(`No static directory found in ${source}`);
      return;
    }

    throw error;
  }
}