Mountain/ApplicationState/Internal/Persistence/
MementoSaver.rs1use std::{collections::HashMap, fs, path::Path};
32
33use serde_json::Value;
34use log::{debug, error};
35use CommonLibrary::Error::CommonError::CommonError;
36
37pub async fn SaveMementoToDisk(StorageFilePath:&Path, MementoData:&HashMap<String, Value>) -> Result<(), CommonError> {
54 if let Some(parent) = StorageFilePath.parent() {
56 if !parent.exists() {
57 fs::create_dir_all(parent).map_err(|e| {
58 error!("[MementoSaver] Failed to create directory '{}': {}", parent.display(), e);
59 CommonError::FileSystemIO {
60 Path:parent.to_path_buf(),
61 Description:format!("Failed to create directory: {}", e),
62 }
63 })?;
64 debug!("[MementoSaver] Created directory: {}", parent.display());
65 }
66 }
67
68 let json_content = serde_json::to_string_pretty(MementoData).map_err(|e| {
70 error!("[MementoSaver] Failed to serialize memento data: {}", e);
71 CommonError::SerializationError { Description:format!("Failed to serialize memento data: {}", e) }
72 })?;
73
74 let temp_path = StorageFilePath.with_extension("json.tmp");
76 fs::write(&temp_path, json_content).map_err(|e| {
77 error!(
78 "[MementoSaver] Failed to write memento to temp file '{}': {}",
79 temp_path.display(),
80 e
81 );
82 CommonError::FileSystemIO { Path:temp_path.clone(), Description:format!("Failed to write memento: {}", e) }
83 })?;
84
85 fs::rename(&temp_path, StorageFilePath).map_err(|e| {
87 error!(
88 "[MementoSaver] Failed to rename temp file to '{}': {}",
89 StorageFilePath.display(),
90 e
91 );
92 let _ = fs::remove_file(&temp_path);
94 CommonError::FileSystemIO {
95 Path:StorageFilePath.to_path_buf(),
96 Description:format!("Failed to rename memento file: {}", e),
97 }
98 })?;
99
100 debug!("[MementoSaver] Successfully saved memento to: {}", StorageFilePath.display());
101
102 Ok(())
103}