wiki_o/io/
file.rs

1use anyhow::Result;
2use serde_derive::Deserialize;
3use serde_derive::Serialize;
4use std::fmt::Display;
5use std::fs;
6use std::fs::OpenOptions;
7use std::io::Seek;
8use std::io::SeekFrom;
9use std::io::Write;
10
11use crate::logging::logger::{added, deleted};
12
13#[derive(Debug, Deserialize, Serialize)]
14pub struct WikioFile {
15    pub file: String,
16    pub content: String,
17    pub file_name: String,
18}
19
20impl Display for WikioFile {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        write!(
23            f,
24            "file: {}\ncontent: {}\nfile_name: {}",
25            self.file, self.content, self.file_name
26        )
27    }
28}
29
30pub fn read_from_file(file_path: &String) -> Result<String> {
31    let content = std::fs::read_to_string(file_path)?;
32    Ok(content)
33}
34
35pub fn write_to_file(file_name: String, file_path: String, content: String) -> Result<()> {
36    let mut file = OpenOptions::new()
37        .read(true)
38        .create(true)
39        .append(true)
40        .open(file_path)?;
41
42    file.seek(SeekFrom::Start(0))?;
43    file.write_all(content.as_bytes())?;
44
45    added(content.trim().to_string(), file_name.to_string());
46
47    Ok(())
48}
49
50pub fn delete_file(file: String) -> Result<()> {
51    fs::remove_file(&file)?;
52    deleted(true, file);
53    Ok(())
54}
55
56pub fn delete_all_dirs(dir: String) -> Result<()> {
57    let deleted_dir = std::fs::remove_dir_all(&dir);
58    if deleted_dir.is_ok() {
59        deleted(false, dir);
60    }
61    Ok(())
62}
63
64pub fn read_all_files_in_dir(dir: String) -> Result<Vec<WikioFile>> {
65    let paths = fs::read_dir(dir)?;
66
67    let mut files: Vec<WikioFile> = vec![];
68
69    for path in paths {
70        let path = path?;
71        let file_i = path.file_name().to_str().get_or_insert("").to_string();
72        let path_i = path.path().display().to_string();
73        let content = read_from_file(&path_i)?;
74
75        files.push(WikioFile {
76            file: path_i.clone(),
77            content: content.clone(),
78            file_name: file_i.clone(),
79        });
80    }
81
82    Ok(files)
83}
84
85pub fn create_dir_if_not_exist(dir: &String) -> Result<String> {
86    if fs::metadata(dir).is_err() {
87        fs::create_dir_all(dir)?;
88        return Ok(dir.clone());
89    }
90
91    Ok(dir.clone())
92}