github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/testdata/wasm/csv/src/main.rs (about) 1 use std::fs::File; 2 use std::error::Error; 3 use std::process; 4 use std::env; 5 6 const HORSE_ID: usize = 0; 7 const HORSE_LABEL: usize = 1; 8 const MOTHER_ID: usize = 2; 9 const MOTHER_LABEL: usize = 3; 10 const FATHER_ID : usize = 4; 11 const FATHER_LABEL: usize = 5; 12 13 fn run(input_path: &String, output_path: &String) -> Result<(), Box<dyn Error>> { 14 // Build the CSV reader and iterate over each record. 15 let input = File::open(input_path)?; 16 let mut wtr = csv::Writer::from_path(output_path)?; 17 let mut rdr = csv::Reader::from_reader(input); 18 19 let headers = csv::ByteRecord::from(vec!["parent", "parentLabel", "child", "childLabel"]); 20 wtr.write_byte_record(&headers)?; 21 22 for result in rdr.records() { 23 let record = result?; 24 let horse_id = record.get(HORSE_ID).or(Some("")).unwrap(); 25 let horse_label = record.get(HORSE_LABEL).or(Some("")).unwrap(); 26 let mother_id = record.get(MOTHER_ID).or(Some("")).unwrap(); 27 let mother_label = record.get(MOTHER_LABEL).or(Some("")).unwrap(); 28 let father_id = record.get(FATHER_ID).or(Some("")).unwrap(); 29 let father_label = record.get(FATHER_LABEL).or(Some("")).unwrap(); 30 31 if mother_id != "" { 32 let mother_record = csv::StringRecord::from(vec![mother_id, mother_label, horse_id, horse_label]); 33 wtr.write_byte_record(&mother_record.into_byte_record())?; 34 } 35 36 if father_id != "" { 37 let father_record = csv::StringRecord::from(vec![father_id, father_label, horse_id, horse_label]); 38 wtr.write_byte_record(&father_record.into_byte_record())?; 39 } 40 } 41 42 Ok(()) 43 } 44 45 fn main() { 46 let args: Vec<String> = env::args().collect(); 47 if args.len() != 3 { 48 let default = String::from("csv"); 49 let program_name = args.first().unwrap_or(&default); 50 eprintln!("Usage: {} input-csv output-csv", program_name); 51 process::exit(1); 52 } 53 54 let input_path = &args[1]; 55 let output_path = &args[2]; 56 if let Err(err) = run(input_path, output_path) { 57 eprintln!("error: {}", err); 58 process::exit(1); 59 } 60 61 process::exit(0) 62 }