orn_cli/
file_manager.rs

1use std::collections::HashMap;
2use std::fs;
3use std::io::{Read, Write};
4use std::path::PathBuf;
5
6use glob::glob;
7
8use crate::core_error::CoreError;
9
10pub struct FileManager {
11    files: HashMap<String, PathBuf>,
12}
13
14impl FileManager {
15    pub fn load(patterns: &Vec<String>) -> Result<Self, CoreError> {
16        let mut files = HashMap::<String, PathBuf>::new();
17        for pattern in patterns {
18            for path in glob(pattern)? {
19                let path = path?;
20                // Check if the path is a file
21                if !path.is_file() {
22                    continue;
23                }
24                files.insert(path.display().to_string(), path);
25            }
26        }
27        Ok(Self { files })
28    }
29}
30
31impl FileManager {
32    pub fn update<F>(&self, updater: F) -> Result<(), CoreError>
33    where
34        F: Fn(String) -> String,
35    {
36        for (file_name, file_path) in &self.files {
37            let mut file = fs::File::open(file_path)?;
38            let mut content = String::new();
39            file.read_to_string(&mut content)?;
40            let result = updater(content);
41            let mut file = fs::File::create(file_name)?; // Open the file in write mode (truncate the file)
42            file.write_all(result.as_bytes())?; // Write the new content
43            println!("{:?}: updated", file_name)
44        }
45        Ok(())
46    }
47
48    pub fn print(&self) {
49        eprintln!("files = {:#?}", self.files);
50    }
51}