-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
95 lines (91 loc) · 2.9 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
93
94
95
/*
* gulp-inject-string
* https://github.com/Schmicko/gulp-inject-string
*
* Copyright (c) 2014 Michael Hazell
* Licensed under the MIT license.
*/
var es = require('event-stream'),
PluginError = require('plugin-error');
var stream = function(injectMethod) {
return es.map(function(file, cb) {
try {
file.contents = new Buffer(injectMethod(String(file.contents)));
} catch (err) {
return cb(new PluginError('gulp-inject-string', err));
}
cb(null, file);
});
};
module.exports = {
append: function(str) {
return stream(function(fileContents) {
// assume str is a string for now
return fileContents + String(str);
});
},
prepend: function(str) {
return stream(function(fileContents) {
// assume str is a string for now
return String(str) + fileContents;
});
},
wrap: function(start, end) {
return stream(function(fileContents) {
// assume start and end are strings
return String(start) + fileContents + String(end);
});
},
before: function(search, str) {
return stream(function(fileContents) {
var index, start, end;
// the simplest thing ...
index = fileContents.indexOf(search);
if (index > -1) {
start = fileContents.substr(0, index);
end = fileContents.substr(index);
return start + str + end;
} else {
return fileContents;
}
});
},
after: function(search, str) {
return stream(function(fileContents) {
var index, start, end;
index = fileContents.indexOf(search);
if (index > -1) {
start = fileContents.substr(0, index + search.length);
end = fileContents.substr(index + search.length);
return start + str + end;
} else {
return fileContents;
}
});
},
beforeEach: function(search, str) {
return stream(function(fileContents) {
return fileContents.split(search).join(str + search);
});
},
afterEach: function(search, str) {
return stream(function(fileContents) {
return fileContents.split(search).join(search + str);
});
},
replace: function(search, str) {
return stream(function(fileContents) {
return fileContents.replace(new RegExp(search, 'g'), str);
});
},
custom: function(callback) {
return stream(function(fileContents) {
if (typeof callback !== "function") {
return fileContents;
}
var newContents = callback(fileContents);
return typeof newContents === 'string' ? newContents : fileContents;
});
}
};
module.exports._stream = stream;