rusty_cli/
file_reader.rs

1use std::fs;
2use std::fs::{File, OpenOptions};
3use std::io::{Read, Write};
4use std::path::{Path, PathBuf};
5use platform_dirs::AppDirs;
6
7pub struct FileReader {
8    /// The directory all application files are stored in
9    platform_dir: PathBuf
10}
11
12impl FileReader {
13
14    /// Creates a new file-reader for reading files from
15    /// the app dir with the provided name
16    pub fn new(app_folder: String) -> Self {
17        FileReader {platform_dir: AppDirs::new(Some(app_folder.as_str()), false).unwrap().data_dir}
18    }
19
20    /// Reads a string from a file contained in the app directory
21    /// of the cli application
22    pub fn read_file_to_string(&mut self, file_name: String) -> String {
23        let path = PathBuf::as_path(&self.platform_dir);
24        if !Path::exists(&path) {
25            fs::create_dir(path.clone()).expect("Cannot create root data directory");
26        }
27        let str_path = path.to_str().unwrap().to_owned() + file_name.as_str();
28        let raw_file = File::open(&str_path);
29        let mut file = match raw_file {
30            Ok(f) => f,
31            Err(_e) => {
32                let mut f = OpenOptions::new()
33                    .write(true)
34                    .create(true)
35                    .read(true)
36                    .truncate(true)
37                    .open(str_path)
38                    .unwrap();
39                f.write_all("".as_bytes()).unwrap();
40                f
41            }
42        };
43        let mut data = String::new();
44        file.read_to_string(&mut data)
45            .expect("Failed reading config");
46        if data.is_empty() {
47            return String::new();
48        }
49        data
50    }
51
52    /// Writes string content to the file with the provided
53    /// file name and closes it after the write process
54    pub fn write_string_to_file(&mut self, file_name: String, content: String) {
55        let path = PathBuf::as_path(&self.platform_dir);
56        let mut file = OpenOptions::new()
57            .write(true)
58            .create(true)
59            .truncate(true)
60            .open(path.to_str().unwrap().to_owned() + file_name.as_str())
61            .unwrap();
62        file.write_all(content.as_str().as_ref())
63            .expect("Cannot write data");
64    }
65}