-
Notifications
You must be signed in to change notification settings - Fork 1
/
run.js
102 lines (76 loc) · 2.08 KB
/
run.js
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
"use strict";
var defaults = require("lodash/object/defaults"),
last = require("lodash/array/last"),
rest = require("lodash/array/rest"),
spawn = require("child_process").spawn,
trimRight = require("lodash/string/trimRight"),
popOptions = require("./common").popOptions,
Builder = require("./Builder");
module.exports = factory;
module.exports.run = run;
function factory(command/*, args..., [options] */) {
var args = rest(arguments),
options = popOptions(args);
var debug = options.debug,
log = debug.bind(null,"(" + command + ")"),
task = run.bind(null,command,args,log),
builder = new Builder(task,debug),
rebuild = builder.rebuild,
wait = builder.wait;
middleware.wait = wait;
middleware.rebuild = rebuild;
return middleware;
function middleware(req, res, next) {
rebuild();
wait(next);
}
}
function run(command, args, log, callback) {
var output = [],
env = process.env,
envPath = env.PATH;
log("Running","`" + command,args.join(" ") + "`");
env = defaults({
PATH: "node_modules/.bin:" + envPath
},env);
var child = spawn(command,args,{
env: env,
stdio: ["ignore", "pipe", "pipe"]
});
child.stdout.setEncoding("utf8");
child.stdout.on("data",writeOut);
child.stderr.setEncoding("utf8");
child.stderr.on("data",writeErr);
child.on("exit",exit);
return stop;
function stop(cancelledCallback) {
log("Killing process");
callback = cancelledCallback;
child.kill("SIGINT");
}
function exit(code) {
if (code === 0) {
log("Success");
callback();
} else {
var err = new Error(command + " exited with error status " + code);
err.stack = output.join("");
callback(err);
}
}
function writeErr(data) {
writeIO("err:",data);
}
function writeOut(data) {
writeIO("out:",data);
}
function writeIO(prefix, data) {
var lines = data.split("\n");
if (!last(lines).trim())
lines.pop();
lines.forEach(function(line) {
log(prefix,trimRight(line));
});
output.push(data);
}
}