From 895f5ffdf5b190d4538be4a2e1a8ae709b74387e Mon Sep 17 00:00:00 2001 From: Trask Stalnaker Date: Mon, 2 Dec 2024 18:45:56 -0800 Subject: [PATCH] extract method and unit tests --- lychee-lib/src/utils/request.rs | 52 ++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/lychee-lib/src/utils/request.rs b/lychee-lib/src/utils/request.rs index b7023b9bff..d5e002f162 100644 --- a/lychee-lib/src/utils/request.rs +++ b/lychee-lib/src/utils/request.rs @@ -55,14 +55,7 @@ fn try_parse_into_uri( root_path: &Option, base: &Option, ) -> Result { - let mut text = raw_uri.text.clone(); - if text.starts_with('/') { - if let Some(path) = root_path { - if let Some(path_str) = path.to_str() { - text = format!("{path_str}{text}"); - } - } - } + let text = prepend_root_path_if_absolute_local_link(&raw_uri.text, root_path); let uri = match Uri::try_from(raw_uri.clone()) { Ok(uri) => uri, Err(_) => match base { @@ -200,6 +193,17 @@ fn resolve_and_create_url( Ok(url) } +fn prepend_root_path_if_absolute_local_link(text: &str, root_path: &Option) -> String { + if text.starts_with('/') { + if let Some(path) = root_path { + if let Some(path_str) = path.to_str() { + return format!("{}{}", path_str, text); + } + } + } + text.to_string() +} + #[cfg(test)] mod tests { use super::*; @@ -524,4 +528,36 @@ mod tests { assert_eq!(uri.url.as_str(), "file:///tmp/lychee/absolute.html"); } + + #[test] + fn test_prepend_with_absolute_local_link_and_root_path() { + let text = "/absolute/path"; + let root_path = Some(PathBuf::from("/root")); + let result = prepend_root_path_if_absolute_local_link(text, &root_path); + assert_eq!(result, "/root/absolute/path"); + } + + #[test] + fn test_prepend_with_absolute_local_link_and_no_root_path() { + let text = "/absolute/path"; + let root_path: Option = None; + let result = prepend_root_path_if_absolute_local_link(text, &root_path); + assert_eq!(result, "/absolute/path"); + } + + #[test] + fn test_prepend_with_relative_link_and_root_path() { + let text = "relative/path"; + let root_path = Some(PathBuf::from("/root")); + let result = prepend_root_path_if_absolute_local_link(text, &root_path); + assert_eq!(result, "relative/path"); + } + + #[test] + fn test_prepend_with_relative_link_and_no_root_path() { + let text = "relative/path"; + let root_path = None; + let result = prepend_root_path_if_absolute_local_link(text, &root_path); + assert_eq!(result, "relative/path"); + } }