-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
75 lines (57 loc) · 2.02 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
/* jshint node: true */
var xmljs = require('libxmljs');
var through = require('through2');
var PluginError = require('gulp-util').PluginError;
module.exports = function (editor, namespace) {
// edit XML document by user specific function
function editByFunction(xmlDoc, xmljs) {
return editor(xmlDoc, xmljs).toString();
}
// edit XML document by user specific object
function editByObject(xmlDoc, xmljs, ee) {
editor.forEach(function(ed) {
var elem = (namespace == undefined) ? xmlDoc.get(ed.path) : xmlDoc.get(ed.path, namespace);
if (!elem || !(elem instanceof xmljs.Element)) {
ee.emit('error', new PluginError('gulp-xml-editor', 'Can\'t find element at "' + ed.path + '"'));
return;
}
if (ed.text !== undefined && ed.text !== null) {
elem.text(ed.text);
}
var attrs = ed.attrs || [];
if (ed.attr) attrs.push(ed.attr);
attrs.forEach(function(attr) {
elem.attr(attr);
});
});
return xmlDoc.toString();
}
var editByXXX;
// check options
if (typeof editor === 'function') editByXXX = editByFunction;
else if (editor instanceof Array) editByXXX = editByObject;
else if (typeof editor === 'undefined') throw new PluginError('gulp-xml-editor', 'missing "editor" option');
else throw new PluginError('gulp-xml-editor', '"editor" option must be a function or array');
// create through object
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-xml-editor', 'Streaming is not supported'));
return callback();
}
// edit XML document
try {
file.contents = new Buffer(editByXXX(xmljs.parseXmlString(file.contents.toString('utf8')), xmljs, this));
}
catch (err) {
this.emit('error', new PluginError('gulp-xml-editor', err));
}
this.push(file);
callback();
});
};