1use std::fs;
24use std::io::{Read, Write};
25use std::path::{Path, PathBuf};
26use std::time::Duration;
27
28use crate::error::ForgeError;
29use crate::writer::unique_suffix;
30
31pub fn fetch_bytes(url: &str, max_size: u64) -> Result<Vec<u8>, ForgeError> {
40 let client = reqwest::blocking::Client::builder()
41 .connect_timeout(Duration::from_secs(30))
42 .timeout(Duration::from_secs(120))
43 .redirect(reqwest::redirect::Policy::limited(5))
44 .build()
45 .map_err(|e| ForgeError::Fetch(format!("client build failed: {e}")))?;
46
47 let mut resp = client
48 .get(url)
49 .send()
50 .map_err(|e| ForgeError::Fetch(format!("request failed: {e}")))?
51 .error_for_status()
52 .map_err(|e| ForgeError::Fetch(format!("http status: {e}")))?;
53
54 if let Some(len) = resp.content_length()
55 && len > max_size
56 {
57 return Err(ForgeError::TooLarge {
58 size: len,
59 max: max_size,
60 });
61 }
62
63 let tmp: PathBuf = std::env::temp_dir().join(format!(".utf8-forge-fetch-{}", unique_suffix()));
66 let cleanup = |p: &Path| {
67 let _ = fs::remove_file(p);
68 };
69 let mut file = fs::File::create(&tmp)
70 .map_err(|e| ForgeError::Fetch(format!("create temp file failed: {e}")))?;
71 let mut total: u64 = 0;
72 let mut buf = [0u8; 8192];
73 loop {
74 match resp.read(&mut buf) {
75 Ok(0) => break,
76 Ok(n) => {
77 total += n as u64;
78 if total > max_size {
79 cleanup(&tmp);
80 return Err(ForgeError::TooLarge {
81 size: total,
82 max: max_size,
83 });
84 }
85 if let Err(e) = file.write_all(&buf[..n]) {
86 cleanup(&tmp);
87 return Err(ForgeError::Fetch(format!("write temp file failed: {e}")));
88 }
89 }
90 Err(e) => {
91 cleanup(&tmp);
92 return Err(ForgeError::Fetch(format!("read body failed: {e}")));
93 }
94 }
95 }
96 if total > max_size {
98 cleanup(&tmp);
99 return Err(ForgeError::TooLarge {
100 size: total,
101 max: max_size,
102 });
103 }
104 let body = match fs::read(&tmp) {
105 Ok(bytes) => bytes,
106 Err(e) => {
107 cleanup(&tmp);
108 return Err(ForgeError::Fetch(format!("read temp file failed: {e}")));
109 }
110 };
111 cleanup(&tmp);
112 Ok(body)
113}
114
115pub fn derive_output_path(url: &str) -> PathBuf {
122 let segment = reqwest::Url::parse(url).ok().and_then(|u| {
123 u.path_segments()?
124 .next_back()
125 .map(str::to_owned)
126 .filter(|s| !s.is_empty())
127 });
128
129 match segment {
130 Some(seg) if has_extension(&seg) => PathBuf::from(seg),
131 Some(seg) => PathBuf::from(format!("{seg}.utf8")),
132 None => PathBuf::from("download.utf8"),
133 }
134}
135
136fn has_extension(segment: &str) -> bool {
138 std::path::Path::new(segment)
139 .extension()
140 .map(|e| !e.is_empty())
141 .unwrap_or(false)
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 #[test]
149 fn derive_keeps_extensioned_segments() {
150 assert_eq!(
151 derive_output_path("https://example.com/data/legacy.cpp"),
152 PathBuf::from("legacy.cpp")
153 );
154 }
155
156 #[test]
157 fn derive_appends_utf8_without_extension() {
158 assert_eq!(
159 derive_output_path("https://example.com/foo"),
160 PathBuf::from("foo.utf8")
161 );
162 }
163
164 #[test]
165 fn derive_falls_back_when_no_segment() {
166 assert_eq!(
167 derive_output_path("https://example.com/"),
168 PathBuf::from("download.utf8")
169 );
170 assert_eq!(
171 derive_output_path("not a url"),
172 PathBuf::from("download.utf8")
173 );
174 }
175
176 #[test]
177 fn derive_ignores_query_string() {
178 assert_eq!(
179 derive_output_path("https://example.com/a.cpp?raw=1"),
180 PathBuf::from("a.cpp")
181 );
182 }
183
184 #[test]
185 fn derive_treats_trailing_dot_as_missing_extension() {
186 assert_eq!(
187 derive_output_path("https://example.com/foo."),
188 PathBuf::from("foo..utf8")
189 );
190 }
191}