]> git.r.bdr.sh - rbdr/blog/blobdiff - lib/generators/static.js
Use new generators
[rbdr/blog] / lib / generators / static.js
diff --git a/lib/generators/static.js b/lib/generators/static.js
new file mode 100644 (file)
index 0000000..eb3c631
--- /dev/null
@@ -0,0 +1,50 @@
+'use strict';
+
+const { access, rmdir } = require('fs/promises');
+const { ncp } = require('ncp');
+const { join } = require('path');
+const { debuglog, promisify } = require('util');
+
+const internals = {
+  ncp: promisify(ncp),
+  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
+ */
+module.exports = async function StaticGenerator(source, target, posts) {
+
+  const assetsTarget = join(target, internals.kAssetsDirectoryName);
+
+  internals.debuglog(`Removing ${assetsTarget}`);
+  await rmdir(assetsTarget, { recursive: true });
+
+  for (let i = 0; i < posts.length; ++i) {
+    const postSourcePath = join(source, `${i}`);
+
+    try {
+      await access(postSourcePath);
+
+      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;
+      }
+
+      throw error;
+    }
+  }
+};