rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Git `--patch` text for one file change, in ACP v2's `git_patch` format:
//! Git's layout, but with absolute paths and no `a/`/`b/` prefixes.

use std::{path::Path, time::Duration};

use similar::TextDiff;

/// One file's text before and after a change.
#[derive(Clone, Copy, Debug)]
pub(super) enum FileContents<'a> {
    Created(&'a str),
    Modified {
        old: &'a str,
        new: &'a str,
    },
    Deleted(&'a str),
    /// Moved here from `from`, and possibly edited on the way.
    Moved {
        from: &'a Path,
        old: &'a str,
        new: &'a str,
    },
}

/// How long one file's diff may search for a minimal patch.
const PATCH_DIFF_DEADLINE: Duration = Duration::from_millis(250);

/// The patch for the change to the file at `path`. `None` when there is
/// nothing to render or a path needs Git's quoting, which v2 makes
/// optional: the change list stays authoritative.
pub(super) fn file_patch(path: &Path, contents: FileContents<'_>) -> Option<String> {
    let path = plain_absolute(path)?;
    // Git names a created or deleted file on both sides of `diff --git`,
    // and `/dev/null` only on the side of `---`/`+++` it is missing from.
    let (source, extended, from, to, old, new) = match contents {
        FileContents::Created(new) => (
            path,
            "new file mode 100644\n".to_owned(),
            "/dev/null",
            path,
            "",
            new,
        ),
        FileContents::Modified { old, new } => (path, String::new(), path, path, old, new),
        FileContents::Deleted(old) => (
            path,
            "deleted file mode 100644\n".to_owned(),
            path,
            "/dev/null",
            old,
            "",
        ),
        FileContents::Moved { from, old, new } => {
            let from = plain_absolute(from)?;
            let rename = format!("rename from {from}\nrename to {path}\n");
            (from, rename, from, path, old, new)
        }
    };
    // Runs inside the update's send. Repetitive 50,000-line rewrites took
    // under 100 ms in a release build; past the deadline the diff is still
    // valid, only less minimal.
    let hunks = TextDiff::configure()
        .timeout(PATCH_DIFF_DEADLINE)
        .diff_lines(old, new)
        .unified_diff()
        .header(from, to)
        .to_string();
    if hunks.is_empty() && extended.is_empty() {
        return None;
    }
    Some(format!("diff --git {source} {path}\n{extended}{hunks}"))
}

/// `path` as patch text, when Git would print it unquoted.
fn plain_absolute(path: &Path) -> Option<&str> {
    let text = path.to_str()?;
    let needs_quoting = text
        .chars()
        .any(|c| c == '"' || c == '\\' || c.is_control() || !c.is_ascii());
    (path.is_absolute() && !needs_quoting).then_some(text)
}

#[cfg(test)]
#[path = "git_patch_tests.rs"]
mod tests;