use std::{
fs::{create_dir_all, read_to_string},
path::{Path, PathBuf},
};
use anyhow::{Context, Result, anyhow};
use directories::{BaseDirs, ProjectDirs};
use serde::{Deserialize, Serialize};
use crate::constants::OLD_MANAGER_FOLDER_NAME;
pub fn deserialize_from_json<T>(file_path: &Path) -> Result<T>
where
for<'a> T: Deserialize<'a>,
{
let text = read_to_string(file_path)?;
serde_json::from_str(fix_bom(&text)).context("Failed to parse JSON")
}
pub fn serialize_to_json<T>(obj: &T, out_path: &Path, create_parents: bool) -> Result<()>
where
T: Serialize,
{
if create_parents && let Some(parent_path) = out_path.parent() {
create_dir_all(parent_path)?;
}
let text = serde_json::to_string_pretty(obj)?;
std::fs::write(out_path, text).context("Failed to write JSON")
}
pub fn get_app_path() -> Result<PathBuf> {
let app_data_path = ProjectDirs::from("com", "ow-mods", "ow-mod-man");
match app_data_path {
Some(app_data_path) => Ok(app_data_path.data_dir().to_path_buf()),
None => Err(anyhow!("Can't find user's app data dir")),
}
}
pub fn get_default_owml_path() -> Result<PathBuf> {
let base_dirs = BaseDirs::new().context("Couldn't Get User App Data")?;
let appdata_dir = base_dirs.data_dir();
Ok(appdata_dir.join(OLD_MANAGER_FOLDER_NAME).join("OWML"))
}
pub fn check_file_matches_paths(path: &Path, to_check: &[PathBuf]) -> bool {
for check in to_check.iter() {
if check.file_name().unwrap_or(check.as_os_str())
== path.file_name().unwrap_or(path.as_os_str())
|| path.starts_with(check)
{
return true;
}
}
false
}
pub fn create_all_parents(file_path: &Path) -> Result<()> {
if let Some(parent_path) = file_path.parent() {
create_dir_all(parent_path)?;
}
Ok(())
}
pub fn fix_bom(str: &str) -> &str {
str.strip_prefix('\u{FEFF}').unwrap_or(str)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_file_matches_path() {
let test_path = Path::new("folder/some_file.json");
let test_parent = PathBuf::from("folder");
let unrelated_parent = PathBuf::from("other_folder");
assert!(check_file_matches_paths(test_path, &[test_parent]));
assert!(!check_file_matches_paths(test_path, &[unrelated_parent]),);
}
}