Skip to main content

session_core/
cell_file_changes.rs

1//! The diff of what an rlm cell wrote, in its result's `details.fileChanges` (Rust-only; the TypeScript result's
2//! details stay `{}`): `[{path, created, diff}]` per file written through the checked `write()`/`edit()`
3//! ([`host::cell_writes`]), `diff` in the edit tool's display format (`generateDiffString`, context 2), or null for a
4//! file too large or not text. The interactive mode shows it under the expanded cell.
5
6use host::Host;
7use serde_json::{Value, json};
8
9pub const CONTEXT_LINES: usize = 2;
10/// Diff lines kept per file; the rest is counted in `omitted`.
11pub const MAX_DIFF_LINES: usize = 400;
12
13/// `details` of the result of `lane`'s cell that just ended: `{}`, or `{fileChanges: [...]}`. `mask` hides secrets
14/// in each diff as in the cell's output (the files' texts are not masked on disk).
15pub fn details(host: &Host, lane: &str, mask: &dyn Fn(&str) -> String) -> Value {
16    let changes: Vec<Value> = host
17        .take_cell_writes(lane)
18        .into_iter()
19        .map(|write| {
20            let path =
21                host::file_hooks::inside(host.cwd(), &write.path).unwrap_or_else(|| write.path.display().to_string());
22            let mut change = json!({ "path": path, "created": write.created, "diff": null });
23            if let Some((before, after)) = &write.texts {
24                let (diff, _) = jsrt::diff::generate_diff_string(before, after, CONTEXT_LINES);
25                let diff = mask(&diff);
26                let lines: Vec<&str> = diff.split('\n').collect();
27                change["diff"] = json!(lines[..lines.len().min(MAX_DIFF_LINES)].join("\n"));
28                if lines.len() > MAX_DIFF_LINES {
29                    change["omitted"] = json!(lines.len() - MAX_DIFF_LINES);
30                }
31            }
32            change
33        })
34        .collect();
35    if changes.is_empty() {
36        json!({})
37    } else {
38        json!({ "fileChanges": changes })
39    }
40}