-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
81 lines (72 loc) · 2.19 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
'use strict';
var fs = require('fs');
var path = require('path');
var objectAssign = require('object-assign');
var sortKeys = require('sort-keys');
var Transform = require('readable-stream/transform');
function exists(pth, mode) {
try {
fs.accessSync(pth, mode);
return true;
} catch (e) {
return false;
}
}
module.exports = function(regexp, fn, opt) {
var options = objectAssign({
path: '',
filename: 'gulp-search-menifest.json'
}, opt);
return new Transform({
objectMode: true,
transform: function(file, enc, callback) {
if (file.isNull()) {
return callback(null, file);
}
function doSearch() {
if (file.isStream()) {
this.emit('error', new PluginError('gulp-search', 'Streams aren\'t supported'));
return callback(null, file);
}
if (file.isBuffer()) {
if (regexp instanceof RegExp) {
var str = String(file.contents),
entris = [],
basePath = options.path,
filename = options.filename,
filePath = path.join(basePath, filename);
if(options.group) {
var matches = [];
while (matches = regexp.exec(str)) {
entris.push(matches[options.group]);
}
} else {
entris = str.match(regexp);
}
var fileStr = '';
if (entris && entris.length > 0) {
entris.forEach(function (item) {
if (!exists(filePath)) {
if (!exists(basePath)) {
fs.mkdirSync(basePath);
}
fs.writeFileSync(filePath, JSON.stringify({}, null, ' '));
}
fileStr = fs.readFileSync(filePath, {
encoding: 'utf8'
});
var oldObj = JSON.parse(fileStr);
var newObj = objectAssign(oldObj, fn(item))
fs.writeFileSync(filePath, JSON.stringify(sortKeys(newObj), null, ' '), {
flag: 'w'
});
});
}
}
}
callback(null, file);
}
doSearch();
}
});
};