• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use std::env;
2 use std::error::Error;
3 use std::io;
4 use std::process;
5 
run() -> Result<(), Box<dyn Error>>6 fn run() -> Result<(), Box<dyn Error>> {
7     // Get the query from the positional arguments.
8     // If one doesn't exist, return an error.
9     let query = match env::args().nth(1) {
10         None => return Err(From::from("expected 1 argument, but got none")),
11         Some(query) => query,
12     };
13 
14     // Build CSV readers and writers to stdin and stdout, respectively.
15     let mut rdr = csv::Reader::from_reader(io::stdin());
16     let mut wtr = csv::Writer::from_writer(io::stdout());
17 
18     // Before reading our data records, we should write the header record.
19     wtr.write_record(rdr.headers()?)?;
20 
21     // Iterate over all the records in `rdr`, and write only records containing
22     // `query` to `wtr`.
23     for result in rdr.records() {
24         let record = result?;
25         if record.iter().any(|field| field == &query) {
26             wtr.write_record(&record)?;
27         }
28     }
29 
30     // CSV writers use an internal buffer, so we should always flush when done.
31     wtr.flush()?;
32     Ok(())
33 }
34 
main()35 fn main() {
36     if let Err(err) = run() {
37         println!("{}", err);
38         process::exit(1);
39     }
40 }
41