rnotifylib/destination/kinds/
file.rs

1use std::error::Error;
2use std::fs::File;
3use std::path::PathBuf;
4use serde::{Serialize, Deserialize};
5use std::fmt::{Debug, Write};
6use std::fs;
7use std::io::Write as IoWrite;
8use chrono::{Local, SecondsFormat, TimeZone};
9use crate::destination::{MessageDestination, SerializableDestination};
10use crate::message::Message;
11
12#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
13pub struct FileDestination {
14    path: PathBuf,
15}
16
17impl MessageDestination for FileDestination {
18    fn send(&self, message: &Message) -> Result<(), Box<dyn Error>> {
19        if let Some(parent) = self.path.parent() {
20            if !parent.exists() {
21                fs::create_dir_all(parent)?;
22            }
23        }
24        let s = self.format_message(message);
25        let mut file = File::options()
26            .create(true)
27            .append(true)
28            .open(&self.path)?;
29
30        writeln!(&mut file, "{}", s)?;
31        Ok(())
32    }
33}
34
35#[typetag::serde(name = "File")]
36impl SerializableDestination for FileDestination {
37    fn as_message_destination(&self) -> &dyn MessageDestination {
38        self
39    }
40}
41
42impl FileDestination {
43    pub fn new(path: PathBuf) -> Self {
44        Self {
45            path
46        }
47    }
48
49    // TODO: Allow custom format.
50    fn format_message(&self, message: &Message) -> String {
51        let mut s = String::new();
52        let timestamp = Local::timestamp_millis(&Local, message.get_unix_timestamp_millis());
53        write!(s, "{} - {:?}: ", timestamp.to_rfc3339_opts(SecondsFormat::Millis, true), message.get_level()).unwrap();
54        if message.get_component().is_some() {
55            write!(s, "[{}] ", message.get_component().as_ref().unwrap()).unwrap();
56        }
57        if message.get_title().is_some() {
58            write!(s, "{} - ", message.get_title().as_ref().unwrap()).unwrap();
59        }
60        write!(s, "'{}'", inline(message.get_message_detail().raw())).unwrap();
61        write!(s, " @ {}", message.get_author()).unwrap();
62        s
63    }
64}
65
66fn inline(s: &str) -> String {
67    let vec: Vec<_> = s.lines().collect();
68    vec.join("\\n")
69}