Skip to main content

host/
cell_writes.rs

1//! The files a cell wrote through the checked `write()`/`edit()` (`files.before_write`), with their text before and
2//! after, so the cell's result can carry a diff of what it changed (the interactive mode's expanded rlm cell). The
3//! text before is read when the write is proposed, while the file still holds it; at the cell's end a write counts
4//! only when the file holds what was proposed. Files changed by other means (`bash`) are not seen here.
5
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::Mutex;
9use std::sync::atomic::{AtomicBool, Ordering};
10
11/// Files above this size (before or after) are named without their texts.
12pub const MAX_TEXT_BYTES: usize = 256 * 1024;
13/// Files one cell reports.
14pub const MAX_FILES: usize = 32;
15
16/// One file a cell wrote.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct CellWrite {
19    pub path: PathBuf,
20    /// The file did not exist before the cell.
21    pub created: bool,
22    /// The text before (empty for a new file) and after; None when either is too large or not UTF-8.
23    pub texts: Option<(String, String)>,
24}
25
26/// Off until the composition root turns it on ([`crate::Host::recording_cell_writes`]).
27#[derive(Default)]
28pub struct CellWrites {
29    enabled: AtomicBool,
30    lanes: Mutex<HashMap<String, Vec<CellWrite>>>,
31}
32
33fn small_text(path: &Path) -> Result<Option<String>, ()> {
34    match std::fs::metadata(path) {
35        Err(_) => Ok(None),
36        Ok(meta) if !meta.is_file() || meta.len() as usize > MAX_TEXT_BYTES => Err(()),
37        Ok(_) => std::fs::read(path)
38            .ok()
39            .and_then(|bytes| String::from_utf8(bytes).ok())
40            .map(Some)
41            .ok_or(()),
42    }
43}
44
45impl CellWrites {
46    fn lanes(&self) -> std::sync::MutexGuard<'_, HashMap<String, Vec<CellWrite>>> {
47        self.lanes.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
48    }
49
50    pub fn set_enabled(&self, enabled: bool) {
51        self.enabled.store(enabled, Ordering::SeqCst);
52    }
53
54    /// A cell on `lane` starts: forget what an earlier one left (a cell that never ended).
55    pub fn begin(&self, lane: &str) {
56        self.lanes().remove(lane);
57    }
58
59    /// `lane` proposed writing `content` to `path` (absolute) and no hook blocked it. A file written twice keeps its
60    /// first text before.
61    pub fn record(&self, lane: &str, path: &Path, content: &str) {
62        if !self.enabled.load(Ordering::SeqCst) {
63            return;
64        }
65        let mut lanes = self.lanes();
66        let writes = lanes.entry(lane.to_string()).or_default();
67        if let Some(write) = writes.iter_mut().find(|w| w.path == path) {
68            write.texts = match write.texts.take() {
69                Some((before, _)) if content.len() <= MAX_TEXT_BYTES => Some((before, content.to_string())),
70                _ => None,
71            };
72            return;
73        }
74        if writes.len() >= MAX_FILES {
75            return;
76        }
77        let before = small_text(path);
78        let created = matches!(before, Ok(None));
79        let texts = match before {
80            Ok(before) if content.len() <= MAX_TEXT_BYTES => Some((before.unwrap_or_default(), content.to_string())),
81            _ => None,
82        };
83        writes.push(CellWrite {
84            path: path.to_path_buf(),
85            created,
86            texts,
87        });
88    }
89
90    /// What `lane`'s cell wrote, in order (and forget it): the writes whose file now holds the proposed text, minus
91    /// those that changed nothing.
92    pub fn take(&self, lane: &str) -> Vec<CellWrite> {
93        let writes = self.lanes().remove(lane).unwrap_or_default();
94        writes
95            .into_iter()
96            .filter(|write| match &write.texts {
97                Some((before, after)) => {
98                    (write.created || before != after)
99                        && std::fs::read(&write.path).is_ok_and(|now| now == after.as_bytes())
100                }
101                None => write.path.exists(),
102            })
103            .collect()
104    }
105}