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({}) }) }) })) }) } }