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