UNPKG

2.51 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3/*
4 Copyright (c) 2012, Yahoo! Inc. All rights reserved.
5 Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
6 */
7
8
9var async = require('async'),
10 Command = require('./command'),
11 inputError = require('./util/input-error'),
12 exitProcess = process.exit; //hold a reference to original process.exit so that we are not affected even when a test changes it
13
14require('./register-plugins');
15
16function 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
28function exit(ex, code) {
29 // flush output for Node.js Windows pipe bug
30 // https://github.com/joyent/node/issues/6247 is just one bug example
31 // https://github.com/visionmedia/mocha/issues/333 has a good discussion
32 var streams = [process.stdout, process.stderr];
33 async.forEach(streams, function (stream, done) {
34 // submit a write request and wait until it's written
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; // turn it into an uncaught exception
43 }
44 } else {
45 exitProcess(code);
46 }
47 });
48}
49
50function errHandler (ex) {
51 if (!ex) { return; }
52 if (!ex.inputError) {
53 // exit with exception stack trace
54 exit(ex);
55 } else {
56 //don't print nasty traces but still exit(1)
57 console.error(ex.message);
58 console.error('Try "istanbul help" for usage');
59 exit(null, 1);
60 }
61}
62
63function 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
86function runToCompletion(args) {
87 runCommand(args, errHandler);
88}
89
90/* istanbul ignore if: untestable */
91if (require.main === module) {
92 var args = Array.prototype.slice.call(process.argv, 2);
93 runToCompletion(args);
94}
95
96module.exports = {
97 runToCompletion: runToCompletion
98};
99