]> git.r.bdr.sh - rbdr/blog/blobdiff - lib/generators/static.js
Add generator
[rbdr/blog] / lib / generators / static.js
index eb3c631e4eeb383763309e561a298a5fd32072ae..45f5a04ed1c1a763bc8e6b128ac5c6a80984934a 100644 (file)
@@ -1,14 +1,11 @@
-'use strict';
-
-const { access, rmdir } = require('fs/promises');
-const { ncp } = require('ncp');
-const { join } = require('path');
-const { debuglog, promisify } = require('util');
+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 = {
 
 const internals = {
-  ncp: promisify(ncp),
   debuglog: debuglog('blog'),
   debuglog: debuglog('blog'),
-
   kAssetsDirectoryName: 'assets'
 };
 
   kAssetsDirectoryName: 'assets'
 };
 
@@ -20,31 +17,32 @@ const internals = {
  * @param {string} target the target directory
  * @param {Array.<Blog.tPost>} posts the list of posts
  */
  * @param {string} target the target directory
  * @param {Array.<Blog.tPost>} posts the list of posts
  */
-module.exports = async function StaticGenerator(source, target, posts) {
-
-  const assetsTarget = join(target, internals.kAssetsDirectoryName);
+export default async function StaticGenerator(source, target, _) {
 
 
-  internals.debuglog(`Removing ${assetsTarget}`);
-  await rmdir(assetsTarget, { recursive: true });
+  try {
+    await access(source, constants.R_OK);
 
 
-  for (let i = 0; i < posts.length; ++i) {
-    const postSourcePath = join(source, `${i}`);
+    const entries = await readdir(source, { withFileTypes: true });
+    for (const entry of entries) {
+      const sourceAsset = join(source, entry.name);
+      const targetAsset = join(target, entry.name);
 
 
-    try {
-      await access(postSourcePath);
+      internals.debuglog(`Copying ${sourceAsset} to ${targetAsset}`);
 
 
-      const assetsSource = join(postSourcePath, internals.kAssetsDirectoryName);
-
-      internals.debuglog(`Copying ${assetsSource} to ${assetsTarget}`);
-      await internals.ncp(assetsSource, assetsTarget);
-    }
-    catch (error) {
-      if (error.code === internals.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;
+  }
+}