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 | },
|
11 | });
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | function _grep(options, regex, files) {
|
31 |
|
32 | var pipe = common.readFromPipe();
|
33 |
|
34 | if (!files && !pipe) common.error('no paths given', 2);
|
35 |
|
36 | files = [].slice.call(arguments, 2);
|
37 |
|
38 | if (pipe) {
|
39 | files.unshift('-');
|
40 | }
|
41 |
|
42 | var grep = [];
|
43 | files.forEach(function (file) {
|
44 | if (!fs.existsSync(file) && file !== '-') {
|
45 | common.error('no such file or directory: ' + file, 2, { continue: true });
|
46 | return;
|
47 | }
|
48 |
|
49 | var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8');
|
50 | if (options.nameOnly) {
|
51 | if (contents.match(regex)) {
|
52 | grep.push(file);
|
53 | }
|
54 | } else {
|
55 | var lines = contents.split('\n');
|
56 | lines.forEach(function (line) {
|
57 | var matched = line.match(regex);
|
58 | if ((options.inverse && !matched) || (!options.inverse && matched)) {
|
59 | grep.push(line);
|
60 | }
|
61 | });
|
62 | }
|
63 | });
|
64 |
|
65 | return grep.join('\n') + '\n';
|
66 | }
|
67 | module.exports = _grep;
|