UNPKG

1.76 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 Command = require('./command'),
10 inputError = require('./util/input-error'),
11 exit = process.exit; //hold a reference to original process.exit so that we are not affected even when a test changes it
12
13require('./register-plugins');
14
15function findCommandPosition(args) {
16 var i;
17
18 for (i = 0; i < args.length; i += 1) {
19 if (args[i].charAt(0) !== '-') {
20 return i;
21 }
22 }
23
24 return -1;
25}
26
27function errHandler (ex) {
28 if (!ex) { return; }
29 if (!ex.inputError) {
30 throw ex; // turn it into an uncaught exception
31 } else {
32 //don't print nasty traces but still exit(1)
33 console.error(ex.message);
34 console.error('Try "istanbul help" for usage');
35 exit(1);
36 }
37}
38
39function runCommand(args, callback) {
40 var pos = findCommandPosition(args),
41 command,
42 commandArgs,
43 commandObject;
44
45 if (pos < 0) {
46 return callback(inputError.create('Need a command to run'));
47 }
48
49 commandArgs = args.slice(0, pos);
50 command = args[pos];
51 commandArgs.push.apply(commandArgs, args.slice(pos + 1));
52
53 try {
54 commandObject = Command.create(command);
55 } catch (ex) {
56 errHandler(inputError.create(ex.message));
57 }
58 commandObject.run(commandArgs, errHandler);
59}
60
61function runToCompletion(args) {
62 runCommand(args, errHandler);
63}
64
65/* istanbul ignore if: untestable */
66if (require.main === module) {
67 var args = Array.prototype.slice.call(process.argv, 2);
68 runToCompletion(args);
69}
70
71module.exports = {
72 runToCompletion: runToCompletion
73};
74