J.A.R.V.I.S-rust/crates/jarvis-core/src/db.rs

60 lines
1.4 KiB
Rust
Raw Normal View History

pub mod structs;
pub mod manager;
use crate::{config, APP_CONFIG_DIR};
2025-12-11 23:43:50 +05:00
use log::info;
use std::fs::File;
use std::io::BufReader;
2025-12-11 23:43:50 +05:00
use std::path::PathBuf;
pub use manager::SettingsManager;
fn get_db_file_path() -> PathBuf {
2025-12-11 23:43:50 +05:00
PathBuf::from(format!(
"{}/{}",
APP_CONFIG_DIR.get().unwrap().display(),
config::DB_FILE_NAME
))
}
pub fn init_settings() -> structs::Settings {
let db_file_path = get_db_file_path();
2025-12-11 23:43:50 +05:00
info!(
"Loading settings db file located at: {}",
db_file_path.display()
);
if db_file_path.exists() {
if let Ok(db_file) = File::open(&db_file_path) {
let reader = BufReader::new(db_file);
if let Ok(settings) = serde_json::from_reader(reader) {
info!("Settings loaded.");
return settings;
}
}
}
warn!("No settings file found or there was an error parsing it. Creating default struct.");
structs::Settings::default()
}
/// init settings and return a SettingsManager ready to use
pub fn init() -> SettingsManager {
let settings = init_settings();
SettingsManager::new(settings)
}
pub fn save_settings(settings: &structs::Settings) -> Result<(), std::io::Error> {
let db_file_path = get_db_file_path();
std::fs::write(
2026-01-04 09:00:51 +05:00
&db_file_path,
2025-12-11 23:43:50 +05:00
serde_json::to_string_pretty(&settings).unwrap(),
)?;
2026-01-04 09:00:51 +05:00
info!("Settings saved to: {:#}", db_file_path.display());
Ok(())
2025-12-11 23:43:50 +05:00
}