1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | var spawn = require('child_process').spawn;
|
12 |
|
13 |
|
14 | var utils = module.exports = {};
|
15 |
|
16 |
|
17 | utils.task = require('../util/task');
|
18 | utils.namespace = require('../util/namespace');
|
19 |
|
20 |
|
21 | utils.hooker = require('hooker');
|
22 | utils.async = require('async');
|
23 | var _ = utils._ = require('underscore');
|
24 |
|
25 |
|
26 | _.str = require('underscore.string');
|
27 | _.mixin(_.str.exports());
|
28 |
|
29 |
|
30 | utils.linefeed = process.platform === 'win32' ? '\r\n' : '\n';
|
31 |
|
32 |
|
33 | utils.normalizelf = function(str) {
|
34 | return str.replace(/\r\n|\n/g, utils.linefeed);
|
35 | };
|
36 |
|
37 |
|
38 |
|
39 | var kindsOf = {};
|
40 | 'Number String Boolean Function RegExp Array Date Error'.split(' ').forEach(function(k) {
|
41 | kindsOf['[object ' + k + ']'] = k.toLowerCase();
|
42 | });
|
43 | utils.kindOf = function(value) {
|
44 |
|
45 | if (value == null) { return String(value); }
|
46 |
|
47 | return kindsOf[kindsOf.toString.call(value)] || 'object';
|
48 | };
|
49 |
|
50 |
|
51 | utils.toArray = Function.call.bind(Array.prototype.slice);
|
52 |
|
53 |
|
54 | utils.repeat = function(n, str) {
|
55 | return new Array(n + 1).join(str || ' ');
|
56 | };
|
57 |
|
58 |
|
59 | utils.pluralize = function(n, str, separator) {
|
60 | var parts = str.split(separator || '/');
|
61 | return n === 1 ? (parts[0] || '') : (parts[1] || '');
|
62 | };
|
63 |
|
64 |
|
65 | utils.recurse = function recurse(value, fn, fnContinue) {
|
66 | var obj;
|
67 | if (fnContinue && fnContinue(value) === false) {
|
68 |
|
69 | return value;
|
70 | } else if (utils.kindOf(value) === 'array') {
|
71 |
|
72 | return value.map(function(value) {
|
73 | return recurse(value, fn, fnContinue);
|
74 | });
|
75 | } else if (utils.kindOf(value) === 'object') {
|
76 |
|
77 | obj = {};
|
78 | Object.keys(value).forEach(function(key) {
|
79 | obj[key] = recurse(value[key], fn, fnContinue);
|
80 | });
|
81 | return obj;
|
82 | } else {
|
83 |
|
84 | return fn(value);
|
85 | }
|
86 | };
|
87 |
|
88 |
|
89 | utils.spawn = function(opts, done) {
|
90 | var child = spawn(opts.cmd, opts.args, opts.opts);
|
91 | var stdout = '';
|
92 | var stderr = '';
|
93 | child.stdout.on('data', function(buf) { stdout += buf; });
|
94 | child.stderr.on('data', function(buf) { stderr += buf; });
|
95 | child.on('exit', function(code) {
|
96 |
|
97 | stdout = _.rtrim(stdout);
|
98 | stderr = _.rtrim(stderr);
|
99 |
|
100 | var MyString = String;
|
101 |
|
102 | var result = new MyString(code === 0 ? stdout : 'fallback' in opts ? opts.fallback : stderr);
|
103 | result.stdout = stdout;
|
104 | result.stderr = stderr;
|
105 | result.code = code;
|
106 |
|
107 | done(code === 0 || 'fallback' in opts ? null: result, result, code);
|
108 | });
|
109 | return child;
|
110 | };
|