UNPKG

1.83 kBJavaScriptView Raw
1var common = require('./common');
2var fs = require('fs');
3
4common.register('grep', _grep, {
5 globStart: 2, // don't glob-expand the regex
6 canReceivePipe: true,
7 cmdOptions: {
8 'v': 'inverse',
9 'l': 'nameOnly',
10 'i': 'ignoreCase',
11 },
12});
13
14//@
15//@ ### grep([options,] regex_filter, file [, file ...])
16//@ ### grep([options,] regex_filter, file_array)
17//@
18//@ Available options:
19//@
20//@ + `-v`: Invert `regex_filter` (only print non-matching lines).
21//@ + `-l`: Print only filenames of matching files.
22//@ + `-i`: Ignore case.
23//@
24//@ Examples:
25//@
26//@ ```javascript
27//@ grep('-v', 'GLOBAL_VARIABLE', '*.js');
28//@ grep('GLOBAL_VARIABLE', '*.js');
29//@ ```
30//@
31//@ Reads input string from given files and returns a string containing all lines of the
32//@ file that match the given `regex_filter`.
33function _grep(options, regex, files) {
34 // Check if this is coming from a pipe
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}
73module.exports = _grep;