]> git.r.bdr.sh - rbdr/blog/blobdiff - lib/generators/static.js
Use modules, use XDG dirs
[rbdr/blog] / lib / generators / static.js
index 416076c966e084d06bd5d1680cedbfbc238b1282..60719e2ef5ee7e1fbe7159a92c321da7b1f6b7d9 100644 (file)
@@ -1,10 +1,10 @@
 'use strict';
 
-const { access, cp } = require('fs/promises');
-const { join } = require('path');
-const { debuglog } = require('util');
-const { rmIfExists } = require('../utils');
-const { kFileNotFoundError } = require('../constants');
+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'),
@@ -19,31 +19,31 @@ const internals = {
  * @param {string} target the target directory
  * @param {Array.<Blog.tPost>} posts the list of posts
  */
-module.exports = async function StaticGenerator(source, target, posts) {
+export default async function StaticGenerator(source, target, _) {
 
-  const assetsTarget = join(target, internals.kAssetsDirectoryName);
+  try {
+    await access(source, constants.R_OK);
 
-  internals.debuglog(`Removing ${assetsTarget}`);
-  await rmIfExists(assetsTarget);
+    const entries = await readdir(source, { withFileTypes: true });
+    for (const entry of entries) {
+      const sourceAsset = join(source, entry.name);
+      const targetAsset = join(target, entry.name);
 
-  for (let i = 0; i < posts.length; ++i) {
-    const postSourcePath = join(source, `${i}`);
+      internals.debuglog(`Copying ${sourceAsset} to ${targetAsset}`);
 
-    try {
-      await access(postSourcePath);
-
-      const assetsSource = join(postSourcePath, internals.kAssetsDirectoryName);
-
-      internals.debuglog(`Copying ${assetsSource} to ${assetsTarget}`);
-      await cp(assetsSource, assetsTarget, { recursive: true });
-    }
-    catch (error) {
-      if (error.code === kFileNotFoundError) {
-        internals.debuglog(`Skipping ${i}`);
-        continue;
+      if (entry.isDirectory()) {
+        await cp(sourceAsset, targetAsset, { recursive: true });
+      } else {
+        await cp(sourceAsset, targetAsset);
       }
-
-      throw error;
     }
   }
+  catch (error) {
+    if (error.code === kFileNotFoundError) {
+      internals.debuglog(`No static directory found in ${source}`);
+      return;
+    }
+
+    throw error;
+  }
 };