tiempo-rs/src/formatters.rs

70 lines
2.0 KiB
Rust

use std::str::FromStr;
use std::io::Write;
use serde::{Serialize, Deserialize};
use chrono::{DateTime, Utc};
use crate::error;
use crate::models::Entry;
pub mod text;
pub mod csv;
pub mod json;
pub mod ids;
pub mod ical;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Formatter {
Text,
Csv,
Json,
Ids,
Ical,
Custom(String),
}
impl Default for Formatter {
fn default() -> Formatter {
Formatter::Text
}
}
impl Formatter {
/// Prints the given entries to the specified output device.
///
/// the current time is given as the `now` argument and the offset from UTC
/// to the local timezone is given in `offset` to prevent this function from
/// using a secondary effect to retrieve the time and conver dates. This
/// also makes it easier to test.
pub fn print_formatted<W: Write>(&self, entries: Vec<Entry>, out: &mut W, now: DateTime<Utc>, ids: bool) -> error::Result<()> {
match &self {
Formatter::Text => text::print_formatted(entries, out, now, ids)?,
Formatter::Csv => csv::print_formatted(entries, out, ids)?,
Formatter::Json => json::print_formatted(entries, out)?,
Formatter::Ids => ids::print_formatted(entries, out)?,
Formatter::Ical => ical::print_formatted(entries, out, now)?,
Formatter::Custom(name) => {
panic!("attempted custom formatter with name {} which is not implemented", name);
}
}
Ok(())
}
}
impl FromStr for Formatter {
type Err = error::Error;
fn from_str(s: &str) -> error::Result<Formatter> {
Ok(match s.to_lowercase().as_str() {
"text" => Formatter::Text,
"csv" => Formatter::Csv,
"json" => Formatter::Json,
"ids" => Formatter::Ids,
"ical" => Formatter::Ical,
custom_format => Formatter::Custom(custom_format.into()),
})
}
}