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