rs_grok_pattern_checker/
lib.rs1use std::io;
2
3use io::BufWriter;
4use io::Write;
5
6use io::BufRead;
7
8use grok::Grok;
9use grok::Pattern;
10
11pub struct GrokPattern {
12 pub pattern: Pattern,
13}
14
15impl GrokPattern {
16 pub fn match_to_writer<W>(&self, text: &str, wtr: &mut W) -> Result<(), io::Error>
17 where
18 W: FnMut(&str, &str) -> Result<(), io::Error>,
19 {
20 let om: Option<_> = self.pattern.match_against(text);
21 let m = om.ok_or_else(|| io::Error::other("no match got"))?;
22 for (key, val) in &m {
23 wtr(key, val)?;
24 }
25 Ok(())
26 }
27
28 pub fn texts2match2writer<W, I>(&self, texts: I, wtr: &mut W) -> Result<(), io::Error>
29 where
30 I: Iterator<Item = Result<String, io::Error>>,
31 W: FnMut(&str, &str) -> Result<(), io::Error>,
32 {
33 for rtxt in texts {
34 let txt: String = rtxt?;
35 self.match_to_writer(&txt, wtr)?;
36 }
37 Ok(())
38 }
39
40 pub fn reader2txts2match2writer<W, R>(&self, texts: R, wtr: &mut W) -> Result<(), io::Error>
41 where
42 R: BufRead,
43 W: FnMut(&str, &str) -> Result<(), io::Error>,
44 {
45 let lines = texts.lines();
46 self.texts2match2writer(lines, wtr)
47 }
48
49 pub fn stdin2txts2match2writer<W>(&self, wtr: &mut W) -> Result<(), io::Error>
50 where
51 W: FnMut(&str, &str) -> Result<(), io::Error>,
52 {
53 self.reader2txts2match2writer(io::stdin().lock(), wtr)
54 }
55}
56
57pub fn kv2writer_new<W>(mut wtr: W) -> impl FnMut(&str, &str) -> Result<(), io::Error>
58where
59 W: Write,
60{
61 move |key: &str, val: &str| writeln!(&mut wtr, "{key}: {val}")
62}
63
64#[derive(Default)]
65pub struct Builder {
66 pub bldr: Grok,
67}
68
69impl Builder {
70 pub fn add_pattern(&mut self, name: &str, pattern: &str) {
71 self.bldr.add_pattern(name, pattern)
72 }
73
74 pub fn build(&self, pattern: &str, with_alias_only: bool) -> Result<GrokPattern, io::Error> {
75 let pat: Pattern = self
76 .bldr
77 .compile(pattern, with_alias_only)
78 .map_err(io::Error::other)?;
79 Ok(GrokPattern { pattern: pat })
80 }
81
82 pub fn stdin2texts2match2stdout_default(
83 &self,
84 pattern: &str,
85 with_alias_only: bool,
86 ) -> Result<(), io::Error> {
87 let pat: GrokPattern = self.build(pattern, with_alias_only)?;
88
89 let o = io::stdout();
90 let mut ol = o.lock();
91 {
92 let mut bw = BufWriter::new(&mut ol);
93 let mut wtr = kv2writer_new(&mut bw);
94
95 pat.stdin2txts2match2writer(&mut wtr)?;
96
97 drop(wtr);
98 bw.flush()?;
99 }
100 ol.flush()
101 }
102}