-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
85 lines (77 loc) · 1.82 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
"use strict";
var through = require("through");
var path = require("path");
var PluginError = require("plugin-error");
var Vinyl = require("vinyl");
module.exports = function(fileName, converter) {
if (!fileName) {
throw new PluginError(
"gulp-jsoncombine",
"Missing fileName option for gulp-jsoncombine"
);
}
if (!converter) {
throw new PluginError(
"gulp-jsoncombine",
"Missing converter option for gulp-jsoncombine"
);
}
var data = {};
var meta = {};
var firstFile = null;
// We keep track of when we should skip the conversion for error cases
var skipConversion = false;
function bufferContents(file) {
if (!firstFile) {
firstFile = file;
}
if (file.isNull()) {
return; // ignore
}
if (file.isStream()) {
skipConversion = true;
return this.emit(
"error",
new PluginError("gulp-jsoncombine", "Streaming not supported")
);
}
try {
var name = file.relative.substr(0, file.relative.length - 5);
data[name] = JSON.parse(file.contents.toString());
meta[name] = { cwd: file.cwd, base: file.base, path: file.path };
} catch (err) {
skipConversion = true;
return this.emit(
"error",
new PluginError(
"gulp-jsoncombine",
"Error parsing JSON: " +
err +
", file: " +
file.path.slice(file.base.length)
)
);
}
}
function endStream() {
if (firstFile && !skipConversion) {
var joinedPath = path.join(firstFile.base, fileName);
try {
var joinedFile = new Vinyl({
cwd: firstFile.cwd,
base: firstFile.base,
path: joinedPath,
contents: converter(data, meta)
});
this.emit("data", joinedFile);
} catch (e) {
return this.emit(
"error",
new PluginError("gulp-jsoncombine", e, { showStack: true })
);
}
}
this.emit("end");
}
return through(bufferContents, endStream);
};