1use anyhow::{Context, Result};
4use serde::{Deserialize, Serialize};
5use std::path::{Path, PathBuf};
6use tokio::fs;
7
8use crate::image::has_supported_image_extension;
9
10pub async fn ensure_dir_exists(path: &Path) -> Result<()> {
12 if !path.exists() {
13 fs::create_dir_all(path)
14 .await
15 .with_context(|| format!("Failed to create directory: {}", path.display()))?;
16 }
17 Ok(())
18}
19
20pub async fn read_file_with_context(path: &Path, context: &str) -> Result<String> {
22 fs::read_to_string(path)
23 .await
24 .with_context(|| format!("Failed to read {}: {}", context, path.display()))
25}
26
27pub async fn write_file_with_context(path: &Path, content: &str, context: &str) -> Result<()> {
29 if let Some(parent) = path.parent() {
30 ensure_dir_exists(parent).await?;
31 }
32 fs::write(path, content)
33 .await
34 .with_context(|| format!("Failed to write {}: {}", context, path.display()))
35}
36
37pub async fn write_file_atomic_with_context(
49 path: &Path,
50 content: &str,
51 context: &str,
52) -> Result<()> {
53 if let Some(parent) = path.parent() {
54 ensure_dir_exists(parent).await?;
55 }
56
57 let temp_path = atomic_temp_path(path);
58
59 fs::write(&temp_path, content)
60 .await
61 .with_context(|| format!("Failed to write {}: {}", context, temp_path.display()))?;
62
63 if let Err(err) = fs::rename(&temp_path, path).await {
64 let _ = fs::remove_file(&temp_path).await;
65 return Err(err)
66 .with_context(|| format!("Failed to write {}: {}", context, path.display()));
67 }
68
69 Ok(())
70}
71
72fn atomic_temp_path(path: &Path) -> PathBuf {
75 use std::sync::atomic::{AtomicU64, Ordering};
76
77 static ATOMIC_WRITE_COUNTER: AtomicU64 = AtomicU64::new(0);
78
79 let dir = path
80 .parent()
81 .filter(|parent| !parent.as_os_str().is_empty())
82 .unwrap_or_else(|| Path::new("."));
83 let file_name =
84 path.file_name().and_then(|name| name.to_str()).unwrap_or("vtcode-atomic-write");
85 let nanos = std::time::SystemTime::now()
86 .duration_since(std::time::UNIX_EPOCH)
87 .map(|duration| duration.as_nanos())
88 .unwrap_or(0);
89 let counter = ATOMIC_WRITE_COUNTER.fetch_add(1, Ordering::Relaxed);
90
91 dir.join(format!(".{file_name}.tmp-{}-{nanos:x}-{counter:x}", std::process::id()))
92}
93
94pub async fn write_json_file<T: Serialize>(path: &Path, data: &T) -> Result<()> {
96 let json = serde_json::to_string_pretty(data)
97 .with_context(|| format!("Failed to serialize data for {}", path.display()))?;
98
99 write_file_with_context(path, &json, "JSON data").await
100}
101
102pub async fn read_json_file<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {
104 let content = read_file_with_context(path, "JSON file").await?;
105
106 serde_json::from_str(&content)
107 .with_context(|| format!("Failed to parse JSON from {}", path.display()))
108}
109
110pub fn parse_json_with_context<T: for<'de> Deserialize<'de>>(
112 content: &str,
113 context: &str,
114) -> Result<T> {
115 serde_json::from_str(content).with_context(|| format!("Failed to parse JSON from {context}"))
116}
117
118pub fn serialize_json_with_context<T: Serialize>(data: &T, context: &str) -> Result<String> {
120 serde_json::to_string(data).with_context(|| format!("Failed to serialize JSON for {context}"))
121}
122
123pub fn serialize_json_pretty_with_context<T: Serialize>(data: &T, context: &str) -> Result<String> {
125 serde_json::to_string_pretty(data)
126 .with_context(|| format!("Failed to pretty-serialize JSON for {context}"))
127}
128
129#[must_use]
135#[inline]
136pub fn try_parse_json<T: for<'de> Deserialize<'de>>(input: &str) -> Option<T> {
137 serde_json::from_str(input).ok()
138}
139
140#[must_use]
145#[inline]
146pub fn try_parse_json_value(input: &str) -> Option<serde_json::Value> {
147 serde_json::from_str(input).ok()
148}
149
150#[inline]
155pub fn parse_json_or_default<T: for<'de> Deserialize<'de> + Default>(
156 input: &str,
157 label: &str,
158) -> T {
159 serde_json::from_str(input).unwrap_or_else(|err| {
160 tracing::debug!(label, %err, "JSON parse failed, using default");
161 T::default()
162 })
163}
164
165pub fn canonicalize_with_context(path: &Path, context: &str) -> Result<PathBuf> {
167 path.canonicalize()
168 .with_context(|| format!("Failed to canonicalize {} path: {}", context, path.display()))
169}
170
171pub async fn canonicalize_with_context_async(path: &Path, context: &str) -> Result<PathBuf> {
173 fs::canonicalize(path)
174 .await
175 .with_context(|| format!("Failed to canonicalize {} path: {}", context, path.display()))
176}
177
178pub async fn read_to_string_async(path: &Path) -> Result<String> {
180 fs::read_to_string(path)
181 .await
182 .with_context(|| format!("Failed to read {}", path.display()))
183}
184
185pub async fn write_async(path: &Path, contents: impl AsRef<[u8]>) -> Result<()> {
187 fs::write(path, contents)
188 .await
189 .with_context(|| format!("Failed to write {}", path.display()))
190}
191
192pub async fn create_dir_all_async(path: &Path) -> Result<()> {
194 fs::create_dir_all(path)
195 .await
196 .with_context(|| format!("Failed to create {}", path.display()))
197}
198
199pub async fn remove_file_async(path: &Path) -> Result<()> {
201 fs::remove_file(path)
202 .await
203 .with_context(|| format!("Failed to remove {}", path.display()))
204}
205
206pub async fn rename_async(from: &Path, to: &Path) -> Result<()> {
208 fs::rename(from, to)
209 .await
210 .with_context(|| format!("Failed to rename {} to {}", from.display(), to.display()))
211}
212
213pub fn ensure_dir_exists_sync(path: &Path) -> Result<()> {
217 if !path.exists() {
218 std::fs::create_dir_all(path)
219 .with_context(|| format!("Failed to create directory: {}", path.display()))?;
220 }
221 Ok(())
222}
223
224pub fn read_file_with_context_sync(path: &Path, context: &str) -> Result<String> {
226 std::fs::read_to_string(path)
227 .with_context(|| format!("Failed to read {}: {}", context, path.display()))
228}
229
230pub fn write_file_with_context_sync(path: &Path, content: &str, context: &str) -> Result<()> {
232 if let Some(parent) = path.parent() {
233 ensure_dir_exists_sync(parent)?;
234 }
235 std::fs::write(path, content)
236 .with_context(|| format!("Failed to write {}: {}", context, path.display()))
237}
238
239pub fn write_json_file_sync<T: Serialize>(path: &Path, data: &T) -> Result<()> {
241 let json = serde_json::to_string_pretty(data)
242 .with_context(|| format!("Failed to serialize data for {}", path.display()))?;
243
244 write_file_with_context_sync(path, &json, "JSON data")
245}
246
247pub fn read_json_file_sync<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {
249 let content = read_file_with_context_sync(path, "JSON file")?;
250
251 serde_json::from_str(&content)
252 .with_context(|| format!("Failed to parse JSON from {}", path.display()))
253}
254
255pub fn is_image_path(path: &Path) -> bool {
257 let Some(extension) = path.extension().and_then(|ext| ext.to_str()) else {
258 return false;
259 };
260
261 matches!(
262 extension,
263 _ if extension.eq_ignore_ascii_case("png")
264 || extension.eq_ignore_ascii_case("jpg")
265 || extension.eq_ignore_ascii_case("jpeg")
266 || extension.eq_ignore_ascii_case("gif")
267 || extension.eq_ignore_ascii_case("bmp")
268 || extension.eq_ignore_ascii_case("webp")
269 || extension.eq_ignore_ascii_case("tiff")
270 || extension.eq_ignore_ascii_case("tif")
271 || extension.eq_ignore_ascii_case("svg")
272 )
273}
274
275pub fn is_windows_absolute_path(path: &str) -> bool {
277 let bytes = path.as_bytes();
278 bytes.len() > 2
279 && bytes[0].is_ascii_alphabetic()
280 && bytes[1] == b':'
281 && (bytes[2] == b'\\' || bytes[2] == b'/')
282}
283
284pub fn unescape_whitespace(token: &str) -> String {
289 let mut result = String::with_capacity(token.len());
290 let mut chars = token.chars().peekable();
291 while let Some(ch) = chars.next() {
292 if ch == '\\'
293 && let Some(next) = chars.peek()
294 && next.is_ascii_whitespace()
295 {
296 result.push(*next);
297 chars.next();
298 continue;
299 }
300 result.push(ch);
301 }
302 result
303}
304
305pub fn trim_trailing_image_path<F>(raw: &str, candidate_check: F) -> &str
315where
316 F: Fn(&str) -> bool,
317{
318 if candidate_check(raw) {
319 return raw;
320 }
321 let mut candidate = raw.trim_end();
322 while let Some(last_space) = candidate.rfind(' ') {
323 candidate = &candidate[..last_space];
324 if candidate_check(candidate) {
325 return candidate;
326 }
327 }
328 raw
329}
330
331pub fn trim_trailing_image_path_str(raw: &str) -> &str {
336 trim_trailing_image_path(raw, |candidate| {
337 let unescaped = unescape_whitespace(candidate);
338 let mut path_str = unescaped.as_str();
339 if let Some(rest) = path_str.strip_prefix("file://") {
340 path_str = rest;
341 }
342 if let Some(rest) = path_str.strip_prefix("~/") {
343 if let Some(home) = dirs::home_dir() {
344 return has_supported_image_extension(&home.join(rest));
345 }
346 return false;
347 }
348 has_supported_image_extension(Path::new(path_str))
349 })
350}