forked from gulp-community/gulp-json-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (74 loc) · 2.49 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
/* jshint node: true */
var jsbeautify = require('js-beautify').js_beautify;
var merge = require('deepmerge');
var through = require('through2');
var PluginError = require('gulp-util').PluginError;
var detectIndent = require('detect-indent');
module.exports = function (editor, jsbeautifyOptions) {
/*
create 'editBy' function from 'editor'
*/
var editBy;
if (typeof editor === 'function') {
// edit JSON object by user specific function
editBy = function(json, file) { return editor(json, file); };
}
else if (typeof editor === 'object') {
// edit JSON object by merging with user specific object
editBy = function(json) { return merge(json, editor); };
}
else if (typeof editor === 'undefined') {
throw new PluginError('gulp-json-editor', 'missing "editor" option');
}
else {
throw new PluginError('gulp-json-editor', '"editor" option must be a function or object');
}
/*
js-beautify option
*/
jsbeautifyOptions = jsbeautifyOptions || {};
// always beautify output
var beautify = true;
/*
create through object and return it
*/
return through.obj(function (file, encoding, callback) {
// ignore it
if (file.isNull()) {
this.push(file);
return callback();
}
// stream is not supported
if (file.isStream()) {
this.emit('error', new PluginError('gulp-json-editor', 'Streaming is not supported'));
return callback();
}
try {
// try to get current indentation
var indent = detectIndent(file.contents.toString('utf8'));
// beautify options for this particular file
var beautifyOptions = merge({}, jsbeautifyOptions); // make copy
beautifyOptions.indent_size = beautifyOptions.indent_size || indent.amount || 2;
beautifyOptions.indent_char = beautifyOptions.indent_char || (indent.type === 'tab' ? '\t' : ' ');
// transform file
var rawJSON = editBy(JSON.parse(file.contents.toString('utf8')), file);
// skip file if returned "false"
if (rawJSON === false) {
return callback();
}
// get transformed file as string notation
var json = JSON.stringify(rawJSON, null, indent.indent);
// beautify JSON
if (beautify) {
json = jsbeautify(json, beautifyOptions);
}
// write it to file
file.contents = new Buffer(json);
}
catch (err) {
this.emit('error', new PluginError('gulp-json-editor', err));
}
this.push(file);
callback();
});
};