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)
}