Skip to content

Instantly share code, notes, and snippets.

@durka
Created October 27, 2017 04:25
Show Gist options
  • Save durka/0bb7cbe590d724f574e2a7b70551d65e to your computer and use it in GitHub Desktop.
Save durka/0bb7cbe590d724f574e2a7b70551d65e to your computer and use it in GitHub Desktop.
//! ```cargo
//! [dependencies]
//! clap = "2"
//! csv = "0.15"
//! error-chain = "0.11"
//! ```
#[macro_use] extern crate clap;
extern crate csv;
#[macro_use] extern crate error_chain;
use std::io;
error_chain! {
foreign_links {
Io(io::Error);
Csv(csv::Error);
}
}
quick_main!(|| -> Result<i32> {
let matches = clap_app! { ecpp17ccrs =>
(author: "Steve Klabnik, Alex Burka")
(about: "Expressive C++17 Coding Challenge -- in Rust!")
(@arg INPUT: +required "Input CSV file")
(@arg COL: +required "Column to replace")
(@arg REP: +required "Replacement value")
(@arg OUTPUT: +required "Output CSV file")
}.get_matches();
let filename = matches.value_of("INPUT").unwrap();
let column_name = matches.value_of("COL").unwrap();
let replacement = matches.value_of("REP").unwrap();
let output_filename = matches.value_of("OUTPUT").unwrap();
let mut input = csv::Reader::from_file(filename)?;
let mut output = csv::Writer::from_file(output_filename)?;
let headers = input.headers()?;
if headers.is_empty() {
bail!("input file missing");
}
let col_to_replace = headers.iter()
.position(|e| e == column_name)
.ok_or("column name doesn't exist in the input file")?;
output.encode(headers)?;
for row in input.records() {
let mut row = row?;
row[col_to_replace] = replacement.into();
output.encode(row)?;
}
Ok(0)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment