1use crate::tui::confirmation;
2use simplelog::*;
3use std::env;
4use std::fs::{self, File};
5use std::io::Write;
6use std::path::Path;
7
8pub struct FileUtils {}
9
10impl FileUtils {
11 pub fn create_dir(dir_name: String, dir_path: String) -> Result<(), anyhow::Error> {
12 if Path::new(&dir_path).exists() {
13 info!("Tembo {} path exists", dir_name);
14 return Ok(());
15 }
16
17 match fs::create_dir_all(dir_path) {
18 Err(why) => panic!("Couldn't create {}: {}", dir_name, why),
19 Ok(_) => info!("Tembo {} created", dir_name),
20 };
21
22 Ok(())
23 }
24
25 pub fn create_file(
26 file_name: String,
27 file_path: String,
28 file_content: String,
29 recreate: bool,
30 ) -> Result<(), anyhow::Error> {
31 let path = Path::new(&file_path);
32 if !recreate && path.exists() {
33 info!("Tembo {} file exists", file_name);
34 return Ok(());
35 }
36
37 let parent = path
39 .parent()
40 .ok_or_else(|| anyhow::anyhow!("Failed to get parent directory"))?;
41 fs::create_dir_all(parent)?;
42
43 let display = path.display();
44 let mut file: File = match File::create(path) {
45 Err(why) => panic!("Couldn't create {}: {}", display, why),
46 Ok(file) => file,
47 };
48 info!("Tembo {} file created", file_name);
49
50 if let Err(e) = file.write_all(file_content.as_bytes()) {
51 panic!("Couldn't write to context file: {}", e);
52 }
53 Ok(())
54 }
55
56 pub fn save_tembo_toml(default_text: &str) -> Result<(), Box<dyn std::error::Error>> {
57 let parent_dir = FileUtils::get_current_working_dir();
58 let tembo_toml_path = Path::new(&parent_dir).join("tembo.toml");
59
60 if tembo_toml_path.exists() {
61 print!("Tembo.toml file already exists in this path");
62 Ok(())
63 } else {
64 let mut file = File::create(&tembo_toml_path)?;
65 file.write_all(default_text.as_bytes())?;
66 confirmation("Tembo.toml initialized successfully!");
67
68 Ok(())
69 }
70 }
71
72 pub fn get_current_working_dir() -> String {
73 env::current_dir().unwrap().to_str().unwrap().to_string()
74 }
75}