Skip to content
Newer
Older
100755 94 lines (75 sloc) 1.86 KB
7785b7d @tj Initial commit
authored
1 #!/usr/bin/env node
2
3 /**
4 * Module dependencies.
5 */
6
7 var program = require('commander')
8 , path = require('path')
9 , join = path.join
10 , fs = require('fs');
11
12 // options
13
14 program
5f5d6e6 @tj Release 1.0.0
authored
15 .version('1.0.0')
7785b7d @tj Initial commit
authored
16 .usage('[options] <query> [path ...]')
17 .option('-H, --hidden', 'search hidden files and directories')
18 .parse(process.argv);
19
20 // no args
21
22 if (!program.args.length) {
23 process.stdout.write(program.helpInformation());
24 process.exit(0);
25 }
26
27 // arguments
28
29 var query = program.args.shift()
30 , paths = program.args
31 , pending = paths.length
32 , re = new RegExp('(' + query + ')', 'ig');
33
34 // whitespace
35
36 process.on('exit', console.log);
37
6c2ce36 @tj Added default path of "."
authored
38 // default to the CWD
39
40 if (!paths.length) paths.push(process.cwd());
41
7785b7d @tj Initial commit
authored
42 /**
43 * Search `path`.
44 *
45 * @param {String} path
46 */
47
48 function search(path) {
49 fs.stat(path, function(err, stat){
50 if (err) throw err;
51 if (stat.isDirectory()) {
52 fs.readdir(path, function(err, files){
53 if (err) throw err;
54 files.filter(hidden).map(function(file){
55 return join(path, file);
56 }).forEach(search);
57 });
9526131 @tj Changed: only regular files for now
authored
58 } else if (stat.isFile()) {
7785b7d @tj Initial commit
authored
59 var lines = [];
60 fs.readFile(path, 'utf8', function(err, str){
61 if (err) throw err;
62 str.split('\n').forEach(function(line, i){
63 if (!re.test(line)) return;
64 lines.push([i, line]);
65 });
66
67 if (lines.length) {
68 console.log('\n \033[36m%s\033[0m', path);
69 lines.forEach(function(line){
70 var i = line[0]
71 , line = line[1];
72 line = line.replace(re, '\033[37;43m$1\033[0;90m');
41ccf3e @tj Fixed linenos
authored
73 console.log(' \033[90m%d: %s\033[0m', i+1, line);
7785b7d @tj Initial commit
authored
74 });
75 }
76 });
77 }
78 });
79 }
80
81 /**
82 * Filter hidden paths unless `--hidden` is used.
83 */
84
85 function hidden(path) {
86 if (program.hidden) return true;
87 return '.' != path[0];
88 }
89
90 /**
91 * Search the given paths.
92 */
93
94 paths.forEach(search);
Something went wrong with that request. Please try again.