Skip to main content

stynx_code_engine/application/
undo.rs

1use std::sync::Arc;
2use tokio::sync::Mutex;
3
4pub struct UndoEntry {
5    pub path: String,
6    pub original: Option<String>,
7}
8
9pub type UndoStack = Mutex<Vec<UndoEntry>>;
10
11pub async fn push_file_state(stack: &Arc<UndoStack>, path: &str) {
12    let original = tokio::fs::read_to_string(path).await.ok();
13    stack.lock().await.push(UndoEntry { path: path.to_string(), original });
14}
15
16pub async fn restore(stack: &Arc<UndoStack>, n: usize) -> Vec<(String, bool)> {
17    let mut guard = stack.lock().await;
18    let take = n.min(guard.len());
19    if take == 0 { return Vec::new(); }
20    let len = guard.len();
21    let entries: Vec<_> = guard.drain(len - take..).collect();
22    drop(guard);
23    let mut results = Vec::new();
24    for entry in entries.into_iter().rev() {
25        let ok = match entry.original {
26            Some(c) => tokio::fs::write(&entry.path, c).await.is_ok(),
27            None => tokio::fs::remove_file(&entry.path).await.is_ok(),
28        };
29        results.push((entry.path, ok));
30    }
31    results
32}