78 lines
2.5 KiB
Rust
78 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::Micros, true),
|
|
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Micros, true)).unwrap_or_else(|| "".into()),
|
|
entry.note.unwrap_or_else(|| "".into()),
|
|
entry.sheet,
|
|
])?;
|
|
} else {
|
|
wtr.write_record(&[
|
|
entry.start.to_rfc3339_opts(SecondsFormat::Micros, true),
|
|
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Micros, true)).unwrap_or_else(|| "".into()),
|
|
entry.note.unwrap_or_else(|| "".into()),
|
|
entry.sheet,
|
|
])?;
|
|
}
|
|
}
|
|
|
|
wtr.flush().map_err(IOError)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use chrono::{TimeZone, Utc};
|
|
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_print_formatted() {
|
|
let entries = vec![
|
|
Entry::new_sample(1, Utc.with_ymd_and_hms(2021, 6, 30, 18, 12, 34).unwrap(), Some(Utc.with_ymd_and_hms(2021, 6, 30, 19, 0, 0).unwrap())),
|
|
Entry::new_sample(2, Utc.with_ymd_and_hms(2021, 6, 30, 18, 12, 34).unwrap(), None),
|
|
];
|
|
let mut out = Vec::new();
|
|
|
|
print_formatted(entries, &mut out, false).unwrap();
|
|
|
|
assert_eq!(&String::from_utf8_lossy(&out), "start,end,note,sheet
|
|
2021-06-30T18:12:34.000000Z,2021-06-30T19:00:00.000000Z,entry 1,default
|
|
2021-06-30T18:12:34.000000Z,,entry 2,default
|
|
");
|
|
}
|
|
|
|
#[test]
|
|
fn test_print_formatted_ids() {
|
|
let entries = vec![
|
|
Entry::new_sample(1, Utc.with_ymd_and_hms(2021, 6, 30, 18, 12, 34).unwrap(), Some(Utc.with_ymd_and_hms(2021, 6, 30, 19, 0, 0).unwrap())),
|
|
Entry::new_sample(2, Utc.with_ymd_and_hms(2021, 6, 30, 18, 12, 34).unwrap(), None),
|
|
];
|
|
let mut out = Vec::new();
|
|
|
|
print_formatted(entries, &mut out, true).unwrap();
|
|
|
|
assert_eq!(&String::from_utf8_lossy(&out), "id,start,end,note,sheet
|
|
1,2021-06-30T18:12:34.000000Z,2021-06-30T19:00:00.000000Z,entry 1,default
|
|
2,2021-06-30T18:12:34.000000Z,,entry 2,default
|
|
");
|
|
}
|
|
}
|