2016-03-18 11:12:50 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Node.js core.
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
// Public node modules.
|
|
|
|
const _ = require('lodash');
|
|
|
|
const async = require('async');
|
|
|
|
const fs = require('fs-extra');
|
|
|
|
const reportback = require('reportback')();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a file using the specified string
|
|
|
|
*/
|
|
|
|
|
2018-05-04 17:36:50 +02:00
|
|
|
/* eslint-disable prefer-template */
|
2021-04-29 11:11:46 +02:00
|
|
|
module.exports = function(options, cb) {
|
2016-03-18 11:12:50 +01:00
|
|
|
// Provide default values for switchback.
|
|
|
|
cb = reportback.extend(cb, {
|
2021-04-29 11:11:46 +02:00
|
|
|
alreadyExists: 'error',
|
2016-03-18 11:12:50 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
// Provide defaults and validate required options.
|
|
|
|
_.defaults(options, {
|
2021-04-29 11:11:46 +02:00
|
|
|
force: false,
|
2016-03-18 11:12:50 +01:00
|
|
|
});
|
|
|
|
|
2021-04-29 11:11:46 +02:00
|
|
|
const missingOpts = _.difference(['contents', 'rootPath'], Object.keys(options));
|
2016-03-18 11:12:50 +01:00
|
|
|
|
|
|
|
if (missingOpts.length) {
|
|
|
|
return cb.invalid(missingOpts);
|
|
|
|
}
|
|
|
|
|
|
|
|
// In case we ended up here with a relative path,
|
|
|
|
// resolve it using the process's CWD
|
|
|
|
const rootPath = path.resolve(process.cwd(), options.rootPath);
|
|
|
|
|
|
|
|
// Only override an existing file if `options.force` is true.
|
2016-11-07 16:31:34 +01:00
|
|
|
fs.exists(rootPath, exists => {
|
2016-03-18 11:12:50 +01:00
|
|
|
if (exists && !options.force) {
|
|
|
|
return cb.alreadyExists('Something else already exists at `' + rootPath + '`.');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Don't actually write the file if this is a dry run.
|
|
|
|
if (options.dry) {
|
|
|
|
return cb.success();
|
|
|
|
}
|
|
|
|
|
2021-04-29 11:11:46 +02:00
|
|
|
async.series(
|
|
|
|
[
|
|
|
|
function deleteExistingFileIfNecessary(cb) {
|
|
|
|
if (!exists) {
|
|
|
|
return cb();
|
|
|
|
}
|
|
|
|
return fs.remove(rootPath, cb);
|
|
|
|
},
|
|
|
|
function writeToDisk(cb) {
|
|
|
|
fs.outputFile(rootPath, options.contents, cb);
|
|
|
|
},
|
|
|
|
],
|
|
|
|
cb
|
|
|
|
);
|
2016-03-18 11:12:50 +01:00
|
|
|
});
|
|
|
|
};
|