lib_tasker/io/
mod.rs

1use crate::{error::TaskerFailure, todos::ToDo};
2use camino::{Utf8Path, Utf8PathBuf};
3use directories::ProjectDirs;
4use std::io::Write;
5
6/// Returns an object containing the project's respective directories to store
7/// data.
8///
9/// # Errors
10///
11/// Returns an error if the program can't determine the appropiate directories
12/// to store its data in the user's operating system.
13pub fn get_project_directories() -> Result<ProjectDirs, TaskerFailure> {
14    let project_directories = ProjectDirs::from("dev", "DaliaReds", "tasker")
15        .ok_or(TaskerFailure::ProjectDirectoryError(
16        std::io::Error::new(
17            std::io::ErrorKind::Unsupported,
18            "System not supported",
19        ),
20    ))?;
21
22    if !project_directories.config_dir().exists() {
23        std::fs::create_dir_all(project_directories.config_dir())?;
24    }
25
26    if !project_directories.data_dir().exists() {
27        std::fs::create_dir_all(project_directories.data_dir())?;
28    }
29
30    Ok(project_directories)
31}
32
33impl ToDo {
34    /// Parses and returns a deserialized `ToDo` struct from the given file path.
35    ///
36    /// # Errors
37    ///
38    /// Returns an error if the program failed to read the given file.
39    pub fn get_to_do(file_path: &Utf8Path) -> Result<Self, TaskerFailure> {
40        match file_path.try_exists() {
41            Ok(true) => {
42                Ok(ron::from_str(std::fs::read_to_string(file_path)?.as_str())?)
43            }
44            Ok(false) => Ok(Self::default()),
45            Err(err) => Err(TaskerFailure::ProjectDirectoryError(err)),
46        }
47    }
48
49    /// Returns the default path to store Tasks in.
50    ///
51    /// # Errors
52    ///
53    /// Returns an error if it failed to determine the default file paths for
54    /// the program or if this path is not valid UTF-8.
55    pub fn get_default_to_do_path() -> Result<Utf8PathBuf, TaskerFailure> {
56        let dirs = get_project_directories()?;
57
58        let mut config_dir =
59            Utf8PathBuf::try_from(dirs.data_dir().to_path_buf())?;
60        config_dir.push("todo.ron");
61
62        Ok(config_dir)
63    }
64
65    /// Writes the Tassk into the filesystem.
66    ///
67    /// # Errors
68    ///
69    /// Returns an error if it failed to create the file at the given location,
70    /// if it failed to serialize the `ToDo` struct into the RON file format or
71    /// if it failed to write data into the given file path.
72    pub fn save(&self, path: &Utf8Path) -> Result<(), TaskerFailure> {
73        let mut to_do_file = std::fs::File::create(path)?;
74
75        to_do_file.write_all(ron::to_string(self)?.as_bytes())?;
76
77        Ok(())
78    }
79}