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 fs = require('fs-extra');
|
|
|
|
const reportback = require('reportback')();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a JSON file
|
|
|
|
*/
|
|
|
|
|
|
|
|
module.exports = function (options, handlers) {
|
|
|
|
|
|
|
|
// Provide default values for handlers.
|
|
|
|
handlers = reportback.extend(handlers, {
|
|
|
|
alreadyExists: 'error'
|
|
|
|
});
|
|
|
|
|
|
|
|
// Provide defaults and validate required options.
|
|
|
|
_.defaults(options, {
|
|
|
|
force: false
|
|
|
|
});
|
|
|
|
|
|
|
|
const missingOpts = _.difference([
|
|
|
|
'rootPath',
|
|
|
|
'data'
|
|
|
|
], Object.keys(options));
|
|
|
|
|
|
|
|
if (missingOpts.length) {
|
|
|
|
return handlers.invalid(missingOpts);
|
|
|
|
}
|
|
|
|
|
|
|
|
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 handlers.alreadyExists('Something else already exists at `' + rootPath + '`.');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (exists) {
|
2016-11-07 16:31:34 +01:00
|
|
|
fs.remove(rootPath, err => {
|
2016-03-18 11:12:50 +01:00
|
|
|
if (err) {
|
|
|
|
return handlers.error(err);
|
|
|
|
}
|
|
|
|
_afterwards_();
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
_afterwards_();
|
|
|
|
}
|
|
|
|
|
|
|
|
function _afterwards_() {
|
2016-11-07 16:31:34 +01:00
|
|
|
fs.outputJSON(rootPath, options.data, {spaces: 2}, err => {
|
2016-03-18 11:12:50 +01:00
|
|
|
if (err) {
|
|
|
|
return handlers.error(err);
|
|
|
|
} else {
|
|
|
|
handlers.success();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|