use std::{error::Error, fs, path::PathBuf};
use once_cell::sync::Lazy;
static DATA_PATH: Lazy<PathBuf> = Lazy::new(|| {
const FALLBACK_DIR: &str = ".";
#[cfg(target_os = "windows")]
{
use std::{env, path::PathBuf};
let base = env::var("LOCALAPPDATA").unwrap_or_else(|_| FALLBACK_DIR.to_string());
return PathBuf::from(base);
}
#[cfg(target_os = "macos")]
{
let base = env::var("HOME").unwrap_or_else(|_| FALLBACK_DIR.to_string());
return PathBuf::from(base)
.join("Library")
.join("Application Support");
}
#[cfg(target_os = "linux")]
{
use std::env;
let base = env::var("XDG_DATA_HOME")
.or_else(|_| env::var("HOME").map(|h| format!("{}/.local/share", h)))
.unwrap_or_else(|_| FALLBACK_DIR.to_string());
return PathBuf::from(base);
}
#[cfg(target_os = "android")]
{
let base = env::var("HOME").unwrap_or_else(|_| FALLBACK_DIR.to_string());
return PathBuf::from(base); }
#[cfg(target_os = "ios")]
{
let base = env::var("HOME").unwrap_or_else(|_| FALLBACK_DIR.to_string());
return PathBuf::from(base).join("Documents"); }
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "android",
target_os = "ios"
)))]
{
PathBuf::from(FALLBACK_DIR)
}
});
pub fn get_local_usr_data_path(app_folder_name: Option<&str>, subfolder: Option<&str>, create_if_not_exists: bool) -> Result<String, Box<dyn Error>>{
let mut d_path = DATA_PATH.to_path_buf();
if let Some (asf) = app_folder_name{
if asf.trim().len() > 0 {
d_path = d_path.join(asf.trim());
}
}
if let Some(sf) = subfolder{
if sf.trim().len() > 0 {
d_path = d_path.join(sf.trim());
}
}
let path = d_path.to_string_lossy().into_owned();
if create_if_not_exists{
fs::create_dir_all(d_path)?;
}
Ok(path)
}
#[cfg(test)]
mod info_app_tests {
use regex::Regex;
use super::*;
const APP_NAME: &str = "bt_file_cache";
#[test]
fn test_get_app_path_no_create_success() {
let subfolder = "db";
let re = Regex::new(r"^/home/.*/\.local/share/bt_file_cache/db").unwrap();
let df = get_local_usr_data_path(Some(APP_NAME), Some(subfolder), false).unwrap();
assert!(re.is_match(&df));
}
#[test]
fn test_get_app_path_create_fail() {
let subfolder = ":/?\0'"; let df = get_local_usr_data_path(Some(APP_NAME), Some(subfolder), true);
assert!(df.is_err())
}
#[test]
fn test_get_app_path_create_success() {
let subfolder = "db.test"; let re = Regex::new(r"^/home/.*/\.local/share/bt_file_cache/db.test").unwrap();
let df = get_local_usr_data_path(Some(APP_NAME), Some(subfolder), true);
assert!(df.is_ok());
assert!(re.is_match(&df.unwrap()));
}
}