forked from lazd/gulp-replace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
95 lines (78 loc) · 2.52 KB
/
index.js
File metadata and controls
95 lines (78 loc) · 2.52 KB
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
95
'use strict';
var Transform = require('readable-stream/transform');
var rs = require('replacestream');
var istextorbinary = require('istextorbinary');
var lodash = require('lodash');
module.exports = function(search, replacement, options) {
return new Transform({
objectMode: true,
transform: function(file, enc, callback) {
var replacementWrap = wrapReplacement(replacement, file);
if (file.isNull()) {
return callback(null, file);
}
function doReplace() {
if (file.isStream()) {
file.contents = file.contents.pipe(rs(search, replacementWrap));
return callback(null, file);
}
if (file.isBuffer()) {
if (search instanceof RegExp) {
file.contents = new Buffer(String(file.contents).replace(search, replacementWrap));
}
else {
var chunks = String(file.contents).split(search);
var result;
if (typeof replacementWrap === 'function') {
// Start with the first chunk already in the result
// Replacements will be added thereafter
// This is done to avoid checking the value of i in the loop
result = [ chunks[0] ];
// The replacement function should be called once for each match
for (var i = 1; i < chunks.length; i++) {
// Add the replacement value
result.push(replacementWrap(search));
// Add the next chunk
result.push(chunks[i]);
}
result = result.join('');
}
else {
result = chunks.join(replacementWrap);
}
file.contents = new Buffer(result);
}
return callback(null, file);
}
callback(null, file);
}
if (options && options.skipBinary) {
istextorbinary.isText(file.path, file.contents, function(err, result) {
if (err) {
return callback(err, file);
}
if (!result) {
callback(null, file);
} else {
doReplace();
}
});
return;
}
doReplace();
}
});
};
function wrapReplacement(replacement, file) {
if (typeof replacement !== 'function') {
return replacement;
}
return function replacementWrap() {
var argsArray = lodash.values(arguments);
var args = [file];
argsArray.forEach((value) => {
args.push(value);
});
return replacement.apply(this, args);
};
}