tiempo-rs/src/formatters/csv.rs

80 lines
2.5 KiB
Rust

use std::io::Write;
use csv::Writer;
use chrono::SecondsFormat;
use crate::error::{Result, Error::*};
use crate::models::Entry;
pub fn print_formatted<W: Write>(entries: Vec<Entry>, out: &mut W, ids: bool) -> Result<()> {
let mut wtr = Writer::from_writer(out);
if ids {
wtr.write_record(&["id", "start", "end", "note", "sheet"])?;
} else {
wtr.write_record(&["start", "end", "note", "sheet"])?;
}
for entry in entries {
if ids {
wtr.write_record(&[
entry.id.to_string(),
entry.start.to_rfc3339_opts(SecondsFormat::Secs, true),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Secs, true)).unwrap_or("".into()),
entry.note.unwrap_or("".into()),
entry.sheet,
])?;
} else {
wtr.write_record(&[
entry.start.to_rfc3339_opts(SecondsFormat::Secs, true),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Secs, true)).unwrap_or("".into()),
entry.note.unwrap_or("".into()),
entry.sheet,
])?;
}
}
wtr.flush().map_err(|e| IOError(e))
}
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
use crate::test_utils::PrettyString;
use super::*;
#[test]
fn test_print_formatted() {
let entries = vec![
Entry::new_sample(1, Utc.ymd(2021, 6, 30).and_hms(18, 12, 34), Some(Utc.ymd(2021, 6, 30).and_hms(19, 0, 0))),
Entry::new_sample(2, Utc.ymd(2021, 6, 30).and_hms(18, 12, 34), None),
];
let mut out = Vec::new();
print_formatted(entries, &mut out, false).unwrap();
assert_eq!(PrettyString(&String::from_utf8_lossy(&out)), PrettyString("start,end,note,sheet
2021-06-30T18:12:34Z,2021-06-30T19:00:00Z,entry 1,default
2021-06-30T18:12:34Z,,entry 2,default
"));
}
#[test]
fn test_print_formatted_ids() {
let entries = vec![
Entry::new_sample(1, Utc.ymd(2021, 6, 30).and_hms(18, 12, 34), Some(Utc.ymd(2021, 6, 30).and_hms(19, 0, 0))),
Entry::new_sample(2, Utc.ymd(2021, 6, 30).and_hms(18, 12, 34), None),
];
let mut out = Vec::new();
print_formatted(entries, &mut out, true).unwrap();
assert_eq!(PrettyString(&String::from_utf8_lossy(&out)), PrettyString("id,start,end,note,sheet
1,2021-06-30T18:12:34Z,2021-06-30T19:00:00Z,entry 1,default
2,2021-06-30T18:12:34Z,,entry 2,default
"));
}
}