|
| 1 | +#!/usr/bin/env node |
| 2 | +const fs = require('fs') |
| 3 | + |
| 4 | +// Helpers |
| 5 | +const availables_options = [ |
| 6 | + 'n', // add line numbers |
| 7 | + 'l', // print file names where pattern is found |
| 8 | + 'i', // ignore case |
| 9 | + 'v', // reverse files results |
| 10 | + 'x' // match entire line |
| 11 | +]; |
| 12 | + |
| 13 | +const does_line_matche_pattern = (line, pattern) => { |
| 14 | + let left = line; |
| 15 | + let right = pattern; |
| 16 | + |
| 17 | + if (is_option_set('i')) { |
| 18 | + left = line.toLowerCase() |
| 19 | + right = pattern.toLowerCase() |
| 20 | + } |
| 21 | + |
| 22 | + if (is_option_set('x')) { |
| 23 | + return left === right; |
| 24 | + } |
| 25 | + |
| 26 | + return left.match(right) !== null; |
| 27 | + |
| 28 | +} |
| 29 | + |
| 30 | +const getConfigFromArgs = () => { |
| 31 | + const config = { |
| 32 | + 'pattern': '', |
| 33 | + 'options': [], |
| 34 | + 'files': [] |
| 35 | + }; |
| 36 | + |
| 37 | + let has_pattern_been_found = false; |
| 38 | + |
| 39 | + process.argv.slice(2).forEach(val => { |
| 40 | + if (has_pattern_been_found) { |
| 41 | + config.files.push(val) |
| 42 | + } else if (val.indexOf('-') !== -1) { |
| 43 | + const option = val.replace('-', '') |
| 44 | + |
| 45 | + if (!availables_options.includes(option)) { |
| 46 | + throw new Error(`Unknown option ${option}`) |
| 47 | + } |
| 48 | + |
| 49 | + config.options.push(option) |
| 50 | + } else { |
| 51 | + has_pattern_been_found = true |
| 52 | + config.pattern = val |
| 53 | + } |
| 54 | + }) |
| 55 | + |
| 56 | + return config; |
| 57 | +} |
| 58 | + |
| 59 | +const config = getConfigFromArgs() |
| 60 | +const is_option_set = option => config.options.includes(option); |
| 61 | + |
| 62 | +// Actual script |
| 63 | +config.files.forEach(file => { |
| 64 | + const data = fs.readFileSync(file, { encoding: 'utf-8' }) |
| 65 | + |
| 66 | + if (is_option_set('l')) { |
| 67 | + data.split('\n').find(line => { |
| 68 | + const does_line_match_pattern = does_line_matche_pattern(line, config.pattern) |
| 69 | + |
| 70 | + return is_option_set('v') ? !does_line_match_pattern : does_line_match_pattern |
| 71 | + }) && console.log(file) |
| 72 | + } else { |
| 73 | + data.split('\n').forEach((line, index) => { |
| 74 | + let result = ''; |
| 75 | + let should_output_line = does_line_matche_pattern(line, config.pattern); |
| 76 | + |
| 77 | + if (is_option_set('v')) { |
| 78 | + should_output_line = !should_output_line; |
| 79 | + } |
| 80 | + |
| 81 | + if (should_output_line) { |
| 82 | + if (config.files.length > 1) { |
| 83 | + result += `${file}:` |
| 84 | + } |
| 85 | + |
| 86 | + if (is_option_set('n')) { |
| 87 | + result += `${index+1}:`; |
| 88 | + } |
| 89 | + |
| 90 | + result += line; |
| 91 | + |
| 92 | + console.log(result) |
| 93 | + } |
| 94 | + }) |
| 95 | + } |
| 96 | +}); |
0 commit comments