curd-editor 0.27.3

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! The project as it was before an answer, to tell what the assistant changed
//! and to put it back.

use super::*;

// ---- What Claude changed --------------------------------------------------

/// Files bigger than this are watched for changes but not kept for undo.
pub(super) const MAX_KEPT_BYTES: u64 = 512 * 1024;
/// The most the files kept for undo may take together.
pub(super) const MAX_SNAPSHOT_BYTES: u64 = 32 * 1024 * 1024;

/// What happened to a file while Claude worked.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChangeKind {
    Created,
    Modified,
    Deleted,
}

#[derive(Debug, PartialEq)]
pub struct Change {
    /// The file, relative to the project folder.
    pub file: String,
    pub kind: ChangeKind,
}

/// One file as it was before Claude started.
pub(super) struct Before {
    len: u64,
    modified: Option<SystemTime>,
    /// What was in it; `None` if it was too big to keep.
    content: Option<Vec<u8>>,
}

/// The project's files as they were before Claude started on an answer,
/// to tell afterwards what it changed and to be able to put it back.
pub struct Snapshot {
    root: PathBuf,
    files: HashMap<String, Before>,
}

impl Snapshot {
    /// Remembers `files` (relative to `root`) as they are now.
    pub fn take(root: &Path, files: &[String]) -> Self {
        let mut kept = 0;
        let mut before = HashMap::new();
        for file in files {
            let path = root.join(file);
            let Ok(data) = std::fs::metadata(&path) else {
                continue;
            };
            let fits = data.len() <= MAX_KEPT_BYTES && kept + data.len() <= MAX_SNAPSHOT_BYTES;
            let content = fits.then(|| std::fs::read(&path).ok()).flatten();
            kept += content.as_ref().map_or(0, |content| content.len() as u64);
            before.insert(
                file.clone(),
                Before {
                    len: data.len(),
                    modified: data.modified().ok(),
                    content,
                },
            );
        }
        Self {
            root: root.to_path_buf(),
            files: before,
        }
    }

    /// What is different now, given the project's files as they are now
    /// (`files`), in alphabetical order.
    pub fn changes(&self, files: &[String]) -> Vec<Change> {
        let mut changes = Vec::new();
        for file in files {
            let path = self.root.join(file);
            let kind = match self.files.get(file) {
                // Listed, but not there: nothing was made.
                None if !path.exists() => continue,
                None => ChangeKind::Created,
                Some(before) => {
                    let same = match (&before.content, std::fs::metadata(&path)) {
                        (Some(content), Ok(_)) => std::fs::read(&path).is_ok_and(|now| now == *content),
                        (None, Ok(data)) => {
                            data.len() == before.len && data.modified().ok() == before.modified
                        }
                        // Listed, but not there to look at: leave it be.
                        (_, Err(_)) => true,
                    };
                    if same {
                        continue;
                    }
                    ChangeKind::Modified
                }
            };
            changes.push(Change { file: file.clone(), kind });
        }
        for file in self.files.keys() {
            if !self.root.join(file).exists() {
                changes.push(Change { file: file.clone(), kind: ChangeKind::Deleted });
            }
        }
        changes.sort_by(|a, b| a.file.cmp(&b.file));
        changes
    }

    /// Puts the files of `changes` back the way they were: new ones are
    /// removed, the others get their old contents. Returns how many were
    /// put back and how many could not be (too big to have been kept).
    pub fn restore(&self, changes: &[Change]) -> (usize, usize) {
        let (mut restored, mut failed) = (0, 0);
        for change in changes {
            let path = self.root.join(&change.file);
            let done = match (change.kind, self.files.get(&change.file)) {
                (ChangeKind::Created, _) => std::fs::remove_file(&path).is_ok(),
                (_, Some(Before { content: Some(content), .. })) => {
                    let folder = path.parent().unwrap_or(&self.root);
                    std::fs::create_dir_all(folder).is_ok() && std::fs::write(&path, content).is_ok()
                }
                _ => false,
            };
            if done {
                restored += 1;
            } else {
                failed += 1;
            }
        }
        (restored, failed)
    }
}

/// One line saying what `changes` are: "Changed 2 files: a.rs, new b.rs".
pub fn describe(changes: &[Change]) -> String {
    let names: Vec<String> = changes
        .iter()
        .map(|change| match change.kind {
            ChangeKind::Created => format!("new {}", change.file),
            ChangeKind::Modified => change.file.clone(),
            ChangeKind::Deleted => format!("deleted {}", change.file),
        })
        .collect();
    let files = if changes.len() == 1 { "file" } else { "files" };
    format!("Changed {} {files}: {}", changes.len(), names.join(", "))
}