forked from crissdev/gulp-yaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (65 loc) · 2.22 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
'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var yaml = require('js-yaml');
var xtend = require('xtend');
var BufferStreams = require('bufferstreams');
var PluginError = gutil.PluginError;
var PLUGIN_NAME = 'gulp-json-to-yaml';
function json2yaml(buffer, options) {
var contents = buffer.toString('utf8');
var src = JSON.parse(contents);
var ymlDocument = options.safe ? yaml.safeDump(src, options) : yaml.dump(src, options);
return new Buffer(ymlDocument);
}
module.exports = function(options) {
options = xtend({safe: true, replacer: null, space: null}, options);
var providedFilename = options.filename;
return through.obj(function(file, enc, callback) {
if (!providedFilename) {
options.filename = file.path;
}
if (file.isBuffer()) {
if (file.contents.length === 0) {
this.emit('error', new PluginError(PLUGIN_NAME, 'File ' + file.path +
' is empty. JSON loader cannot load empty content'));
return callback();
}
try {
file.contents = json2yaml(file.contents, options);
file.path = gutil.replaceExtension(file.path, '.yaml');
}
catch (error) {
this.emit('error', new PluginError(PLUGIN_NAME, error, {showStack: true}));
return callback();
}
}
else if (file.isStream()) {
var _this = this;
var streamer = new BufferStreams(function(err, buf, cb) {
if (err) {
_this.emit('error', new PluginError(PLUGIN_NAME, err, {showStack: true}));
}
else {
if (buf.length === 0) {
_this.emit('error', new PluginError(PLUGIN_NAME, 'File ' + file.path +
' is empty. JSON loader cannot load empty content'));
}
else {
try {
var parsed = json2yaml(buf, options);
file.path = gutil.replaceExtension(file.path, '.yaml');
cb(null, parsed);
}
catch (error) {
_this.emit('error', new PluginError(PLUGIN_NAME, error, {showStack: true}));
}
}
}
});
file.contents = file.contents.pipe(streamer);
}
this.push(file);
callback();
});
};