Permalink
Browse files

Added lines span and matches counting

  • Loading branch information...
1 parent 5363cc2 commit df76e9c7948f5f8ab36a6908486d1a5a38fe7237 @stagas committed Aug 25, 2011
Showing with 46 additions and 7 deletions.
  1. +46 −7 bin/search
View
@@ -15,6 +15,8 @@ program
.version('0.0.2')
.usage('[options] <query> [path ...]')
.option('-H, --hidden', 'search hidden files and directories')
+ .option('-s, --span <lines>', 'number of lines to span result')
+ .option('-c, --count', 'count results next to line numbers')
.parse(process.argv);
// no args
@@ -28,6 +30,7 @@ if (!program.args.length) {
var query = program.args.shift()
, paths = program.args
+ , span = +program.span
, pending = paths.length
, re = new RegExp('(' + query + ')', 'ig');
@@ -59,19 +62,55 @@ function search(path) {
var lines = [];
fs.readFile(path, 'utf8', function(err, str){
if (err) throw err;
- str.split('\n').forEach(function(line, i){
- if (!re.test(line)) return;
- lines.push([i, line]);
+ var docLines = str.split('\n');
+ var r = 0;
+ docLines.forEach(function(line, i){
+ var match = line.match(re);
+ if (!match) return;
+ for (var n = span; n > 0; n--) {
+ lines.push([i - n, docLines[i - n]]);
+ }
+ lines.push([ i, line, match.length]);
+ for (var n = 1; n <= span; n++) {
+ lines.push([i + n, docLines[i + n]]);
+ }
});
if (lines.length) {
- console.log('\n \033[36m%s\033[0m', path);
- lines.forEach(function(line){
+ var r = 0, space = ' ', linesUnique = {};
+ lines.forEach(function(line, index){
var i = line[0]
+ , highlight = line[2]
, line = line[1];
- line = line.replace(re, '\033[37;43m$1\033[0;90m');
- console.log(' \033[90m%d: %s\033[0m', i, line);
+ if (linesUnique[i]) {
+ if (highlight) linesUnique[i].highlight = highlight
+ } else {
+ linesUnique[i] = { i: i + 1, highlight: highlight, line: line };
+ }
});
+ console.log('\n \033[36m%s\033[0m', path);
+ var last = 0;
+ Object.keys(linesUnique).forEach(function(ln){
+ var i = linesUnique[ln].i
+ , highlight = linesUnique[ln].highlight
+ , line = linesUnique[ln].line;
+ if ('undefined' === typeof line) return;
+ if (span && last + 1 != i && i != 0) {
+ console.log(space + space + ' ...');
+ }
+ last = i;
+ line = line.replace(re, '\033[07;43m$1\033[0;90m');
+ if (highlight) r += highlight;
+ console.log((highlight && '\033[37m' || '\033[90m') + (program.count && highlight
+ ? ' \033[36m' + r + '\033[37m'
+ : (span && space || ' '))
+ + ' %s\033[90m: %s\033[0m', i, line);
+ if (program.count) space = new Array(2 + r.toString().length).join(' ')
+ });
+ if (span && linesUnique[last - 1].i < docLines.length - 1) {
+ console.log(space + space + ' ...');
+ }
+ console.log(space + ' --- \033[33m%s\033[0;90m occurrences of \033[37m"%s"', r, query);
}
});
}

0 comments on commit df76e9c

Please sign in to comment.