create cache module

This commit is contained in:
2024-12-09 04:31:00 +01:00
parent b0c2c8d478
commit 573fc14767
5 changed files with 52 additions and 50 deletions

34
src/cache.rs Normal file
View File

@@ -0,0 +1,34 @@
use crate::structs::{Cache, StoredGameData};
use std::{fs, path::Path};
pub fn get_cache(dir: &Path) -> Cache {
let cache_path = dir.join("awcache.json");
let cache_content = fs::read_to_string(cache_path).unwrap_or_default();
if cache_content.trim().is_empty() {
Cache::default()
} else {
serde_json::from_str(&cache_content).unwrap_or_default()
}
}
pub fn save_cache(dir: &Path, cache: Cache) {
let cache_path = dir.join("awcache.json");
let cache_serialized = serde_json::to_string_pretty(&cache).unwrap();
fs::write(cache_path, cache_serialized).unwrap_or_else(|e| {
error!("Failed to save cache: {}", e);
});
}
pub fn get_stored_data() -> Option<StoredGameData> {
let dir = std::env::current_dir().ok()?;
let cache = get_cache(&dir);
cache.stored_data
}
pub fn store_game_data(data: &StoredGameData) -> Result<(), Box<dyn std::error::Error>> {
let dir = std::env::current_dir()?;
let mut cache = get_cache(&dir);
cache.stored_data = Some((*data).clone());
save_cache(&dir, cache);
Ok(())
}

View File

@@ -1,5 +1,4 @@
use crate::misc; use crate::structs::PrintPrefix;
use crate::structs::{PrintPrefix, StoredGameData};
use colored::Colorize; use colored::Colorize;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std::collections::HashMap; use std::collections::HashMap;
@@ -66,17 +65,3 @@ pub async fn check_connectivity() -> bool {
} }
} }
} }
pub fn get_stored_data() -> Option<StoredGameData> {
let dir = std::env::current_dir().ok()?;
let cache = misc::get_cache(&dir);
cache.stored_data
}
pub fn store_game_data(data: &StoredGameData) -> Result<(), Box<dyn std::error::Error>> {
let dir = std::env::current_dir()?;
let mut cache = misc::get_cache(&dir);
cache.stored_data = Some((*data).clone());
misc::save_cache(&dir, cache);
Ok(())
}

View File

@@ -1,3 +1,4 @@
mod cache;
mod config; mod config;
mod extend; mod extend;
mod github; mod github;
@@ -376,7 +377,7 @@ async fn update(
let mut cache = if force { let mut cache = if force {
structs::Cache::default() structs::Cache::default()
} else { } else {
misc::get_cache(dir) cache::get_cache(dir)
}; };
if game.engine == "iw4" { if game.engine == "iw4" {
@@ -482,10 +483,10 @@ async fn update(
} }
} }
misc::save_cache(dir, cache); cache::save_cache(dir, cache);
// Store game data for offline mode // Store game data for offline mode
let mut stored_data = global::get_stored_data().unwrap_or_default(); let mut stored_data = cache::get_stored_data().unwrap_or_default();
stored_data.game_path = dir.to_string_lossy().into_owned(); stored_data.game_path = dir.to_string_lossy().into_owned();
// Store available clients for this engine // Store available clients for this engine
@@ -494,7 +495,7 @@ async fn update(
game.client.iter().map(|s| s.to_string()).collect(), game.client.iter().map(|s| s.to_string()).collect(),
); );
if let Err(e) = global::store_game_data(&stored_data) { if let Err(e) = cache::store_game_data(&stored_data) {
println!( println!(
"{} Failed to store game data: {}", "{} Failed to store game data: {}",
PREFIXES.get("error").unwrap().formatted(), PREFIXES.get("error").unwrap().formatted(),
@@ -679,7 +680,7 @@ async fn main() {
let offline_mode = !global::check_connectivity().await; let offline_mode = !global::check_connectivity().await;
if offline_mode { if offline_mode {
// Check if this is a first-time run (no stored data) // Check if this is a first-time run (no stored data)
let stored_data = global::get_stored_data(); let stored_data = cache::get_stored_data();
if stored_data.is_none() { if stored_data.is_none() {
println!( println!(
"{} Internet connection is required for first-time installation.", "{} Internet connection is required for first-time installation.",
@@ -713,7 +714,7 @@ async fn main() {
let cfg = config::load(install_path.join("alterware-launcher.json")); let cfg = config::load(install_path.join("alterware-launcher.json"));
// Try to get stored game data // Try to get stored game data
let stored_data = global::get_stored_data(); let stored_data = cache::get_stored_data();
if let Some(ref data) = stored_data { if let Some(ref data) = stored_data {
info!("Found stored game data for path: {}", data.game_path); info!("Found stored game data for path: {}", data.game_path);
} else { } else {
@@ -933,7 +934,7 @@ async fn main() {
} }
// Store game data for offline mode // Store game data for offline mode
let mut stored_data = global::get_stored_data().unwrap_or_default(); let mut stored_data = cache::get_stored_data().unwrap_or_default();
stored_data.game_path = install_path.to_string_lossy().into_owned(); stored_data.game_path = install_path.to_string_lossy().into_owned();
// Store available clients for this engine // Store available clients for this engine
@@ -942,7 +943,7 @@ async fn main() {
g.client.iter().map(|s| s.to_string()).collect(), g.client.iter().map(|s| s.to_string()).collect(),
); );
if let Err(e) = global::store_game_data(&stored_data) { if let Err(e) = cache::store_game_data(&stored_data) {
println!( println!(
"{} Failed to store game data: {}", "{} Failed to store game data: {}",
PREFIXES.get("error").unwrap().formatted(), PREFIXES.get("error").unwrap().formatted(),

View File

@@ -2,7 +2,7 @@ use std::{fs, path::Path};
use indicatif::{ProgressBar, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
use crate::{global, structs}; use crate::global;
pub fn stdin() -> String { pub fn stdin() -> String {
let mut input = String::new(); let mut input = String::new();
@@ -140,24 +140,6 @@ pub fn prefix(tag_name: &str) -> String {
.map_or_else(|| tag_name.to_string(), |tag| tag.formatted()) .map_or_else(|| tag_name.to_string(), |tag| tag.formatted())
} }
pub fn get_cache(dir: &Path) -> structs::Cache {
let cache_path = dir.join("awcache.json");
let cache_content = fs::read_to_string(cache_path).unwrap_or_default();
if cache_content.trim().is_empty() {
structs::Cache::default()
} else {
serde_json::from_str(&cache_content).unwrap_or_default()
}
}
pub fn save_cache(dir: &Path, cache: structs::Cache) {
let cache_path = dir.join("awcache.json");
let cache_serialized = serde_json::to_string_pretty(&cache).unwrap();
fs::write(cache_path, cache_serialized).unwrap_or_else(|e| {
println_error!("Failed to save cache: {}", e);
});
}
pub fn random_string(length: u32) -> String { pub fn random_string(length: u32) -> String {
use rand::Rng; use rand::Rng;
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();

View File

@@ -49,7 +49,7 @@ mod config {
} }
mod misc { mod misc {
use crate::{fs, misc, structs, Blake3Path}; use crate::{cache, fs, misc, structs, Blake3Path};
use std::{fs::File, io::Write, path::Path}; use std::{fs::File, io::Write, path::Path};
#[test] #[test]
@@ -95,7 +95,7 @@ mod misc {
let cache_file = path.join("awcache.json"); let cache_file = path.join("awcache.json");
// Test initial empty cache // Test initial empty cache
let initial_cache = misc::get_cache(path); let initial_cache = cache::get_cache(path);
assert_eq!(initial_cache, structs::Cache::default()); assert_eq!(initial_cache, structs::Cache::default());
// Test saving and loading cache // Test saving and loading cache
@@ -106,8 +106,8 @@ mod misc {
.collect(), .collect(),
stored_data: None, stored_data: None,
}; };
misc::save_cache(path, test_cache.clone()); cache::save_cache(path, test_cache.clone());
let loaded_cache = misc::get_cache(path); let loaded_cache = cache::get_cache(path);
assert_eq!(loaded_cache, test_cache); assert_eq!(loaded_cache, test_cache);
fs::remove_file(&cache_file).unwrap(); fs::remove_file(&cache_file).unwrap();
@@ -115,7 +115,7 @@ mod misc {
} }
mod stored_data { mod stored_data {
use crate::{fs, global, structs::StoredGameData}; use crate::{cache, fs, structs::StoredGameData};
use serial_test::serial; use serial_test::serial;
use std::{collections::HashMap, path::Path}; use std::{collections::HashMap, path::Path};
@@ -134,8 +134,8 @@ mod stored_data {
let path = Path::new("tests_tmp"); let path = Path::new("tests_tmp");
fs::create_dir_all(path).unwrap(); fs::create_dir_all(path).unwrap();
global::store_game_data(&data).unwrap(); cache::store_game_data(&data).unwrap();
let loaded = global::get_stored_data().unwrap(); let loaded = cache::get_stored_data().unwrap();
assert_eq!(data.game_path, loaded.game_path); assert_eq!(data.game_path, loaded.game_path);
assert_eq!(data.clients, loaded.clients); assert_eq!(data.clients, loaded.clients);