64 lines
1.7 KiB
Rust
64 lines
1.7 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;
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum Formatter {
|
|
Text,
|
|
Csv,
|
|
Json,
|
|
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::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> {
|
|
let lower = s.to_lowercase();
|
|
|
|
Ok(match &*lower {
|
|
"text" => Formatter::Text,
|
|
"csv" => Formatter::Csv,
|
|
"json" => Formatter::Json,
|
|
custom_format => Formatter::Custom(custom_format.into()),
|
|
})
|
|
}
|
|
}
|