novel_api/common/utils/
dir.rs

1use std::env;
2use std::path::PathBuf;
3
4use directories::{ProjectDirs, UserDirs};
5
6use crate::Error;
7
8/// Return the path to the user's home directory
9pub fn home_dir_path() -> Result<PathBuf, Error> {
10    if let Some(user_dirs) = UserDirs::new() {
11        Ok(user_dirs.home_dir().to_path_buf())
12    } else {
13        Err(Error::NovelApi(
14            "No valid home directory path could be retrieved from the operating system".to_string(),
15        ))
16    }
17}
18
19/// Return the path to the project's config directory or the current directory on failure
20pub fn config_dir_path(app_name: &str) -> Result<PathBuf, Error> {
21    match ProjectDirs::from("", "novel-rs", app_name) {
22        Some(dir) => Ok(dir.config_dir().to_path_buf()),
23        None => {
24            tracing::error!(
25                "Failed to get the path to the project's config directory, using the current working directory"
26            );
27            Ok(env::current_dir()?)
28        }
29    }
30}
31
32/// Return the path to the project's local data directory or the current directory on failure
33pub fn data_dir_path(app_name: &str) -> Result<PathBuf, Error> {
34    match ProjectDirs::from("", "novel-rs", app_name) {
35        Some(dir) => Ok(dir.data_local_dir().to_path_buf()),
36        None => {
37            tracing::error!(
38                "Failed to get the path to the project's local data directory, using the current working directory"
39            );
40            Ok(env::current_dir()?)
41        }
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn config_dir_path() -> Result<(), Error> {
51        let _ = super::config_dir_path("test-app")?;
52        Ok(())
53    }
54
55    #[test]
56    fn data_dir_path() -> Result<(), Error> {
57        let _ = super::data_dir_path("test-app")?;
58        Ok(())
59    }
60}