use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::error::ForgeError;
use crate::writer::unique_suffix;
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 mut 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()
&& len > max_size
{
return Err(ForgeError::TooLarge {
size: len,
max: max_size,
});
}
let tmp: PathBuf = std::env::temp_dir().join(format!(".utf8-forge-fetch-{}", unique_suffix()));
let cleanup = |p: &Path| {
let _ = fs::remove_file(p);
};
let mut file = fs::File::create(&tmp)
.map_err(|e| ForgeError::Fetch(format!("create temp file failed: {e}")))?;
let mut total: u64 = 0;
let mut buf = [0u8; 8192];
loop {
match resp.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
total += n as u64;
if total > max_size {
cleanup(&tmp);
return Err(ForgeError::TooLarge {
size: total,
max: max_size,
});
}
if let Err(e) = file.write_all(&buf[..n]) {
cleanup(&tmp);
return Err(ForgeError::Fetch(format!("write temp file failed: {e}")));
}
}
Err(e) => {
cleanup(&tmp);
return Err(ForgeError::Fetch(format!("read body failed: {e}")));
}
}
}
if total > max_size {
cleanup(&tmp);
return Err(ForgeError::TooLarge {
size: total,
max: max_size,
});
}
let body = match fs::read(&tmp) {
Ok(bytes) => bytes,
Err(e) => {
cleanup(&tmp);
return Err(ForgeError::Fetch(format!("read temp file failed: {e}")));
}
};
cleanup(&tmp);
Ok(body)
}
pub fn derive_output_path(url: &str) -> PathBuf {
let segment = reqwest::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")
);
}
}