Created
February 14, 2018 19:17
-
-
Save killercup/049d759118e3b5029737eb77e157ea42 to your computer and use it in GitHub Desktop.
CSV thingy from http://words.steveklabnik.com/the-expressive-c-17-coding-challenge-in-rust-revisited with quicli
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "steves-csv-thingy" | |
version = "0.1.0" | |
authors = ["Pascal Hertleif <[email protected]>"] | |
[[bin]] | |
name = "quicsv" | |
path = "main.rs" | |
[dependencies] | |
quicli = "0.2.0" | |
csv = "1.0.0-beta.5" | |
serde = "1.0.27" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] extern crate quicli; | |
extern crate csv; | |
use quicli::prelude::*; | |
#[derive(Debug, Serialize, Deserialize)] | |
struct Record<'a> { | |
name: &'a str, | |
surname: &'a str, | |
city: &'a str, | |
country: &'a str, | |
} | |
#[derive(StructOpt, Debug)] | |
struct Opt { | |
filename: String, | |
column_name: String, | |
replacement: String, | |
output_filename: String, | |
} | |
main!(|args: Opt| { | |
use std::fs::File; | |
let input = File::open(&args.filename)?; | |
let output = File::create(&args.output_filename)?; | |
let mut rdr = csv::Reader::from_reader(input); | |
let mut wtr = csv::Writer::from_writer(output); | |
let mut raw_record = csv::StringRecord::new(); | |
let headers = rdr.headers()?.clone(); | |
while rdr.read_record(&mut raw_record)? { | |
let mut record: Record = raw_record.deserialize(Some(&headers))?; | |
match &*args.column_name { | |
"name" => record.name = &args.replacement, | |
"surname" => record.surname = &args.replacement, | |
"city" => record.city = &args.replacement, | |
"country" => record.country = &args.replacement, | |
_ => panic!("incorrect column name"), | |
} | |
wtr.serialize(record)?; | |
} | |
wtr.flush()?; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment