From 81affd4017870bd3f24a753bd4b937d86bd8da76 Mon Sep 17 00:00:00 2001 From: Qrius Date: Thu, 26 Sep 2024 00:11:06 +0200 Subject: Add macro that checks whether links are working or not --- src/macro_processor/deadlinks.rs | 45 ++++++++++++++++++++++++++++++++++ src/macro_processor/macro_processor.rs | 4 +++ src/macro_processor/mod.rs | 2 ++ 3 files changed, 51 insertions(+) create mode 100644 src/macro_processor/deadlinks.rs (limited to 'src/macro_processor') diff --git a/src/macro_processor/deadlinks.rs b/src/macro_processor/deadlinks.rs new file mode 100644 index 0000000..061f729 --- /dev/null +++ b/src/macro_processor/deadlinks.rs @@ -0,0 +1,45 @@ +use crate::macro_processor::error::SMPError; +use crate::macro_processor::macro_processor::MacroProcessorWarning; +use crate::macro_processor::MacroProcessor; + +/// Warn on dead link +pub fn smp_builtin_wodl( + smp: &mut MacroProcessor, + macro_name: &str, + args: &mut [String], +) -> Result { + if args.len() != 1 { + smp.warnings + .push(MacroProcessorWarning::from_macro_invocation( + macro_name, + args, + format!("Wrong number of arguments, expected 1"), + )); + return Ok(macro_name.to_string()); + } + + let response = match minreq::get(&args[0]).send() { + Ok(s) => s, + Err(e) => { + smp.warnings + .push(MacroProcessorWarning::from_macro_invocation( + macro_name, + args, + format!("Dead link {:#?} ({:#?})!", args[0], e), + )); + return Ok(args[0].to_string()); + } + }; + if response.status_code != 200 || response.reason_phrase != "OK" { + smp.warnings + .push(MacroProcessorWarning::from_macro_invocation( + macro_name, + args, + format!( + "Dead link {:#?} ({} {})!", + args[0], response.status_code, response.reason_phrase + ), + )); + } + Ok(args[0].to_string()) +} diff --git a/src/macro_processor/macro_processor.rs b/src/macro_processor/macro_processor.rs index 612d2c5..a9585bb 100644 --- a/src/macro_processor/macro_processor.rs +++ b/src/macro_processor/macro_processor.rs @@ -3,6 +3,8 @@ use std::collections::HashMap; use std::fs; use std::process::Command; +#[cfg(feature = "deadlinks")] +use crate::macro_processor::deadlinks::smp_builtin_wodl; // print only with debug_assertions macro_rules! dprint { ($($x:tt)*) => { @@ -672,6 +674,8 @@ impl MacroProcessor { String::from("html_from_markdown"), MacroType::Function(smp_builtin_html_from_markdown), ); + #[cfg(feature = "deadlinks")] + self.define_macro(String::from("wodl"), MacroType::Function(smp_builtin_wodl)); #[cfg(feature = "webring")] self.define_macro( String::from("webring_rss"), diff --git a/src/macro_processor/mod.rs b/src/macro_processor/mod.rs index ffc2144..f586e0c 100644 --- a/src/macro_processor/mod.rs +++ b/src/macro_processor/mod.rs @@ -1,3 +1,5 @@ pub mod error; pub mod macro_processor; pub use macro_processor::MacroProcessor; +#[cfg(feature = "deadlinks")] +pub mod deadlinks; -- cgit v1.2.3