-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.js
116 lines (98 loc) · 2.77 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
'use strict';
var find = require('find'),
fs = require('fs'),
Q = require('q'),
path = require('path');
function readFile(filename) {
return Q.nfcall(fs.readFile, filename, 'utf-8');
}
function searchFile(data) {
return function(content) {
var match = content.match(data.regex),
linesMatch = content.match(data.lineRegEx)
return {
filename: data.filename,
match: match,
lines: linesMatch
};
};
}
function getFileFilter(fileFilter) {
if (typeof fileFilter === 'string') {
fileFilter = new RegExp(fileFilter);
} else if (typeof fileFilter === 'undefined') {
fileFilter = new RegExp('.');
}
return fileFilter;
}
function getRegEx(pattern, regex) {
var flags, term, grabLineRegEx
if (typeof pattern === 'object' && pattern.flags) {
term = pattern.term
flags = pattern.flags
} else {
term = pattern
flags = 'g'
}
grabLineRegEx = "(.*" + term + ".*)"
if (regex === 'line') {
return new RegExp(grabLineRegEx, flags)
}
return new RegExp(term, flags);
}
function getMatchedFiles(pattern, files) {
var matchedFiles = []
for (var i = files.length - 1; i >= 0; i--) {
matchedFiles.push(readFile(files[i])
.then(searchFile({
regex: getRegEx(pattern),
lineRegEx: getRegEx(pattern, 'line'),
filename: files[i]
})));
}
return matchedFiles;
}
function getResults(content) {
var results = {}
for (var i = 0; i < content.length; i++) {
var fileMatch = content[i].value;
if (fileMatch && fileMatch.match !== null) {
results[fileMatch.filename] = {
matches: fileMatch.match,
count: fileMatch.match.length,
line: fileMatch.lines
};
}
}
return results;
}
exports.find = function(pattern, directory, fileFilter) {
var deferred = Q.defer()
find
.file(getFileFilter(fileFilter), directory, function(files) {
Q.allSettled(getMatchedFiles(pattern, files))
.then(function (content) {
deferred.resolve(getResults(content));
})
.done();
})
.error(function (err){
deferred.reject(err)
});
return deferred.promise;
};
exports.findSync = function(pattern, directory, fileFilter) {
var deferred = Q.defer();
var files;
try {
files = find.fileSync(getFileFilter(fileFilter), directory);
Q.allSettled(getMatchedFiles(pattern, files))
.then(function (content) {
deferred.resolve(getResults(content));
})
.done();
} catch (err) {
deferred.reject(err)
}
return deferred.promise;
};