use std::path::PathBuf;
use std::time::Duration;
use crate::error::ForgeError;
pub fn fetch_bytes(url: &str, max_size: u64) -> Result<Vec<u8>, ForgeError> {
let client = reqwest::blocking::Client::builder()
.connect_timeout(Duration::from_secs(30))
.timeout(Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::limited(5))
.build()
.map_err(|e| ForgeError::Fetch(format!("client build failed: {e}")))?;
let resp = client
.get(url)
.send()
.map_err(|e| ForgeError::Fetch(format!("request failed: {e}")))?
.error_for_status()
.map_err(|e| ForgeError::Fetch(format!("http status: {e}")))?;
if let Some(len) = resp.content_length() {
if len > max_size {
return Err(ForgeError::TooLarge {
size: len,
max: max_size,
});
}
}
let body = resp
.bytes()
.map_err(|e| ForgeError::Fetch(format!("read body failed: {e}")))?;
let len = body.len() as u64;
if len > max_size {
return Err(ForgeError::TooLarge {
size: len,
max: max_size,
});
}
Ok(body.to_vec())
}
pub fn derive_output_path(url: &str) -> PathBuf {
let segment = url::Url::parse(url)
.ok()
.and_then(|u| {
u.path_segments()?
.next_back()
.map(str::to_owned)
.filter(|s| !s.is_empty())
});
match segment {
Some(seg) if has_extension(&seg) => PathBuf::from(seg),
Some(seg) => PathBuf::from(format!("{seg}.utf8")),
None => PathBuf::from("download.utf8"),
}
}
fn has_extension(segment: &str) -> bool {
std::path::Path::new(segment)
.extension()
.map(|e| !e.is_empty())
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn derive_keeps_extensioned_segments() {
assert_eq!(
derive_output_path("https://example.com/data/legacy.cpp"),
PathBuf::from("legacy.cpp")
);
}
#[test]
fn derive_appends_utf8_without_extension() {
assert_eq!(
derive_output_path("https://example.com/foo"),
PathBuf::from("foo.utf8")
);
}
#[test]
fn derive_falls_back_when_no_segment() {
assert_eq!(
derive_output_path("https://example.com/"),
PathBuf::from("download.utf8")
);
assert_eq!(
derive_output_path("not a url"),
PathBuf::from("download.utf8")
);
}
#[test]
fn derive_ignores_query_string() {
assert_eq!(
derive_output_path("https://example.com/a.cpp?raw=1"),
PathBuf::from("a.cpp")
);
}
#[test]
fn derive_treats_trailing_dot_as_missing_extension() {
assert_eq!(
derive_output_path("https://example.com/foo."),
PathBuf::from("foo..utf8")
);
}
}