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 dev_log!("storage", "[MementoSaver] Created directory: {}", parent.display());
71 }
72 }
73
74 let json_content = serde_json::to_string_pretty(MementoData).map_err(|e| {
76 dev_log!("storage", "error: [MementoSaver] Failed to serialize memento data: {}", e);
77 CommonError::SerializationError { Description:format!("Failed to serialize memento data: {}", e) }
78 })?;
79
80 let temp_path = StorageFilePath.with_extension("json.tmp");
82 fs::write(&temp_path, json_content).map_err(|e| {
83 dev_log!(
84 "storage",
85 "error: [MementoSaver] Failed to write memento to temp file '{}': {}",
86 temp_path.display(),
87 e
88 );
89 CommonError::FileSystemIO { Path:temp_path.clone(), Description:format!("Failed to write memento: {}", e) }
90 })?;
91
92 fs::rename(&temp_path, StorageFilePath).map_err(|e| {
94 dev_log!(
95 "storage",
96 "error: [MementoSaver] Failed to rename temp file to '{}': {}",
97 StorageFilePath.display(),
98 e
99 );
100 let _ = fs::remove_file(&temp_path);
102 CommonError::FileSystemIO {
103 Path:StorageFilePath.to_path_buf(),
104 Description:format!("Failed to rename memento file: {}", e),
105 }
106 })?;
107
108 dev_log!(
109 "storage",
110 "[MementoSaver] Successfully saved memento to: {}",
111 StorageFilePath.display()
112 );
113
114 Ok(())
115}