foundry_mcp/core/
filesystem.rs

1//! File system operations and utilities
2
3use anyhow::{Context, Result};
4use std::fs;
5use std::path::{Path, PathBuf};
6
7/// Ensure the foundry directory exists
8pub fn ensure_foundry_dir() -> Result<PathBuf> {
9    let foundry_dir = dirs::home_dir()
10        .context("Could not determine home directory")?
11        .join(".foundry");
12
13    if !foundry_dir.exists() {
14        fs::create_dir_all(&foundry_dir)
15            .with_context(|| format!("Failed to create foundry directory: {:?}", foundry_dir))?;
16    }
17
18    Ok(foundry_dir)
19}
20
21/// Get the foundry directory path
22pub fn foundry_dir() -> Result<PathBuf> {
23    ensure_foundry_dir()
24}
25
26/// Write content to a file atomically
27pub fn write_file_atomic<P: AsRef<Path>>(path: P, content: &str) -> Result<()> {
28    let path = path.as_ref();
29
30    // Ensure parent directory exists
31    if let Some(parent) = path.parent() {
32        fs::create_dir_all(parent)
33            .with_context(|| format!("Failed to create parent directory: {:?}", parent))?;
34    }
35
36    // Write to temporary file first
37    let temp_path = path.with_extension(format!(
38        "{}.tmp",
39        path.extension().unwrap_or_default().to_string_lossy()
40    ));
41    fs::write(&temp_path, content)
42        .with_context(|| format!("Failed to write to temporary file: {:?}", temp_path))?;
43
44    // Atomic rename
45    fs::rename(&temp_path, path)
46        .with_context(|| format!("Failed to rename temporary file to: {:?}", path))?;
47
48    Ok(())
49}
50
51/// Read file content
52pub fn read_file<P: AsRef<Path>>(path: P) -> Result<String> {
53    let path = path.as_ref();
54    fs::read_to_string(path).with_context(|| format!("Failed to read file: {:?}", path))
55}
56
57/// Check if a file exists
58pub fn file_exists<P: AsRef<Path>>(path: P) -> bool {
59    path.as_ref().exists()
60}
61
62/// Create a directory and all necessary parent directories
63pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
64    let path = path.as_ref();
65    fs::create_dir_all(path).with_context(|| format!("Failed to create directory: {:?}", path))
66}