Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
702 lines (590 loc) · 20.5 KB
/
Copy pathcli.js
File metadata and controls
702 lines (590 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
var Cli = {};
var IonicAppLib = require('ionic-app-lib');
var IonicStats = require('./utils/stats');
var IonicStore = require('./utils/store');
var IonicConfig = new IonicStore('ionic.config');
var Info = IonicAppLib.info;
var IonicProject = IonicAppLib.project;
var optimist = require('optimist');
var path = require('path');
var fs = require('fs');
var settings = require('../package.json');
var Tasks = require('./config/commands').allCommands;
var orderedListOfTasks = require('./config/commands').orderedListOfCommands;
var appLibUtils = IonicAppLib.utils;
var Logging = IonicAppLib.logging;
var log = Logging.logger;
var Q = require('q');
var helpUtil = require('./utils/help');
var EOL = require('os').EOL;
var chalk = require('chalk');
Cli.ALL_TASKS = Tasks;
Cli.IONIC_DASH = 'https://apps.ionic.io';
Cli.IONIC_API = '/api/v1/';
Cli.PRIVATE_PATH = '.ionic';
Cli.VERSION = settings.version;
// This is where the logger for the app-lib can be configured (or replaced).
log.level = 'info';
/**
* The main entry point for the CLI
* This takes the process.argv array for arguments
* The args passed should be unfiltered.
* From here, we will filter the options/args out
* using optimist. Each command is responsible for
* parsing out the args/options in the way they need.
* This way, we can still test with passing in arguments.
*
* @method run
* @param {Array} processArgv a list of command line arguments including
* @return {Promise}
*/
Cli.run = function run(processArgv) {
/*
* Before taking any more steps, lets check their
* environment and display any upgrade warnings
*/
return Q.all([
Cli.doRuntimeCheck(),
Cli.checkLatestVersion()
]).then(function() {
Cli.runr(processArgv);
}).catch(function(ex) {
return appLibUtils.fail(ex);
});
};
Cli.runr = function runr(processArgv) {
try {
/*
* First we parse out the args to use them.
* Later, we will fetch the command they are trying to
* execute, grab those options, and reparse the arguments.
*/
var rawCliArguments = processArgv.slice(2);
var argv = optimist(rawCliArguments).argv;
var taskList;
Cli.attachErrorHandling();
process.on('exit', function() {
Cli.printVersionWarning(settings.version, Cli.npmVersion);
});
/*
* Print version if '--version' or '--v' is an option
* TODO: version should probably also be a command
* and this should just map the option to a command
*/
if ((argv.version || argv.v) && !argv._.length) {
return Q.fcall(Cli.version);
}
/*
* Print ionitron if '--ionitron' is an option
* TODO: ionitron should probably also be a command
* and this should just map the option to a command
*/
if (argv.ionitron) {
var Ionitron = require('./utils/ionitron');
var lang = argv.es ? 'es' : 'en';
return Q.fcall(Ionitron.print, lang);
}
/*
* Set log level to debug if '--verbose' is an option
* TODO: This might be better to handle the verbose flag
* in each individual command
*/
if (argv.verbose) {
log.level = 'debug';
}
/*
* Print help if '--help' or '-h' is an option
* TODO: help should probably be a command and option on commands
* $ ionic help start (ALREADY WORKS)
* $ ionic start --help
*/
if (argv.help || argv.h) {
taskList = Cli.getAllTaskSettings();
return Q.fcall(helpUtil.printTaskListUsage, taskList, Cli.VERSION);
}
/*
* TODO: Change stats-opt-out to be a command that updates config rather
* than an option that is passed.
*/
if (argv['stats-opt-out']) {
IonicConfig.set('statsOptOut', true);
IonicConfig.save();
log.info('Successful stats opt-out');
return Q.fcall(function() {
return 'saved';
});
}
var taskName = argv._[0];
var task = Cli.getTaskSettingsByName(taskName);
log.debug('Task:', task);
// If no task is found then just provide the list of tasks available
if (!task) {
taskList = Cli.getAllTaskSettings();
return Q.fcall(helpUtil.printTaskListShortUsage, taskList, taskName, Cli.VERSION);
}
var booleanOptions = Cli.getListOfBooleanOptions(task.options);
// Gather stats on the current command execution
IonicStats.t();
// Remove all possible task boolean options from the args
argv = optimist(rawCliArguments)
.boolean(booleanOptions)
.argv;
// No need to do project specific actions, cd to root, etc.
if (!task.isProjectTask) {
return Q.fcall(task.run.bind(task), Cli, argv, rawCliArguments);
}
var root = appLibUtils.cdIonicRoot();
var project = IonicProject.load(root);
argv.v2 = project && project.get('v2');
// For v1 projects ignore as this could have been skipped for faster start
// and gulp hooks aren't required
// For v2, print a warning as this is most likely not what they want
if (!fs.existsSync('node_modules')) {
if (argv.v2) {
log.warn(chalk.yellow('WARN: No node_modules directory found, do you need to run npm install?'));
}
log.debug('node_modules directory not found, not running gulp hooks');
return Q.fcall(task.run.bind(task), Cli, argv, rawCliArguments);
}
// Check if there are npm scripts in the package.json
var npmScripts = Cli.loadNpmScripts();
try {
var gulpLoaded = Cli.loadGulpfile();
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
log.info('Uh oh! Looks like you\'re missing a module in your gulpfile:');
log.error(e.message);
log.info('\nDo you need to run `npm install`?\n');
process.exit(1);
}
log.error(chalk.red('\nThere is an error in your gulpfile: '));
log.error(e.stack + '\n');
process.exit(1);
}
log.debug('\nNpm scripts:', npmScripts);
log.debug('Gulpfile found:', gulpLoaded, '\n');
if (npmScripts && (npmScripts.hasOwnProperty(taskName + ':before') || npmScripts.hasOwnProperty(taskName + ':after'))) {
return Cli.runWithNpmScripts(argv, task, rawCliArguments);
} else if (gulpLoaded) {
return Cli.runWithGulp(argv, task, rawCliArguments);
}
if (!gulpLoaded) {
// warn if no build file and it's a command that requires a build step
// but still run the command with no hooks
if (Cli.isBuildCommand(taskName) && argv.v2 && !npmScripts) {
log.warn('WARN: No build file found!');
log.warn('If your app requires a build step, you may want to ensure it runs before ' + taskName + '.\n');
}
if (!npmScripts) {
log.debug('No gulpfile found, not running gulp hooks');
}
}
return Q.fcall(task.run.bind(task), Cli, argv, rawCliArguments);
} catch (ex) {
return appLibUtils.fail(ex);
}
};
Cli.runWithGulp = function runWithGulp(argv, taskInstance, rawCliArguments) {
var cmdName = argv._[0];
var beforeHook = cmdName + ':before';
var afterHook = cmdName + ':after';
try {
var gulp = require(path.resolve(process.cwd() + '/node_modules/gulp'));
} catch (e) {
// Empty gulpfile (or one that doesn't require gulp?), and no gulp
log.error(chalk.red('\nGulpfile detected, but gulp is not installed'));
log.error(chalk.red('Do you need to run `npm install`?\n'));
return process.exit(1);
}
// setup gulp logging
Cli.logEvents(gulp, [beforeHook, afterHook]);
// if there is no before hook there's no need to run gulp
var beforeHookPromise = Q(true);
if (gulp.tasks[beforeHook]) {
log.info('\nRunning \'' + beforeHook + '\' gulp task before ' + cmdName);
beforeHookPromise = Cli.runGulpHook(gulp, beforeHook);
} else if (Cli.isBuildCommand(cmdName) && argv.v2) {
log.warn(chalk.yellow('WARN: No \'' + beforeHook + '\' gulp task found!'));
log.warn(chalk.yellow('If your app requires a build step, you may want to ensure it runs before ' +
cmdName + '.\n'));
}
// run beforeHook
return beforeHookPromise
// run cmd
.then(function() {
return Q.fcall(taskInstance.run.bind(taskInstance), Cli, argv, rawCliArguments);
})
// run afterHook
.then(function() {
if (gulp.tasks[afterHook]) {
log.info('\nRunning \'' + afterHook + '\' gulp task after ' + cmdName);
return Cli.runGulpHook(gulp, afterHook);
}
});
};
Cli.runGulpHook = function runGulpHook(gulp, hookName) {
// swallow errors because we already check to make sure the task exists
// so not a missingTask error, and gulp already reports its own errors
// which we set up with Cli.logEvents
return Q.nfcall(gulp.start.bind(gulp), hookName)
.catch(function() {});
};
Cli.loadGulpfile = function loadGulpfile() {
// TODO add babel support?
var names = ['gulpfile.js', 'Gulpfile.js'];
for (var i = 0, ii = names.length; i < ii; i += 1) {
try {
require(path.resolve(process.cwd(), names[i]));
log.verbose('Gulpfile found');
return true;
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf(names[i]) !== -1) {
// ignore missing gulpfile
continue;
}
throw e;
}
}
return false;
};
Cli.runWithNpmScripts = function runWithNpmScripts(argv, taskInstance, rawCliArguments) {
var cmdName = argv._[0];
var beforeHook = cmdName + ':before';
var afterHook = cmdName + ':after';
var packageFile = require(path.resolve(process.cwd() + '/package.json'));
var scripts = packageFile.scripts;
var beforeHookPromise = Q(true);
if (scripts[beforeHook]) {
log.info('\nRunning \'' + beforeHook + '\' npm script before ' + cmdName);
beforeHookPromise = Cli.runNpmHook(scripts[beforeHook]);
}
// run beforeHook
return beforeHookPromise
// run cmd
.then(function() {
return Q.fcall(taskInstance.run.bind(taskInstance), Cli, argv, rawCliArguments);
})
// run afterHook
.then(function() {
if (scripts[afterHook]) {
log.info('\nRunning \'' + afterHook + '\' npm script before ' + cmdName);
return Cli.runNpmHook(scripts[afterHook]);
}
});
};
Cli.runNpmHook = function runNpmHook(hook) {
var cmd = 'npm';
var args = ['run', hook];
var command = cmd + ' ' + args;
// Force colors for all spawned child processes
process.env['FORCE_COLOR'] = true;
var q = Q.defer();
var crossSpawn = require('cross-spawn');
var spawned = crossSpawn.spawn('npm', args, { stdio: ['pipe', 'pipe', process.stderr] });
spawned.on('error', function(err) {
log.error('Unable to run spawn command ' + err);
});
spawned.stdout.pipe(process.stdout);
spawned.stdout.on('data', function(data) {
var dataLines = data.toString().split(EOL);
for (var i = 0; i < dataLines.length; i += 1) {
if (dataLines[i].length) {
if (dataLines[i].indexOf('watch ready') > -1) {
return q.resolve();
}
}
}
});
spawned.on('exit', function(code) {
log.debug('Spawn command', command, 'completed');
if (code !== 0) {
return q.reject('There was an error with the spawned command: ' + command);
}
return q.resolve();
});
// If this process ends ensure that we killed the spawned child
process.on('exit', function() {
spawned.kill();
});
return q.promise;
};
Cli.loadNpmScripts = function loadNpmScripts() {
var fileName = 'package.json';
try {
var packageFile = require(path.resolve(process.cwd(), fileName));
log.verbose('Package.json found scripts:', packageFile.scripts);
return packageFile.scripts;
} catch (e) {
throw e;
}
};
Cli.logEvents = function logEvents(gulpInst, finalTaskNames) {
var prettyTime = require('pretty-hrtime');
var gutil = require('gulp-util');
gulpInst.on('task_start', function(e) {
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
gutil.log('Starting', '\'' + chalk.cyan(e.task) + '\'...');
});
gulpInst.on('task_stop', function(e) {
var time = prettyTime(e.hrDuration);
gutil.log(
'Finished', '\'' + chalk.cyan(e.task) + '\'',
'after', chalk.magenta(time)
);
if (finalTaskNames.indexOf(e.task) > -1) {
log.info();
}
});
gulpInst.on('task_err', function(e) {
var msg = Cli.formatGulpError(e);
var time = prettyTime(e.hrDuration);
gutil.log(
'\'' + chalk.cyan(e.task) + '\'',
chalk.red('errored after'),
chalk.magenta(time)
);
gutil.log(msg);
});
};
// Format orchestrator errors
Cli.formatGulpError = function formatGulpError(e) {
if (!e.err) {
return e.message;
}
// PluginError
if (typeof e.err.showStack === 'boolean') {
return e.err.toString();
}
// Normal error
if (e.err.stack) {
return e.err.stack;
}
// Unknown (string, number, etc.)
return new Error(String(e.err)).stack;
};
Cli.isBuildCommand = function isBuildCommand(cmdName) {
return /serve|build|run|emulate|upload/.test(cmdName);
};
/**
* Method accepts an object of 'task options' and returns all
* boolean options that are available
*
* @method getListOfBooleanOptions
* @param {Object} taskOptionsObj
* @return {Array} Returns array of all available boolean options
*/
Cli.getListOfBooleanOptions = function getListOfBooleanOptions(taskOptionsObj) {
if (typeof taskOptionsObj !== 'object' || Object.keys(taskOptionsObj) === 0) {
return [];
}
return Object.keys(taskOptionsObj)
.filter(function(key) {
return typeof taskOptionsObj[key] !== 'string';
})
.reduce(function(list, key) {
var keyItems = key
.split('|')
.map(function(item) {
return item.replace(/^-{1,2}/, '');
});
return list.concat(keyItems);
}, []);
};
Cli.printVersionWarning = function printVersionWarning(version, npmVersion) {
if (version.indexOf('beta') > -1 || version.indexOf('alpha') > -1) {
return;
}
if (npmVersion && npmVersion !== version.trim()) {
log.warn(chalk.red('\n------------------------------------\n'));
log.warn(chalk.yellow.bold('Ionic CLI is out of date:\n'));
log.warn(chalk.yellow(' * Locally installed version: ' + version + '\n'));
log.warn(chalk.yellow(' * Latest version: ' + npmVersion + '\n'));
log.warn(chalk.yellow(' * https://github.com/driftyco/ionic-cli/blob/master/CHANGELOG.md\n'));
log.warn(chalk.yellow(' * Run ') + chalk.bold('npm install -g ionic') + chalk.yellow(' to update\n'));
log.warn(chalk.red('------------------------------------\n\n'));
}
};
Cli.checkLatestVersion = function checkLatestVersion(settingsVersion) {
var resultsDeferred = Q.defer();
try {
if (settingsVersion.indexOf('beta') > -1 || settingsVersion.indexOf('alpha') > -1) {
// don't bother checking if its a beta
resultsDeferred.resolve();
return;
}
var versionCheck = IonicConfig.get('versionCheck');
if (versionCheck && ((versionCheck + 86400000) > Date.now())) {
// we've recently checked for the latest version, so don't bother again
resultsDeferred.resolve();
return;
}
var proxy = process.env.PROXY || process.env.http_proxy || null;
var request = require('request');
request({ url: 'http://registry.npmjs.org/ionic/latest', proxy: proxy }, function(err, res, body) {
if (err) {
return console.log(err);
}
try {
Cli.npmVersion = JSON.parse(body).version;
IonicConfig.set('versionCheck', Date.now());
IonicConfig.save();
} catch (e) {
console.log(e);
}
resultsDeferred.resolve();
});
} catch (e) {
resultsDeferred.resolve();
}
return resultsDeferred.promise;
};
/**
* @method getTaskSettingsByName
* @param {String} taskName task name to look for
* @return {Object} Returns the task settings object that matches
*/
Cli.getTaskSettingsByName = function getTaskSettingsByName(taskName) {
var task;
Object.keys(Cli.ALL_TASKS).every(function(listName) {
if (listName === taskName) {
task = require(Cli.ALL_TASKS[listName]);
return false;
}
return true;
});
return task;
};
/**
* @method getAllTaskSettings
* @return {Array} Returns an array of task settings objects
*/
Cli.getAllTaskSettings = function getAllTaskSettings() {
return orderedListOfTasks.map(function(listName) {
return require(Cli.ALL_TASKS[listName]);
});
};
Cli.processExit = function processExit(code) {
if (Cli.cliNews && Cli.cliNews.promise) {
Q.all([Cli.latestVersion.promise, Cli.cliNews.promise])
.then(function() {
process.exit(code);
});
} else {
Cli.latestVersion.promise.then(function() {
process.exit(code);
});
}
};
Cli.version = function version() {
log.info(settings.version + '\n');
};
Cli.printNewsUpdates = function printNewsUpdates(skipNewsCheck) {
if (typeof skipNewsCheck == 'undefined') {
skipNewsCheck = true;
}
var q = Cli.cliNews = Q.defer();
var proxy = process.env.PROXY || null;
var request = require('request');
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
var d = new Date();
var downloadUrl = 'http://code.ionicframework.com/content/cli-message.json';
request({ url: downloadUrl, proxy: proxy }, function(err, res, html) {
if (!err && res && parseInt(res.statusCode, 10) === 200) {
try {
var newsId = IonicConfig.get('newsId');
var messagesJson = JSON.parse(html);
if (skipNewsCheck || typeof newsId == 'undefined' || newsId !== messagesJson.id) {
IonicConfig.set('newsId', messagesJson.id);
IonicConfig.save();
} else {
q.resolve();
return q.promise;
}
log.info('+---------------------------------------------------------+\n');
var monthMessage = ['+ Extra! Extra! Ionic Updates for ',
monthNames[d.getMonth()],
' ',
d.getFullYear(),
'\n+\n'].join('');
log.info(monthMessage);
for (var i = 0, j = messagesJson.list.length; i < j; i += 1) {
var entry = messagesJson.list[i];
var entryMessage = ['+ ', entry.name, '\n', '+ ', chalk.blue.bold(entry.action), '\n+\n'].join('');
log.info(entryMessage);
}
log.info(chalk.green('+---------------------------------------------------------+\n'));
} catch (ex) {
q.reject('Error occurred in downloading the CLI messages:', ex);
appLibUtils.fail(ex);
}
q.resolve(messagesJson);
} else {
log.error('Unable to fetch', err, res.statusCode);
q.reject(res);
}
});
return q.promise;
};
Cli.handleUncaughtExceptions = function handleUncaughtExceptions(err) {
log.error(chalk.red.bold('An uncaught exception occurred and has been reported to Ionic'));
var errorMessage = typeof err === 'string' ? err : err.message;
appLibUtils.errorHandler(errorMessage);
process.exit(1);
};
Cli.attachErrorHandling = function attachErrorHandling() {
appLibUtils.errorHandler = function errorHandler(msg) {
log.debug('Cli.appLibUtils.errorHandler msg', msg, typeof msg);
var stack = typeof msg == 'string' ? '' : msg.stack;
var errorMessage = typeof msg == 'string' ? msg : msg.message;
var promise = Q();
if (msg) {
promise = Info.gatherInfo().then(function(info) {
var ionicCliVersion = info.ionic_cli;
if (stack && stack.length > 0) {
process.stderr.write('\n' + chalk.bold(stack) + '\n\n');
}
process.stderr.write('\n' + chalk.bold(errorMessage));
process.stderr.write(chalk.bold(' (CLI v' + ionicCliVersion + ')') + '\n');
Info.printInfo(info);
});
}
promise.then(function() {
process.stderr.write('\n');
process.exit(1);
return '';
}).catch(function(ex) {
console.log('errorHandler had an error', ex);
console.log(ex.stack);
});
};
// TODO Attach error reporter here
};
// Backwards compatability for those commands that havent been
// converted yet.
Cli.fail = function fail(err, taskHelp) {
appLibUtils.fail(err, taskHelp);
};
Cli.getContentSrc = function getContentSrc() {
return appLibUtils.getContentSrc(process.cwd());
};
Cli.doRuntimeCheck = function doRuntimeCheck(version) {
var semver = require('semver');
var lastVersionChecked = IonicConfig.get('lastVersionChecked');
var versionHasBeenChecked;
try {
versionHasBeenChecked = semver.satisfies(version, lastVersionChecked);
} catch (ex) {
log.info(ex);
}
if (!lastVersionChecked || !versionHasBeenChecked) {
return Info.gatherInfo().then(function(info) {
Info.checkRuntime(info);
IonicConfig.set('lastVersionChecked', version);
IonicConfig.save();
});
}
return Q();
};
module.exports = Cli;