UNPKG

1.73 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 },
11});
12
13//@
14//@ ### grep([options,] regex_filter, file [, file ...])
15//@ ### grep([options,] regex_filter, file_array)
16//@ Available options:
17//@
18//@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
19//@ + `-l`: Print only filenames of matching files
20//@
21//@ Examples:
22//@
23//@ ```javascript
24//@ grep('-v', 'GLOBAL_VARIABLE', '*.js');
25//@ grep('GLOBAL_VARIABLE', '*.js');
26//@ ```
27//@
28//@ Reads input string from given files and returns a string containing all lines of the
29//@ file that match the given `regex_filter`.
30function _grep(options, regex, files) {
31 // Check if this is coming from a pipe
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}
67module.exports = _grep;