This repository was archived by the owner on Nov 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
66 lines (59 loc) · 1.78 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
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var glob = require('glob');
var diff = require('diff');
var fs = require('fs');
var path = require('path');
var PLUGIN_NAME = "gulp-apply-patch";
module.exports = function (patches, opts) {
opts = opts || {};
var patchLists = {};
// Parse glob
if(typeof(patches)==="string") {
patches = glob.sync(patches)
.map(function(t) { return fs.readFileSync(t) });
}
patches.forEach(function(patch){
patch = opts.replaceCRLF
? patch.toString().replace(/\r\n/g,"\n")
: patch.toString();
diff.parsePatch(patch.toString()).forEach(function(parsedPatch){
var srcName = path.normalize(parsedPatch.oldFileName);
var list = patchLists[srcName] = patchLists[srcName] || [];
list.push(parsedPatch);
});
});
return through.obj(function (file, enc, cb) {
var self = this;
function applyPatch(src,patch,i) {
var results = diff.applyPatch(src, patch);
if(results===false) {
self.emit('error', new gutil.PluginError(PLUGIN_NAME, "Failed to apply patch "+patch.oldFileName));
}
return results;
}
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
var patchesForFile = patchLists[file.relative];
if(patchesForFile!==undefined) {
try {
var originalContents = opts.replaceCRLF
? file.contents.toString().replace(/\r\n/g,"\n")
: file.contents.toString();
file.contents = Buffer.from(
patchesForFile.reduce(applyPatch, originalContents)
);
} catch (err) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, err));
}
}
cb(null, file);
});
};