-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgrep.rs
45 lines (40 loc) · 1.4 KB
/
grep.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//! A simple grep-like program using `kommand` and `InputTextStream`.
//! Unlike regular grep, this grep supports URLs and gzip. Perg!
use nameless::{InputTextStream, LazyOutput, MediaType, OutputTextStream};
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
/// # Arguments
///
/// * `pattern` - The regex to search for
/// * `output` - Output sink
/// * `inputs` - Input sources
/// * `inputs_with_matches` - Print only the names of the inputs containing matches
#[kommand::main]
fn main(
pattern: Regex,
output: LazyOutput<OutputTextStream>,
inputs: Vec<InputTextStream>,
#[kommand(short = 'l', long)] inputs_with_matches: bool,
) -> anyhow::Result<()> {
let mut output = output.materialize(MediaType::text())?;
let print_inputs = inputs.len() > 1;
'next_input: for input in inputs {
let pseudonym = input.pseudonym();
for line in BufReader::new(input).lines() {
let line = line?;
if pattern.is_match(&line) {
if inputs_with_matches {
output.write_pseudonym(&pseudonym)?;
writeln!(output, "")?;
continue 'next_input;
}
if print_inputs {
output.write_pseudonym(&pseudonym)?;
write!(output, ":")?;
}
writeln!(output, "{}", line)?;
}
}
}
Ok(())
}