-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
102 lines (82 loc) · 2.33 KB
/
index.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
var cp = require("child_process"),
path = require("path"),
Duplexer = require("plexer"),
Stream = require("stream"),
PluginError = require('plugin-error');
var PLUGIN_NAME = "gulp-spawn";
function gulpSpawn(options) {
"use strict";
var stream = new Stream.PassThrough({objectMode: true});
// options.cmd required
if (!options.cmd) {
throw new PluginError(PLUGIN_NAME,
"command (\"cmd\") argument required");
}
stream._transform = function (file, unused, cb) {
if (file.isNull()) {
stream.push(file);
return cb();
}
// rename file if optional `filename` function specified
if (options.filename && typeof options.filename === "function") {
var dir = path.dirname(file.path),
ext = path.extname(file.path),
base = path.basename(file.path, ext);
file.shortened = options.filename(base, ext);
file.path = path.join(dir, file.shortened);
}
// spawn program
var program = cp.spawn(options.cmd, options.args, options.opts);
// listen to stderr and emit errors if any
var errBuffer = new Buffer(0);
program.stderr.on("readable", function () {
var chunk;
while (chunk = program.stderr.read()) {
errBuffer = Buffer.concat([
errBuffer,
chunk
], errBuffer.length + chunk.length);
}
});
program.stderr.on("end", function () {
if (errBuffer.length) {
stream.emit("error", new PluginError(PLUGIN_NAME,
errBuffer.toString("utf-8")));
}
});
// check if we have a buffer or stream
if (file.contents instanceof Buffer) {
// create buffer
var newBuffer = new Buffer(0);
// when program receives data add it to buffer
program.stdout.on("readable", function () {
var chunk;
while (chunk = program.stdout.read()) {
newBuffer = Buffer.concat([
newBuffer,
chunk
], newBuffer.length + chunk.length);
}
});
// when program finishes call callback
program.stdout.on("end", function () {
file.contents = newBuffer;
stream.push(file);
cb();
});
// "execute"
// write file buffer to program
program.stdin.write(file.contents, function () {
program.stdin.end();
});
} else { // assume we have a stream.Readable
// stream away!
file.contents = file.contents
.pipe(new Duplexer(program.stdin, program.stdout));
stream.push(file);
cb();
}
};
return stream;
}
module.exports = gulpSpawn;