fakeit-facet
Version:
Command-line utility that generates fake data which can be output as JSON, YAML, CSON, or CSV formats based on models defined in YAML.
324 lines (253 loc) • 16.1 kB
JavaScript
;
var _findInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/find");
var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.code = code;
exports["default"] = _default;
exports.dim = dim;
var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs3/regenerator"));
var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _parseInt2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/parse-int"));
var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));
var _commander = require("commander");
var _updateNotifier = _interopRequireDefault(require("update-notifier"));
var _path = _interopRequireDefault(require("path"));
var _lodash = require("lodash");
var _chalk = _interopRequireDefault(require("chalk"));
var _package = _interopRequireDefault(require("../package.json"));
var _index = _interopRequireDefault(require("./index.js"));
// this is not a function that is to be called by anything other than the `bin/fakeit` file in the project
function _default() {
return _ref.apply(this, arguments);
}
/* istanbul ignore next : too hard to test */
function _ref() {
_ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() {
var _context4, _context6, _context7;
var base_options, output_options, program, runServer, run, _run;
return _regenerator["default"].wrap(function _callee5$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
_run = function _run3() {
_run = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
var _context10;
var output,
opts,
output_path,
regex,
models,
fakeit,
_args4 = arguments;
return _regenerator["default"].wrap(function _callee4$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
output = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : {};
opts = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {};
output = typeof output === 'string' ? {
output: output
} : output; // get the base options from program
opts = (0, _lodash.pick)((0, _lodash.extend)((0, _lodash.pick)(program, base_options), opts), base_options); // set the babel config
opts.babel_config = opts.babel;
delete opts.babel; // get the output options
output = (0, _lodash.extend)((0, _lodash.pick)(program, output_options), (0, _lodash.pick)(output, output_options)); // get the output path
output_path = _path["default"].join(output.output, output.archive || ''); // eslint-disable-next-line max-len
regex = /^(--(?:program|root|babel|count|format|spacing|seed|limit|bucket|username|password|timeout|server|useStreams|highWaterMark)|(?:-[cfnxl]{1,}))$/; // get the model files that have been passed into fakeit
models = (0, _filter["default"])(_context10 = program.args).call(_context10, function (str, i, args) {
var prev = args[i - 1] || '';
if (typeof str !== 'string' // if the previous str was one of these commands that has options then remove it
|| regex.test(prev) // if the str is one of the commands then remove it
|| /^(([-]{1,2}[a-zA-Z]+)|--no-[a-z]+)$/.test(str) // if the str is the same as the output path then remove it
|| str === output_path) {
return false;
}
return true;
});
fakeit = new _index["default"](opts);
if (models.length) {
_context11.next = 15;
break;
}
fakeit.log('warning', 'you must pass in models to use');
(0, _findInstanceProperty(_lodash))(program.commands, ['_name', output.output]).help();
return _context11.abrupt("return");
case 15:
_context11.prev = 15;
_context11.next = 18;
return fakeit.generate(models, output);
case 18:
process.exit();
_context11.next = 25;
break;
case 21:
_context11.prev = 21;
_context11.t0 = _context11["catch"](15);
console.log(_context11.t0);
process.exit(1);
case 25:
case "end":
return _context11.stop();
}
}
}, _callee4, null, [[15, 21]]);
}));
return _run.apply(this, arguments);
};
run = function _run2() {
return _run.apply(this, arguments);
};
runServer = function _runServer(output) {
/* istanbul ignore next : too difficult to test the servers via the cli */
return /*#__PURE__*/function () {
var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(options) {
var couchbaseOptions, commandOptions;
return _regenerator["default"].wrap(function _callee$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
couchbaseOptions = ['server', 'bucket', 'username', 'password', 'timeout', 'useStreams', 'highWaterMark'];
commandOptions = (0, _lodash.pick)(options, couchbaseOptions);
commandOptions.output = output;
_context3.next = 5;
return run(commandOptions);
case 5:
case "end":
return _context3.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}();
};
// check for update and notify
(0, _updateNotifier["default"])({
pkg: _package["default"]
}).notify();
base_options = ['root', 'babel', 'count', 'verbose', 'log', 'spinners', 'timestamp', 'seed'];
output_options = [// global options
'format', 'spacing', 'limit', // action specific options
'highlight', 'archive', 'server', 'bucket', 'username', 'password', 'timeout', 'useStreams', 'highWaterMark', // gets set based off the command that's used
'output'];
program = (0, _commander.createCommand)(); // helper function used for couchbase and sync-gateway below
// get the inputs
program.version(_package["default"].version).usage('[command] [<file|directory|glob> ...]') // these are all the base options across the different actions
.option('--root <directory>', "Defines the root directory from which paths are resolve from (".concat(dim('process.cwd()'), ")"), process.cwd()).option('--babel <glob>', "The location to the babel config (".concat(dim('+(.babelrc|package.json)'), ")"), '+(.babelrc|package.json)').option('-c, --count <n>', 'Overrides the number of documents to generate specified by the model. Defaults to model defined count', _parseInt2["default"]) // eslint-disable-line
.option('-v, --verbose', "Enables verbose logging mode (".concat(dim(false), ")")).option('-S, --no-spinners', 'Disables progress spinners', false).option('-L, --no-log', 'Disables all logging except for errors', false).option('-T, --no-timestamp', 'Disables timestamps from logging output', false) // global output options
.option('-f, --format <type>', (0, _concat["default"])(_context4 = "this determines the output format to use. Supported formats: ".concat(code('json', 'csv', 'yaml', 'yml', 'cson'), ". (")).call(_context4, dim('json'), ")"), 'json') // eslint-disable-line
.option('-n, --spacing <n>', "the number of spaces to use for indention (".concat(dim('2'), ")"), 2).option('-l, --limit <n>', "limit how many files are output at a time (".concat(dim('10'), ")"), Number, 10).option('-x, --seed <seed>', 'The global seed to use for repeatable data', function (seed) {
var number = (0, _parseInt2["default"])(seed);
if (number > 0 || seed === '0') {
return number;
}
return seed;
}); // i.e. `fakeit console`
program.command('console').option('-h, --no-highlight', 'This turns off the cli-table when a csv format').description('outputs the result to the console').action( /*#__PURE__*/function () {
var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(options) {
var highlight;
return _regenerator["default"].wrap(function _callee2$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
highlight = options.highlight;
_context5.next = 3;
return run({
output: 'console',
highlight: highlight
});
case 3:
case "end":
return _context5.stop();
}
}
}, _callee2);
}));
return function (_x2) {
return _ref3.apply(this, arguments);
};
}()); // i.e. `fakeit couchbase`
program.command('couchbase').option('-s, --server [server]', "The server address (".concat(dim('127.0.0.1'), ")"), '127.0.0.1').option('-b, --bucket [bucket]', "The bucket name (".concat(dim('default'), ")"), 'default').option('-u, --username [username]', 'The username to use (optional pre-5.0)').option('-p, --password [password]', 'the password for the account (optional)').option('-t, --timeout [timeout]', "timeout for the servers (".concat(dim(5000), ")"), 5000).option('-r, --use-streams [useStreams]', (0, _concat["default"])(_context6 = "".concat(_chalk["default"].red('**experimental**'), "\n Whether or not to use node streams. Used for high output\n documents and can only be used when there are no dependencies (")).call(_context6, dim(false), ")"), false).option('-w, --high-water-mark [highWaterMark]', (0, _concat["default"])(_context7 = "".concat(_chalk["default"].red('**experimental**'), "\n The # of objects to process through the stream at a time (")).call(_context7, dim(16), ")"), 16).description('This will output to a Couchbase Server').action(runServer('couchbase')); // i.e. `fakeit sync-gateway`
program.command('sync-gateway').option('-s, --server [server]', "The server address (".concat(dim('127.0.0.1'), ")"), '127.0.0.1').option('-b, --bucket [bucket]', "The bucket name (".concat(dim('default'), ")"), 'default').option('-u, --username [username]', 'the username to use (optional)').option('-p, --password [password]', 'the password for the account (optional)').option('-t, --timeout [timeout]', 'timeout for the servers').description('This will output to a Couchbase Sync-Gateway Server').action(runServer('sync-gateway')); // i.e. `fakeit directory`
program.command('directory [<dir|file.zip>] [<models...>]').alias('folder').option('-a, --archive [file.zip]', 'If an archive file is passed then the data will be output as a zip file', '').description('Output the file(s) into a directory').action( /*#__PURE__*/function () {
var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(output, models, _ref4) {
var _context8;
var archive, parsed;
return _regenerator["default"].wrap(function _callee3$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
archive = _ref4.archive;
parsed = _path["default"].parse(output);
if (parsed.ext) {
archive = parsed.base;
output = parsed.dir || program.root;
} // update the program args to be correct
program.args = (0, _slice["default"])(_context8 = process.argv).call(_context8, 4);
_context9.next = 6;
return run({
archive: archive,
output: output
});
case 6:
case "end":
return _context9.stop();
}
}
}, _callee3);
}));
return function (_x3, _x4, _x5) {
return _ref5.apply(this, arguments);
};
}()); // i.e. `fakeit help`
program.command('help').action(function () {
program.help();
});
program.parse(process.argv);
if (!program.args.length) {
program.help();
} // this function is used as a helper to run the different actions
case 15:
case "end":
return _context12.stop();
}
}
}, _callee5);
}));
return _ref.apply(this, arguments);
}
process.on('uncaughtException', function (err) {
console.log('An uncaughtException was found:', err);
process.exit(1);
});
/* istanbul ignore next : too hard to test */
process.on('unhandledRejection', function (err) {
console.log('An unhandledRejection was found:', err);
process.exit(1);
});
function code() {
var _context;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (0, _map["default"])(_context = (0, _lodash.flattenDeep)(args)).call(_context, function (str) {
return _chalk["default"].bold(str);
}).join(', ');
}
function dim() {
var _context2;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return (0, _map["default"])(_context2 = (0, _lodash.flattenDeep)(args)).call(_context2, function (str) {
return _chalk["default"].dim(str);
}).join(', ');
}