aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: ca624161fda3c5b181d93a285ee34be5f9dbb897 (plain) (blame)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use aip_filter::{parse, CompiledFilter};
use serde_json::Value as Json;
use std::{
    fs::File,
    io::{self, BufRead, BufReader, BufWriter, Read, Write},
    path::Path,
    process,
};

const DEFAULT_MAX_RECORD_BYTES: usize = 8 * 1024 * 1024;

struct RecordOutput<W> {
    writer: W,
    needs_separator: bool,
}

impl<W: Write> RecordOutput<W> {
    fn write_record(&mut self, record: &[u8]) -> io::Result<()> {
        if self.needs_separator {
            self.writer.write_all(b"\n")?;
        }
        self.writer.write_all(record)?;
        self.needs_separator = !record.ends_with(b"\n");
        Ok(())
    }
}

fn filter_lines(
    expr: Option<&CompiledFilter<'_>>,
    mut reader: impl BufRead,
    out: &mut RecordOutput<impl Write>,
    source: &str,
    max_record_bytes: usize,
) -> io::Result<bool> {
    let Some(expr) = expr else {
        io::copy(&mut reader, &mut out.writer)?;
        return Ok(true);
    };
    let mut line_buffer = Vec::with_capacity(128);
    let mut lineno = 0;
    let mut valid = true;

    while (&mut reader).take(max_record_bytes as u64 + 1)
        .read_until(b'\n', &mut line_buffer)? > 0
    {
        lineno += 1;
        if line_buffer.len() > max_record_bytes {
            eprintln!("{source}:{lineno}: record exceeds {max_record_bytes} bytes");
            valid = false;
            if line_buffer.last() != Some(&b'\n') {
                reader.skip_until(b'\n')?;
            }
        } else if !line_buffer.iter().all(u8::is_ascii_whitespace) {
            match serde_json::from_slice::<Json>(&line_buffer) {
                Ok(json) => {
                    if expr.evaluate(&json) {
                        out.write_record(&line_buffer)?;
                    }
                }
                Err(e) => {
                    eprintln!("{source}:{lineno}: invalid JSON: {e}");
                    valid = false;
                }
            }
        }
        line_buffer.clear();
    }

    Ok(valid)
}

fn usage(program: &str) -> ! {
    eprintln!("usage: {program} [-p|--print] [--max-record-bytes N] [--] <expr> [file...]");
    process::exit(2);
}

fn main() {
    let mut args = std::env::args();
    let program = args.next().unwrap();
    let mut print_only = false;
    let mut max_record_bytes = DEFAULT_MAX_RECORD_BYTES;
    let raw_expr = loop {
        let arg = args.next().unwrap_or_else(|| usage(&program));
        match arg.as_str() {
            "-p" | "--print" => print_only = true,
            "--max-record-bytes" => {
                max_record_bytes = args.next()
                    .and_then(|value| value.parse::<usize>().ok())
                    .filter(|value| *value > 0 && value.checked_add(1).is_some())
                    .unwrap_or_else(|| usage(&program));
            }
            "--" => break args.next().unwrap_or_else(|| usage(&program)),
            "-h" | "--help" => usage(&program),
            _ => break arg,
        }
    };
    let mut paths = args.peekable();
    let expr = match parse(&raw_expr) {
        Ok(expr) => expr,
        Err(e) => {
            eprintln!("{program}: {e}");
            process::exit(1);
        }
    };

    let mut out = BufWriter::new(io::stdout().lock());
    let result = (|| -> io::Result<bool> {
        if print_only {
            if let Some(expr) = &expr {
                writeln!(out, "{expr}")?;
            }
            return Ok(true);
        }
        let filter = expr.as_ref().map(|expr| expr.compile()).transpose()
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
        let mut records = RecordOutput { writer: &mut out, needs_separator: false };
        if paths.peek().is_none() {
            return filter_lines(filter.as_ref(), io::stdin().lock(), &mut records, "<stdin>", max_record_bytes);
        }
        let mut valid = true;
        for path in paths {
            let file = File::open(Path::new(&path))
                .map_err(|e| io::Error::new(e.kind(), format!("{path}: {e}")))?;
            valid &= filter_lines(filter.as_ref(), BufReader::new(file), &mut records, &path, max_record_bytes)
                .map_err(|e| io::Error::new(e.kind(), format!("{path}: {e}")))?;
        }
        Ok(valid)
    })();
    let flushed = out.flush();
    match result.and_then(|valid| flushed.map(|()| valid)) {
        Ok(true) => {}
        Ok(false) => process::exit(1),
        Err(e) => {
            eprintln!("{program}: {e}");
            process::exit(1);
        }
    }
}