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