Skip to main content

vtcode_commons/
fs.rs

1//! File utility functions for common operations
2
3use anyhow::{Context, Result};
4use serde::{Deserialize, Serialize};
5use std::path::{Path, PathBuf};
6use tokio::fs;
7
8use crate::image::has_supported_image_extension;
9
10/// Ensure a directory exists, creating it if necessary
11pub 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
20/// Read a file with contextual error message
21pub 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
27/// Write a file with contextual error message, ensuring parent directory exists
28pub 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
37/// Write a file atomically with a contextual error message, ensuring the
38/// parent directory exists.
39///
40/// The content is first written to a temporary file created in the same
41/// directory as `path` (so the final rename stays on the same filesystem and
42/// is therefore atomic), then the temp file is renamed onto `path`. This
43/// prevents concurrent readers -- e.g. another vtcode process sharing the
44/// same workspace -- from ever observing a partially written file.
45///
46/// On rename failure the temp file is best-effort removed before returning
47/// the error.
48pub 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
72/// Build a unique temp file path in the same directory as `path`, suitable
73/// for a write-then-rename atomic publish of `path`.
74fn 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
94/// Write a JSON file
95pub 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
102/// Read and parse a JSON file
103pub 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
110/// Parse JSON with context for better error messages
111pub 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
118/// Serialize JSON with context
119pub 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
123/// Serialize JSON pretty with context
124pub 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/// Parse JSON into a typed value, returning `None` on failure.
130///
131/// Intended for non-critical, best-effort parsing where a missing or malformed
132/// value should be silently ignored. Use `parse_json_with_context` when the
133/// caller needs an actionable error.
134#[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/// Parse JSON into an untyped `Value`, returning `None` on failure.
141///
142/// Same semantics as `try_parse_json` but avoids a type annotation at the call
143/// site when only dynamic inspection is needed.
144#[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/// Parse JSON into a typed value, falling back to `Default` on failure.
151///
152/// A parse failure is logged at `debug` level with the provided `label` so the
153/// failure is visible in traces without being fatal.
154#[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
165/// Canonicalize path with context
166pub 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
171/// Canonicalize path with context (async)
172pub 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
178/// Read a file to string with contextual error (async)
179pub 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
185/// Write a file with contextual error (async)
186pub 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
192/// Create directories recursively with contextual error (async)
193pub 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
199/// Remove a file with contextual error (async)
200pub 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
206/// Rename a file with contextual error (async)
207pub 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
213// --- Sync Versions ---
214
215/// Ensure a directory exists (sync)
216pub 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
224/// Read a file with contextual error message (sync)
225pub 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
230/// Write a file with contextual error message (sync)
231pub 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
239/// Write a JSON file (sync)
240pub 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
247/// Read and parse a JSON file (sync)
248pub 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
255/// Check whether a path looks like an image file based on extension.
256pub 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
275/// Check whether a string is a Windows absolute path (e.g., `C:\...` or `C:/...`).
276pub 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
284/// Remove backslash-escaped whitespace from a token.
285///
286/// A backslash followed by an ASCII whitespace character is replaced by the
287/// whitespace character itself.  All other characters are passed through.
288pub 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
305/// Trim trailing text from a raw image path match.
306///
307/// When a regex greedily matches an image path that contains spaces, it may
308/// also consume trailing prose (e.g., "/path/to/image.png can you see").
309/// This function walks backwards through whitespace-delimited tokens to find
310/// the longest prefix that looks like a valid image path.
311///
312/// The `candidate_check` closure receives a trimmed candidate string and
313/// returns `true` if it should be accepted as a valid image path.
314pub 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
331/// Convenience wrapper for [`trim_trailing_image_path`] that checks
332/// image file extensions via [`has_supported_image_extension`].
333///
334/// Handles `file://` scheme and `~/` home expansion before checking.
335pub 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}