Fix CS and some other small things

Useful tool, that clippy...

Signed-off-by: Jacob Kiers <jacob@jacobkiers.net>
This commit is contained in:
Jacob Kiers 2022-12-14 15:34:29 +01:00
parent e7fd41ff95
commit 7407654e60
4 changed files with 42 additions and 49 deletions

View File

@ -35,19 +35,13 @@ pub(crate) fn add_entry_to_feed(
_ => "".to_string(), _ => "".to_string(),
}, },
}, },
email: match &from.address { email: from.address.as_ref().map(|e| e.to_string()),
Some(e) => Some(e.to_string()),
_ => None,
},
uri: None, uri: None,
}, },
title: parsed title: parsed.subject().expect("Expected a subject").to_string(),
.subject()
.expect("Expected a subject")
.to_string(),
content: Some(processed_html.clone()), content: Some(processed_html.clone()),
id: url.clone(), id: url.clone(),
published: Utc.timestamp_opt(date.to_timestamp(), 0).unwrap(), //(format!("{}{}", &date.to_iso8601(), "+00:00").as_str()).`unwrap(), published: Utc.timestamp_opt(date.to_timestamp(), 0).unwrap(),
url: match include_html { url: match include_html {
true => url, true => url,
false => "".to_string(), false => "".to_string(),
@ -119,8 +113,8 @@ impl From<Newsletter> for Entry {
eb.title(post.title) eb.title(post.title)
.id(post.id) .id(post.id)
.published(Some(post.published.clone().into())) .published(Some(post.published.into()))
.author(post.author.into()) .author(post.author)
.content(content); .content(content);
if post.url.len() > 1 { if post.url.len() > 1 {

View File

@ -20,8 +20,8 @@ use std::{
pub(crate) use message::Message; pub(crate) use message::Message;
const INDEX_HTML: & 'static str = include_str!("../resources/index.html"); const INDEX_HTML: &str = include_str!("../resources/index.html");
const FEED_STYLESHEET: & 'static str = include_str!("../resources/feed.xsl"); const FEED_STYLESHEET: &str = include_str!("../resources/feed.xsl");
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
let cli = cli::Cli::parse(); let cli = cli::Cli::parse();
@ -41,7 +41,11 @@ fn main() -> Result<(), Box<dyn Error>> {
username.to_owned(), username.to_owned(),
password.to_owned(), password.to_owned(),
), ),
cli::Command::BuildFeed { filename , hostname, include_html } => build_feed(&filename, hostname.to_owned(), *include_html), cli::Command::BuildFeed {
filename,
hostname,
include_html,
} => build_feed(filename, hostname, *include_html),
_ => unimplemented!("This method is not yet implemented."), _ => unimplemented!("This method is not yet implemented."),
}; };
@ -56,7 +60,11 @@ fn create_directory<P: AsRef<Path>>(dir: P) -> Result<(), std::io::Error> {
Ok(()) Ok(())
} }
fn build_feed(filename: &PathBuf, hostname: String, include_html: bool) -> Result<(), Box<dyn Error>> { fn build_feed(
filename: &PathBuf,
hostname: &String,
include_html: bool,
) -> Result<(), Box<dyn Error>> {
let dir = filename.parent().ok_or(format!( let dir = filename.parent().ok_or(format!(
"Could not get parent directory of {}", "Could not get parent directory of {}",
filename.display() filename.display()
@ -71,12 +79,14 @@ fn build_feed(filename: &PathBuf, hostname: String, include_html: bool) -> Resul
create_directory(dir)?; create_directory(dir)?;
let feed_file = filename let feed_file = filename
.file_name().expect("Feed path should have a file name") .file_name()
.to_str().expect("Feed path should be printable."); .expect("Feed path should have a file name")
.to_str()
.expect("Feed path should be printable.");
let mut feed = feed::build_atom_feed(&hostname, feed_file); let mut feed = feed::build_atom_feed(&hostname, feed_file);
let mut reader = DataDirectoryMessageReader::new((&Path::new("data")).to_path_buf()); let mut reader = DataDirectoryMessageReader::new(Path::new("data").to_path_buf());
for msg in reader.read_rfc822_messages() { for msg in reader.read_rfc822_messages() {
let parsed = msg.get_parsed().expect("A parsed messsage."); let parsed = msg.get_parsed().expect("A parsed messsage.");
@ -86,15 +96,12 @@ fn build_feed(filename: &PathBuf, hostname: String, include_html: bool) -> Resul
msg.get_uid() msg.get_uid()
))?; ))?;
let subject = match parsed.subject() { let subject = parsed.subject().unwrap_or("No subject");
Some(subject) => subject,
None => "No subject",
};
println!( println!(
"Processing message {} from {} with subject {}", "Processing message {} from {} with subject {}",
msg.get_uid(), msg.get_uid(),
date.to_string(), date,
subject subject
); );
@ -102,20 +109,23 @@ fn build_feed(filename: &PathBuf, hostname: String, include_html: bool) -> Resul
let processed_html = process_html(&html_body).expect("Could not process the HTML"); let processed_html = process_html(&html_body).expect("Could not process the HTML");
if include_html { if include_html {
let path : PathBuf = [dir, Path::new(&get_path(&parsed, &msg))].iter().collect(); let path: PathBuf = [dir, Path::new(&get_path(&parsed, &msg))].iter().collect();
write_file(&path, processed_html.as_bytes())?; write_file(&path, processed_html.as_bytes())?;
} }
feed::add_entry_to_feed(&mut feed, &msg, &processed_html, &hostname, include_html); feed::add_entry_to_feed(&mut feed, &msg, &processed_html, &hostname, include_html);
} }
if feed.entries.len() > 0 { if !feed.entries.is_empty() {
feed.set_updated(Utc::now()); feed.set_updated(Utc::now());
println!("Writing feed to {}", filename.display()); println!("Writing feed to {}", filename.display());
feed::write_feed(feed, open_file(filename).unwrap())?; feed::write_feed(feed, open_file(filename).unwrap())?;
write_file(dir.join("feed.xsl"), FEED_STYLESHEET)?; write_file(dir.join("feed.xsl"), FEED_STYLESHEET)?;
write_file(dir.join("index.html"), INDEX_HTML.replace("{FEED}", feed_file))?; write_file(
dir.join("index.html"),
INDEX_HTML.replace("{FEED}", feed_file),
)?;
} }
println!("Finished building the feed."); println!("Finished building the feed.");
@ -134,12 +144,7 @@ fn fetch_from_imap(
print!("Getting mail from {} for mailbox {}", server, username); print!("Getting mail from {} for mailbox {}", server, username);
let mut reader = ImapReader::new( let mut reader = ImapReader::new(server, port, username, password);
String::from(server),
port,
String::from(username),
String::from(password),
);
for msg in reader.read_rfc822_messages() { for msg in reader.read_rfc822_messages() {
let parsed = msg.get_parsed().ok_or(format!( let parsed = msg.get_parsed().ok_or(format!(
@ -152,15 +157,12 @@ fn fetch_from_imap(
msg.get_uid() msg.get_uid()
))?; ))?;
let subject = match parsed.subject() { let subject = parsed.subject().unwrap_or("No subject");
Some(subject) => subject,
None => "No subject",
};
println!( println!(
"Processing message {} from {} with subject {}", "Processing message {} from {} with subject {}",
msg.get_uid(), msg.get_uid(),
date.to_string(), date,
subject subject
); );
@ -180,8 +182,6 @@ fn fetch_from_imap(
Ok(()) Ok(())
} }
fn get_path(parsed: &ParsedMessage, msg: &Message) -> String { fn get_path(parsed: &ParsedMessage, msg: &Message) -> String {
let date = parsed.date().expect("Could not extract date"); let date = parsed.date().expect("Could not extract date");
let date_str = format!( let date_str = format!(
@ -190,14 +190,15 @@ fn get_path(parsed: &ParsedMessage, msg: &Message) -> String {
); );
let hash = base16ct::lower::encode_string(&Sha256::digest( let hash = base16ct::lower::encode_string(&Sha256::digest(
&parsed.body_html(0).expect("Expected a body").as_bytes(), parsed.body_html(0).expect("Expected a body").as_bytes(),
)); ));
let uid: i32 = msg.get_uid() let uid: i32 = msg
.get_uid()
.parse() .parse()
.expect(&format!("Could not convert message id {} to an i32.", msg.get_uid())); .unwrap_or_else(|_| panic!("Could not convert message id {} to an i32.", msg.get_uid()));
format!("{:05}_{}_{}.html", uid, date_str, &hash).to_owned() format!("{:05}_{}_{}.html", uid, date_str, &hash)
} }
fn process_html(input: &str) -> Result<String, ()> { fn process_html(input: &str) -> Result<String, ()> {

View File

@ -21,4 +21,4 @@ impl Message {
pub fn get_data(&self) -> &Vec<u8> { pub fn get_data(&self) -> &Vec<u8> {
&self.data &self.data
} }
} }

View File

@ -44,7 +44,7 @@ impl EmailReader for DataDirectoryMessageReader {
Some(ext) => ext == "eml", Some(ext) => ext == "eml",
None => false, None => false,
}) })
.map(|i| { .filter_map(|i| {
let uid = i let uid = i
.path() .path()
.file_stem() .file_stem()
@ -52,9 +52,9 @@ impl EmailReader for DataDirectoryMessageReader {
.to_owned() .to_owned()
.into_string() .into_string()
.expect("Could not convert filename to string.") .expect("Could not convert filename to string.")
.split("_") .split('_')
.collect::<Vec<&str>>()[0] .collect::<Vec<&str>>()[0]
.trim_start_matches("0") .trim_start_matches('0')
.to_string(); .to_string();
if let Ok(data) = std::fs::read(i.path()) { if let Ok(data) = std::fs::read(i.path()) {
@ -63,8 +63,6 @@ impl EmailReader for DataDirectoryMessageReader {
None None
} }
}) })
.filter(|i| i.is_some())
.map(|i| i.unwrap())
.map(|i| Message::new(i.0, i.1)); .map(|i| Message::new(i.0, i.1));
let iter = items.collect::<Vec<Message>>().into_iter(); let iter = items.collect::<Vec<Message>>().into_iter();