zombiebox-cli
Version:
ZombieBox CLI tool
114 lines (94 loc) • 2.73 kB
JavaScript
;
var path = require('path');
var fs = require('fs');
var colors = require('colors');
var mkdirp = require('mkdirp');
var findup = require('findup-sync');
var templatesDir = path.join(__dirname, '..', 'templates');
/**
* @param {string} where File system path
* @param {string} name Module name
* @throws {Error} Throws error when no module found in specified location.
* @return {*}
*/
var requireIn = function(where, name) {
var dir = where;
var parts = where.split(path.sep);
while (parts.length) {
dir = parts.join(path.sep);
try {
return require(path.join(dir, 'node_modules', name));
} catch (e) { }
try {
if (require(path.join(dir, 'package.json')).name === name) {
return require(dir);
}
} catch (e) { }
parts.pop();
}
throw new Error('Cannot find module \'' + name + '\' in \'' + where + '\'');
};
/**
* TODO fix for Promise and zb args.
* @param {string} version
* @param {string} target
*/
var initProject = function(version, target) {
target = path.resolve(target);
var templatePath = path.join(templatesDir, version);
if (!fs.existsSync(templatePath)) {
throw new Error(('Bad version ' + version).red);
}
if (!fs.existsSync(target)) {
mkdirp.sync(target);
}
var template = require(path.join(templatePath, 'template.js'));
template(target, process.exit.bind(process, 0));
};
var showHelp = function() {
var bin = process.argv.slice(0, 2).join(' ');
console.error(bin + ' init[@VERSION] where VERSION on of [' + fs.readdirSync(templatesDir).join(', ') + ']');
};
var runZB = function(args) {
var zbProjectRoot = '';
try {
var packageJson = findup('package.json');
if (require(packageJson).dependencies.zombiebox) {
zbProjectRoot = path.dirname(packageJson);
}
} catch (e) {}
if (zbProjectRoot) {
var ZBApplication = requireIn(zbProjectRoot, 'zombiebox');
if (!ZBApplication.getCLI) {
console.error('Update zb to > 0.0.174');
process.exit(1);
}
var customConfig = undefined;
args.reduce(function(isPrevKeyConfig, value) {
if (isPrevKeyConfig === true) {
customConfig = path.resolve(value);
return false;
} else if (value === '--custom-config') {
return true;
}
return isPrevKeyConfig;
}, false);
var cli = ZBApplication.getCLI(zbProjectRoot, customConfig);
cli.registerCommand('init', initProject);
cli.parse(args);
} else {
if (args[0] === '--help') {
showHelp();
} else {
console.error('Cannot find ZombieBox project in \'' + process.cwd() + '\'.');
}
}
};
var args = process.argv.slice(2);
var parseInit = /^init(@(.+))?$/.exec(args[0] || '');
if (parseInit) {
initProject(parseInit[2] || 'latest', args[1] || '.');
} else {
runZB(args);
}