1 | var common = require('./common');
|
2 | var fs = require('fs');
|
3 |
|
4 | common.register('grep', _grep, {
|
5 | globStart: 2,
|
6 | canReceivePipe: true,
|
7 | cmdOptions: {
|
8 | 'v': 'inverse',
|
9 | 'l': 'nameOnly',
|
10 | 'i': 'ignoreCase',
|
11 | },
|
12 | });
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | function _grep(options, regex, files) {
|
34 |
|
35 | var pipe = common.readFromPipe();
|
36 |
|
37 | if (!files && !pipe) common.error('no paths given', 2);
|
38 |
|
39 | files = [].slice.call(arguments, 2);
|
40 |
|
41 | if (pipe) {
|
42 | files.unshift('-');
|
43 | }
|
44 |
|
45 | var grep = [];
|
46 | if (options.ignoreCase) {
|
47 | regex = new RegExp(regex, 'i');
|
48 | }
|
49 | files.forEach(function (file) {
|
50 | if (!fs.existsSync(file) && file !== '-') {
|
51 | common.error('no such file or directory: ' + file, 2, { continue: true });
|
52 | return;
|
53 | }
|
54 |
|
55 | var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');
|
56 | if (options.nameOnly) {
|
57 | if (contents.match(regex)) {
|
58 | grep.push(file);
|
59 | }
|
60 | } else {
|
61 | var lines = contents.split('\n');
|
62 | lines.forEach(function (line) {
|
63 | var matched = line.match(regex);
|
64 | if ((options.inverse && !matched) || (!options.inverse && matched)) {
|
65 | grep.push(line);
|
66 | }
|
67 | });
|
68 | }
|
69 | });
|
70 |
|
71 | return grep.join('\n') + '\n';
|
72 | }
|
73 | module.exports = _grep;
|