1 | #!/usr/bin/env node
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | var async = require('async'),
|
10 | Command = require('./command'),
|
11 | inputError = require('./util/input-error'),
|
12 | exitProcess = process.exit;
|
13 |
|
14 | require('./register-plugins');
|
15 |
|
16 | function findCommandPosition(args) {
|
17 | var i;
|
18 |
|
19 | for (i = 0; i < args.length; i += 1) {
|
20 | if (args[i].charAt(0) !== '-') {
|
21 | return i;
|
22 | }
|
23 | }
|
24 |
|
25 | return -1;
|
26 | }
|
27 |
|
28 | function exit(ex, code) {
|
29 |
|
30 |
|
31 |
|
32 | var streams = [process.stdout, process.stderr];
|
33 | async.forEach(streams, function (stream, done) {
|
34 |
|
35 | stream.write('', done);
|
36 | }, function () {
|
37 | if (ex) {
|
38 | if (typeof ex === 'string') {
|
39 | console.error(ex);
|
40 | exitProcess(1);
|
41 | } else {
|
42 | throw ex;
|
43 | }
|
44 | } else {
|
45 | exitProcess(code);
|
46 | }
|
47 | });
|
48 | }
|
49 |
|
50 | function errHandler (ex) {
|
51 | if (!ex) { return; }
|
52 | if (!ex.inputError) {
|
53 |
|
54 | exit(ex);
|
55 | } else {
|
56 |
|
57 | console.error(ex.message);
|
58 | console.error('Try "istanbul help" for usage');
|
59 | exit(null, 1);
|
60 | }
|
61 | }
|
62 |
|
63 | function runCommand(args, callback) {
|
64 | var pos = findCommandPosition(args),
|
65 | command,
|
66 | commandArgs,
|
67 | commandObject;
|
68 |
|
69 | if (pos < 0) {
|
70 | return callback(inputError.create('Need a command to run'));
|
71 | }
|
72 |
|
73 | commandArgs = args.slice(0, pos);
|
74 | command = args[pos];
|
75 | commandArgs.push.apply(commandArgs, args.slice(pos + 1));
|
76 |
|
77 | try {
|
78 | commandObject = Command.create(command);
|
79 | } catch (ex) {
|
80 | errHandler(inputError.create(ex.message));
|
81 | return;
|
82 | }
|
83 | commandObject.run(commandArgs, errHandler);
|
84 | }
|
85 |
|
86 | function runToCompletion(args) {
|
87 | runCommand(args, errHandler);
|
88 | }
|
89 |
|
90 |
|
91 | if (require.main === module) {
|
92 | var args = Array.prototype.slice.call(process.argv, 2);
|
93 | runToCompletion(args);
|
94 | }
|
95 |
|
96 | module.exports = {
|
97 | runToCompletion: runToCompletion
|
98 | };
|
99 |
|