Cli.run = function run(processArgv) { try { var argv = optimist(processArgv.slice(2)).argv; Cli.setUpConsoleLoggingHelpers(); if ((argv.version || argv.v) && !argv._.length) { return Cli.version(); } if (argv.help || argv.h) { return Cli.printHelpLines(); } var task_setting = Cli.tryBuildingTask(argv); if (!task_setting) { return Cli.printAvailableTasks(); } var bool_opts = Cli.getBooleanOptionsForTask(task_setting); // TODO slice的作用 argv = optimist(processArgv.slice(2)).boolean(bool_opts).argv; var module = Cli.lookupTask(task_setting.module); var instance = new module(); var promise = instance.run(Cli, argv); return promise; } catch (ex) { console.log(ex); // return Utils.fail(ex); } };
exports.strings = function () { var s = optimist([ '-s', '0001234' ]).string('s').argv.s; assert.eql(s, '0001234'); assert.eql(typeof s, 'string'); var x = optimist([ '-x', '56' ]).string('x').argv.x; assert.eql(x, '56'); assert.eql(typeof x, 'string'); };
'hasIonicScript(build) is true and hasIonicScript(build) is true and liveReload is passed', function(done) { var processArguments = ['node', 'ionic', 'emulate', 'android', '--livereload']; var rawCliArguments = processArguments.slice(2); var argv = optimist(rawCliArguments).argv; spyOn(npmScripts, 'hasIonicScript').andCallFake(function(task) { if (task === 'build') { return Q(true); } else if (task === 'serve') { return Q(true); } }); spyOn(npmScripts, 'runIonicScript').andReturn(Q(true)); emulate.run(null, argv, rawCliArguments).then(function() { expect(npmScripts.hasIonicScript).toHaveBeenCalledWith('build'); expect(npmScripts.runIonicScript).toHaveBeenCalledWith('serve', [ '--runLivereload', '--isPlatformServe', '--livereload', '--port', jasmine.any(Number), '--livereload-port', jasmine.any(Number), '--address', jasmine.any(String), '--iscordovaserve', '--nobrowser' ]); expect(cordovaUtils.execCordovaCommand).toHaveBeenCalledWith(['emulate', 'android'], true, true); done(); }).catch(function(e) { console.log(e); }); });
CmdServer.prototype.begin = function (argv) { var socket, route; if (argv) this.argv = optimist(argv).argv; argv = this.argv; socket = argv['S'] || argv['socket']; route = argv['_'].slice(2).join(''); if (!socket) return this.startRepl(route); // Fail if there's a route involved, that implies the user wants to // connect to a socket and perform a command. client.error = function (err) { if (route) return console.error(util.format('Can\'t connect to socket `%s`', socket.green)); this.listen(socket); }.bind(this); if (route) { client.silent = true; client.once('connect', function () { client.write(route + '\n'); client.end(); }); }; client.attach(socket); }
module.exports.usage = function(args) { var opts = optimist( args ) .options( 'add', { default : undefined, describe : 'see server-add command OPTIONS' }) .options( 'remove', { default : undefined, describe : 'HOST[:PORT] server to be removed from cluster' }) .options( 'server-user', { default : undefined, describe : 'admin username for the server to be added' }) .options( 'server-password', { default : undefined, describe : 'admin password for the server to be added' }) .options( 'timeout', { default : 1000, describe : 'admin password for the server to be added' }) .options( 'h', { alias : 'help', describe : 'options for server-list command' }) .usage( 'start a cluster rebalancing\n' + 'Usage: $0 [OPTIONS] rebalance [OPTIONS]' ); return opts }
function main(argv, callback) { var options = optimist(argv) .usage("Usage: $0 [CONFIG_NAME] [--help]") .alias("s", "settings") .default("settings", DEFAULT_SETTINGS) .describe("settings", "Settings file to use") .default("source", __dirname + "/../../..") .describe("source", "Source directory") .boolean("help") .describe("help", "Show command line options."); argv = options.argv; if (argv.help) { options.showHelp(); return callback(); } if (argv._.length != 1) { options.showHelp(); return callback(); } var config = argv._[0]; var settingsName = argv.settings; var source = argv.source; listPlugins(source, config, settingsName).forEach(function(line) { console.log(line); }); }
writeMarkdown: function(out) { var optimistCommand; var optimist = require('optimist'); var commandModule = this.getModule(); optimistCommand = optimist([]); optimistCommand.options(this.getOptions()); if (commandModule.usage) { var $0 = require('./rapido').instance.$0; optimistCommand.usage(commandModule.usage.replace(/\$0/g, $0).replace(/\$commandName/g, this.name)); } var writeFn; if (out) { writeFn = function(str) { out.write(str); }; } else { writeFn = console.log; } writeFn('```\n'); optimistCommand.showHelp(writeFn); writeFn('```\n'); var commandFilePath = this.file.getAbsolutePath(); var readmeFile = new File(commandFilePath.slice(0, -3) + '.README.md'); if (readmeFile.exists()) { writeFn('\n' + readmeFile.readAsString()); } }
it('should skip runWithGulp if a gulpfile does not exist', function(done) { var processArguments = ['node', 'bin/ionic', 'fake']; var rawCliArguments = processArguments.slice(2); var argv = optimist(rawCliArguments).argv; var FakeTask = { name: 'fake', title: 'fake', run: function() { return Q(true); }, isProjectTask: true }; spyOn(IonicCli, 'getTaskSettingsByName').andReturn(FakeTask); spyOn(fs, 'existsSync').andReturn(true); spyOn(IonicCli, 'loadGulpfile').andReturn(false); spyOn(FakeTask, 'run').andReturn(Q(true)); spyOn(IonicCli, 'runWithGulp'); IonicCli.run(processArguments) .then(function() { expect(IonicCli.loadGulpfile).toHaveBeenCalled(); expect(IonicCli.runWithGulp).not.toHaveBeenCalled(); expect(FakeTask.run).toHaveBeenCalledWith(IonicCli, argv, rawCliArguments); done(); }); });
module.exports = function(parameters, src, context) { parameters = optimist(parameters) .option('comment', { default : false, boolean : true, alias : 'c' }) .argv; nextReq = findNextRequire(src); if(nextReq !== null) { if(parameters.comment) { //source commenting ignore var lines = src.split('\n'); var line = lines[nextReq.line]; //comment elegament the line line = line.replace(/^(\s*)/g, '$1//'); lines.splice(nextReq.line, 1, line); src = lines.join('\n'); return src; } else { //traditional ignore context.bundle.ignore(nextReq.module); } } };
function main(argv, config, callback) { var options = optimist(argv) .usage("Usage: $0 [CONFIG_NAME] [--help]") .alias("s", "settings") .default("settings", DEFAULT_SETTINGS) .describe("settings", "Settings file to use") .describe("dump", "dump config file as JSON") .describe("domain", "Top-level domain to use (e.g, c9.io)") .boolean("help") .describe("help", "Show command line options."); var configs = options.argv._; if (!configs.length) configs = [config || DEFAULT_CONFIG]; configs.forEach(function(config) { if (shortcuts[config]) { return main(shortcuts[config].concat(argv.filter(function(arg) { return arg != config; })), null, callback); } else { start(config, options, callback); } }); }
function main(argv, callback) { var options = optimist(argv) .usage("Usage: $0 [CONFIG_NAME] [--help]") .alias("s", "settings") .default("settings", DEFAULT_SETTINGS) .describe("settings", "Settings file to use") .default("source", __dirname + "/../../..") .describe("source", "Source directory") .describe("targetFile", "Target package.json") .boolean("help") .describe("help", "Show command line options."); argv = options.argv; if (argv.help) { options.showHelp(); return callback(); } if (argv._.length != 1) { options.showHelp(); return callback(); } var config = argv._[0]; var settings = argv.settings; var source = argv.source; nodeModules(source, config, settings, function(err, json) { if (err) return callback(err); if (argv.targetFile) fs.writeFileSync(argv.targetFile, JSON.stringify(json, null, 2)); else console.log(JSON.stringify(json, null, 2)); }); }
function initOptimist(args) { var o = args ? optimist(args) : optimist , portOptions = { describe: 'overrides the default port' , alias: 'p' } , baseOptions = { describe: 'serves content from this folder. Default: ' + HttpConfig.DEFAULT_FOLDER , alias: ['folder', 'f'] } , cacheOptions = { describe: 'caching method used. Default: ' + HttpConfig.DEFAULT_CACHE_CONTROL } , typeOptions = { describe: 'server type http|https' , alias: 't' } , helpOptions = { describe: 'displays this help message' , alias: '?' } , serverOptions = { describe: 'starts a server using the prescribed server configuration' , alias: 's' } return o.options('port', portOptions) .options('base', baseOptions) .options('cache', cacheOptions) .options('type', typeOptions) .options('server', serverOptions) .options('help', helpOptions) }
var post = function(program_option, command_argument, raw_argv) { // Parse only command arguments, so we can exclude the 'post' token, // any token other then options will be treated as filename, inlcude '-' // token. var argv = optimist(command_argument) .usage("Usage: ./0xfb post --to [ID/username] --link [link] --message [message]") .describe('to', 'ID/username of the target wall') .describe('link', 'link to post') .describe('message', 'message to post') .string('to', 'link', 'message') // treat these argvs as string .default('to', 'me') // post to the user's own wall if // `to` is not specified .alias('to', 't') // --to, -t .alias('link', 'l') // --link, -t .alias('message', 'm') // --message, -m .argv; if (argv['_'].length > 0) { // Contains filenames, handle it with upload. uploadphoto.upload(argv); } else if (argv.hasOwnProperty('message')) { // Text only, as a status update. doPost(argv); } else { // No message, so we show the news. wall.showUserNews(argv); } };
describe('cordova platform checks', function() { var appDirectory = '/ionic/app/path'; var processArguments = ['node', 'ionic', 'build', '-n']; var rawCliArguments = processArguments.slice(2); var argv = optimist(rawCliArguments).argv; beforeEach(function() { spyOn(process, 'cwd').andReturn(appDirectory); spyOn(cordovaUtils, 'isPlatformInstalled').andReturn(true); spyOn(cordovaUtils, 'arePluginsInstalled').andReturn(true); spyOn(npmScripts, 'hasIonicScript').andReturn(Q(false)); spyOn(cordovaUtils, 'execCordovaCommand').andReturn(Q(true)); }); it('should default to iOS for the platform', function(done) { spyOn(os, 'platform').andReturn('darwin'); // Expect failure build.run(null, argv, rawCliArguments).then(function() { expect(cordovaUtils.isPlatformInstalled).toHaveBeenCalledWith('ios', appDirectory); done(); }); }); it('should fail if the system is not Mac and the platform is iOS', function(done) { spyOn(os, 'platform').andReturn('windows'); build.run(null, argv, rawCliArguments).then(function() { expect(log.error).toHaveBeenCalledWith('✗ You cannot run iOS unless you are on Mac OSX.'); done(); }); }); });
function status(argv, done) { argv = optimist(argv) .default('d', 1) .default('e', 'md,txt,markdown') .argv; var uri = process.cwd(); if (uri) { var exts = argv.e.split(','); try { var files = fs.readdirSync(uri); var matches = files.filter(function(file) { var pos = file.lastIndexOf(".") , ext = pos > 0 ? file.substring(pos+1) : ''; return exts.indexOf(ext) >= 0; }).map(function(file) { var fullpath = geekple.config.path(path.join(uri, file)); var text = fs.readFileSync(path.join(uri, file), 'utf-8', 'r'); var sha = crypto.createHash('sha1').update(text).digest('hex'); return {uri: fullpath, sha: sha}; }); _status(matches); } catch (e) { console.log(e); } } done(); }
module.exports.usage = function(args) { var opts = optimist( args ) .options( 'create', { describe : 'create a new xdcr configuration' }) .options( 'edit', { describe : 'modify existing xdcr configuration' }) .options( 'delete', { describe : 'delete existing xdcr configuration' }) .options( 'xdcr-cluster-name', { describe : 'cluster name' }) .options( 'xdcr-hostname', { describe : 'remote host name to connect to' }) .options( 'xdcr-username', { describe : 'remote cluster admin username' }) .options( 'xdcr-password', { describe : 'remote cluster admin password' }) .options( 'h', { alias : 'help', describe : 'options for server-list command' }) .usage( 'setup xdcr connection\n' + 'Usage: $0 [OPTIONS] xdcr-setup [OPTIONS]' ); return opts }
exports.run = function(progOpts, cmdArgv, rawArgv) { var argv = optimist(cmdArgv). usage("Usage: ./0xfb wall [ID/username]"). argv; var action = (argv.a) ? "all" : argv['_'][0] || 'me'; getFeed(doPrintFeed.bind(this, end), end, action); };
module.exports = function options(process, processArgv) { const argv = optimist(processArgv || process.argv) .boolean('auto-updater') .boolean('check-permissions') .boolean('developer-tools') .boolean('quit-after-last-window') .default('auto-updater', true) .default('auto-updater-base-url', 'https://updates.soundcleod.com') .default('check-permissions', true) .default('quit-after-last-window', process.platform != 'darwin').argv // process.argv starts with [SoundCleod] or [Electron, app.js], skip these // and get the first non-hyphenated argument const launchUrl = argv._[process.defaultApp ? 2 : 1] return { autoUpdaterBaseUrl: argv['auto-updater-base-url'], baseUrl: argv['base-url'], developerTools: argv['developer-tools'], launchUrl: isSoundcloudUrl(launchUrl) ? launchUrl : undefined, profile: argv.profile, quitAfterLastWindow: argv['quit-after-last-window'], checkPermissions: argv['check-permissions'], useAutoUpdater: argv['auto-updater'], userData: argv['user-data-path'] } }
module.exports = exports = function (cmdStr, context, options) { var shell = this; // Initialize shell helper methods. if (context) shellHelpers.updateContext(context); var prompt = shell.getVar('prompt'); // If no command string was supplied then write an error message. if (!cmdStr || /^[\s';"\[\]|&()<>]+$/.test(cmdStr)) return shell.error('You must supply a value.'); // Parse the command string into an argument array and set the command name to the first item. var args = cmdStr, cmdName = cmdStr; if (cmdStr.length > 0) { args = shellQuote.parse(cmdStr); cmdName = args[0]; } if (cmdStr.toLowerCase() !== 'cancel') { // If a prompt context exists then override command and options with those stored in the context... if (prompt) { cmdName = prompt.cmd; options = prompt.options; options[prompt.option] = cmdStr; shell.clearPrompt(); } // ...otherwise remove the command name from the args array and build our options object. else { args.splice(0, 1); options = extend({}, optimist(args).argv, options); } // Get reference to the command module by name. var cmd = shell.cmds[cmdName.toLowerCase()]; // If the command module exists then process it's options and invoke the module. if (cmd && cmd.access(shell, cmdName.toLowerCase())) { if (options.hasOwnProperty('?') || options.hasOwnProperty('help')) shell.execute('help', context, { command: cmdName }); else if (validateCommandOptions(options, cmd, shell)) cmd.invoke(shell, options); } else shell.error('"' + cmdName + '" is not a valid command'); } else { // If prompt exists then cancel it... if (prompt){ shell.warn('prompt canceled'); shell.clearPrompt(); } // ...otherwise inform user there is no active prompt. else shell.error('there are no active prompts'); } return shell; };
module.exports = function(argv){ var op = optimist(argv); var mdText = fs.readFileSync(__dirname + "/../README.md").toString(); var options = parseMarkdown("## Options", mdText); op.usage("yalr [options]"); options.forEach(function(item) { // Makes no sense from the cli if (item.name === "disable") return; op.describe(item.name, item.description.trim()); }); op.alias("h", "help"); op.describe("help", "Display this help."); op.describe("version", "Display YALR version."); if (op.argv.help) { process.stderr.write(op.help() + "\n"); process.exit(0); } if (op.argv.version) { process.stderr.write( require(__dirname + "/../package.json").version + "\n" ); process.exit(0); } return op.argv; };
clip.prototype.run = function run(cli, cb) { var argv; if (cli && cli !== process) { argv = optimist(cli.argv || [], cli.cwd); argv.$0 = process.$0; } else { argv = optimist.argv; cli = process; if (!cb) { cb = function() { process.exit(tty.statusCode); } } } var cmd = {}; cmd.env = cli.env; cmd.flags = argv; if(!isatty(0)) { cmd.stream = process.openStdin(); } cmd.url = '/' + argv._.map(function encode(component) { return encodeURIComponent(component) }).join('/'); var tty = new TTYHelper(); this.handle(cmd, tty, cb); }
function main(argv, config, onLoaded) { var inContainer = os.hostname().match(/-\d+$/); var optimist = require("optimist"); var async = require("async"); var options = optimist(argv) .usage("Usage: $0 [CONFIG_NAME] [--help]") .alias("s", "settings") .default("settings", DEFAULT_SETTINGS) .describe("settings", "Settings file to use") .describe("dump", "dump config file as JSON") .describe("domains", "Primary and any secondary top-level domains to use (e.g, c9.io,c9.dev)") .describe("exclude", "Exclude specified service") .describe("include", "Include only specified service") .describe("helpWithSudo", "Ask for sudo password on startup") .default("domains", inContainer && process.env.C9_HOSTNAME || process.env.C9_DOMAINS) .boolean("help") .describe("help", "Show command line options."); var configs = options.argv._; if (!configs.length) configs = [config || DEFAULT_CONFIG]; if (options.argv.exclude && !Array.isArray(options.argv.exclude.length)) options.argv.exclude = [options.argv.exclude]; var expanded = expandShortCuts(configs); if (expanded.length > configs.length) return main(expanded.concat(argv.filter(function(arg) { return !shortcuts[arg]; })), config, onLoaded); if (options.argv.include) expanded = [].concat(options.argv.include); var delayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) !== -1 }); var notDelayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) === -1 }); if (options.argv.helpWithSudo) return child_process.execFile("sudo", ["echo -n"], main.bind(null, argv.filter(function(a) { return a !== "--helpWithSudo"; }), config, onLoaded)); startConfigs(notDelayed, function() { startConfigs(delayed, function() { console.log("Cloud9 is up and running"); }); }); function startConfigs(configs, done) { async.each(configs, function(config, next) { if (options.argv.exclude && options.argv.exclude.indexOf(config) > -1) return next(); start(config, options, function(err, result, path) { onLoaded && onLoaded(err, result, path); next(err); }); }, done); } }
module.exports = function(parameters, src, context) { parameters = optimist(parameters) .option('replace', { default : false, boolean : true, alias : 'r' }) .argv; nextReq = findNextRequire(src); if(nextReq !== null) { var alias = parameters._[0]; if(parameters.replace) { var lines = src.split('\n'); var line = nextReq.match[1]+alias+nextReq.match[3]; lines.splice(nextReq.line, 1, line); src = lines.join('\n'); return src; } else { context.bundle.alias(nextReq.module, alias); } } };
module.exports.usage = function(args) { var opts = optimist( args ) .options( 'bucket-name', { default : undefined, describe : 'bucket to act on' }) .options( 'force', { default : false, describe : 'force to execute command without conformation' }) .options( 'data-only', { describe : 'compact database data only' }) .options( 'view-only', { describe : 'compact view data only' }) .options( 'h', { alias : 'help', describe : 'options for server-list command' }) .usage( 'flush all data from disk for a given bucket\n' + 'Usage: $0 [OPTIONS] bucket-flush [OPTIONS]' ); return opts }
var r = checkUsage(function () { return optimist('-x 10 -y 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(function (argv) { return 'x' in argv && 'y' in argv }) .argv; });
var r = checkUsage(function () { return optimist('--foo 50 --baz 70 --powsy'.split(' ')) .default('foo', 5) .default('bar', 6) .default('baz', 7) .argv ; });
exports.stringArgs = function () { var s = optimist([ ' ', ' ' ]).string('_').argv._; assert.eql(s.length, 2); assert.eql(typeof s[0], 'string'); assert.eql(s[0], ' '); assert.eql(typeof s[1], 'string'); assert.eql(s[1], ' '); };
describe('cordova platform and plugin checks', function() { var appDirectory = '/ionic/app/path'; var processArguments = ['node', 'ionic', 'emulate', 'ios', '-n']; var rawCliArguments = processArguments.slice(2); var argv = optimist(rawCliArguments).argv; beforeEach(function() { spyOn(os, 'platform').andReturn('darwin'); spyOn(process, 'cwd').andReturn(appDirectory); spyOn(cordovaUtils, 'installPlatform').andReturn(Q(true)); spyOn(cordovaUtils, 'installPlugins').andReturn(Q(true)); spyOn(npmScripts, 'hasIonicScript').andReturn(Q(false)); spyOn(cordovaUtils, 'execCordovaCommand').andReturn(Q(true)); }); it('should try to install the cordova platform if it is not installed', function(done) { spyOn(cordovaUtils, 'isPlatformInstalled').andReturn(false); spyOn(cordovaUtils, 'arePluginsInstalled').andReturn(true); emulate.run(null, argv, rawCliArguments).then(function() { expect(cordovaUtils.installPlatform).toHaveBeenCalledWith('ios'); done(); }); }); it('should not try to install the cordova platform if it is installed', function(done) { spyOn(cordovaUtils, 'isPlatformInstalled').andReturn(true); spyOn(cordovaUtils, 'arePluginsInstalled').andReturn(true); emulate.run(null, argv, rawCliArguments).then(function() { expect(cordovaUtils.installPlatform).not.toHaveBeenCalledWith(); done(); }); }); it('should install plugins if they are not installed', function(done) { spyOn(cordovaUtils, 'isPlatformInstalled').andReturn(true); spyOn(cordovaUtils, 'arePluginsInstalled').andReturn(false); emulate.run(null, argv, rawCliArguments).then(function() { expect(cordovaUtils.arePluginsInstalled).toHaveBeenCalledWith(appDirectory); expect(cordovaUtils.installPlugins).toHaveBeenCalledWith(); done(); }); }); it('should not install plugins if they are installed', function(done) { spyOn(cordovaUtils, 'isPlatformInstalled').andReturn(true); spyOn(cordovaUtils, 'arePluginsInstalled').andReturn(true); emulate.run(null, argv, rawCliArguments).then(function() { expect(cordovaUtils.arePluginsInstalled).toHaveBeenCalledWith(appDirectory); expect(cordovaUtils.installPlugins).not.toHaveBeenCalledWith(); done(); }); }); });
it('should always leave the ionic command in the cordova command list', function() { var processArguments = ['node', 'ionic', 'build']; var rawCliArguments = processArguments.slice(2); var argv = optimist(rawCliArguments).argv; var cmdName = argv._[0]; var resultArgs = cordovaUtils.filterArgumentsForCordova(cmdName, argv, rawCliArguments); expect(resultArgs).toEqual(['build']); });
var r = checkUsage(function () { return optimist('-x 10 -z 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(function (argv) { if (!('x' in argv)) throw 'You forgot about -x'; if (!('y' in argv)) throw 'You forgot about -y'; }) .argv; });