summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: f94107b271f87a89fbd2f179693c6cea2cb3a341 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#![feature(test)]
#![feature(plugin,collections,str_char)] // For peg
#![plugin(peg_syntax_ext)]

extern crate test;
extern crate time;
extern crate getopts;
extern crate regex;

mod line;
mod filter;

pub use line::Line;

use std::io::{stdin,stdout,stderr,Write,BufRead};


fn print_usage(prog: &str, opts: getopts::Options) {
    print!("{}", opts.usage(format!("Usage: {} [options] <filter>", prog).as_ref()));
    std::process::exit(1);
}


fn main() {
    let mut opts = getopts::Options::new();
    opts.optflag("", "vhost2ident", "normalize hostname into ident field");
    opts.optflag("h", "help", "print this help");
    opts.optflag("q", "quiet", "suppress warnings about unrecognized lines");
    let mut args = std::env::args();
    let prog = args.next().unwrap();
    let m = opts.parse(args).unwrap();

    if m.opt_present("h") {
        return print_usage(prog.as_ref(), opts);
    }

    let vhost2ident = m.opt_present("vhost2ident");
    let quiet = m.opt_present("q");
    let filter = if m.free.is_empty() {
        return print_usage(prog.as_ref(), opts);
    } else {
        m.free[0].clone()
    };

    let filter = match filter::Filter::new(filter.as_ref()) {
        Ok(x) => x,
        Err(_) => {
            println!("Invalid filter '{}'", filter);
            return;
        }
    };

    let s = stdin();
    let o = stdout();
    let mut o = o.lock();
    for l in s.lock().lines().map(|x| x.unwrap()) {

        let mut line = match Line::new(l.as_ref()) {
            Ok(x) => x,
            Err(_) => {
                if !quiet {
                    writeln!(&mut stderr(), "Unrecognized line: {}", l).unwrap();
                }
                continue;
            }
        };

        if vhost2ident {
            line.vhost2ident();
        }

        if filter.apply(&line) {
            line.write(&mut o).unwrap();
            o.write_all("\n".as_bytes()).unwrap();
        }
    }
}