-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (75 loc) · 2.58 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
/*jslint node: true, vars: true, unparam: true, nomen: true */
"use strict";
var util = require("util");
var stream = require("readable-stream");
var globalBeepOnError = !!process.env.GULP_BEEPONERROR;
function Sink() {
stream.Writable.call(this, { objectMode: true });
}
util.inherits(Sink, stream.Writable);
Sink.prototype._write = function (chunk, enc, cb) {
return cb();
};
module.exports = function taskFromStreams(options, streamsProvider) {
if (streamsProvider === undefined) {
streamsProvider = options;
options = undefined;
}
if (options && typeof streamsProvider !== "function") {
streamsProvider = options.streamsProvider;
}
if (typeof streamsProvider !== "function") {
throw new Error("Streams provider is required");
}
var beepOnError = (options && options.hasOwnProperty("beepOnError")
? options.beepOnError
: globalBeepOnError);
return function taskFromStreamsRun(cb) {
// define error/success handlers
var failed = false;
function onError(err) {
failed = true;
if (beepOnError && process.stdout && process.stdout.isTTY) {
process.stdout.write('\x07'); // system beep
}
return cb(err);
}
function onSuccess() {
if (!failed) {
return cb();
}
}
// run provider to get streams
var s;
try {
s = streamsProvider();
} catch (e) {
return onError(e);
}
// validate streams
if (!Array.isArray(s) || s.length === 0) {
return onError(new Error("Streams provider must return a non-empty array"));
}
// connect streams
var lastStream, stream, i, l;
for (i = 0, l = s.length; i < l; i += 1) {
stream = s[i];
if (!stream || !stream.on || !stream.pipe) {
return onError(new Error("Invalid stream at position " + i));
}
stream.on("error", onError);
if (lastStream) { lastStream.pipe(stream); }
lastStream = stream;
}
// terminate stream pipe with a writable "sink";
// this is to prevent buffering/back-pressure mechanism
// in stream2 from kicking in and blocking task completion
if (lastStream.readable) {
var sink = new Sink();
lastStream.pipe(sink);
lastStream = sink;
}
// when the last stream is done, task is done too
lastStream.on("finish", onSuccess);
};
};