mold_cli/utils/
file.rs

1use anyhow::{Context, Result};
2use std::fs;
3use std::path::Path;
4
5/// Read a file's contents as a string
6pub fn read_file(path: &Path) -> Result<String> {
7    fs::read_to_string(path)
8        .with_context(|| format!("Failed to read file: {}", path.display()))
9}
10
11/// Write content to a file, creating parent directories if needed
12pub fn write_file(path: &Path, content: &str) -> Result<()> {
13    if let Some(parent) = path.parent() {
14        fs::create_dir_all(parent)
15            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
16    }
17    fs::write(path, content)
18        .with_context(|| format!("Failed to write file: {}", path.display()))
19}
20
21/// Extract the file stem (name without extension) from a path
22pub fn get_file_stem(path: &Path) -> String {
23    path.file_stem()
24        .and_then(|s| s.to_str())
25        .unwrap_or("Schema")
26        .to_string()
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    use std::path::PathBuf;
33
34    #[test]
35    fn test_get_file_stem() {
36        assert_eq!(get_file_stem(&PathBuf::from("user.json")), "user");
37        assert_eq!(get_file_stem(&PathBuf::from("/path/to/schema.json")), "schema");
38        assert_eq!(get_file_stem(&PathBuf::from("data")), "data");
39    }
40}