Files
site/scripts/metalsmith-copy.js
2024-03-24 21:29:27 +01:00

58 lines
1.6 KiB
JavaScript

const debug = require('debug')('metalsmith-copy')
const fs = require('fs')
const mode = require('stat-mode')
const path = require('path')
module.exports = plugin
function plugin (options) {
options = Object.assign({ destination: '.' }, options)
return function (files, metalsmith, done) {
const dest = options.destination
const promises = []
const addTask = function (items, promise) {
promises.push(promise)
if (items === promises.length) {
debug('Waiting for ' + items + 'copy operations.')
Promise.all(promises)
.then((data) => {
done()
})
.catch((err) => {
done(err)
})
}
}
const iterateFiles = function (options, action) {
if (options.files != null) {
options.files.forEach((filename) => action(filename, options.files.length))
}
if (options.generator != null) {
options.generator(documents => {
documents.forEach((filename) => action(filename, documents.length))
})
}
}
iterateFiles(options, (filename, items) => {
addTask(items, new Promise(function (resolve, reject) {
fs.stat(filename, function (err, stats) {
if (err) return reject(err)
fs.readFile(filename, function (err, buffer) {
if (err) return reject(err)
const file = {
contents: buffer,
mode: mode(stats).toOctal()
}
files[path.join(dest, path.basename(filename))] = file
resolve({})
})
})
}))
})
}
}