rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho/git/diff`: a repository's uncommitted changes as one patch,
//! ported from rho-ui's Diff panel (`right_panel/diff.rs`, its `SCRIPT`
//! and `diff_here`), streamed whole file by whole file up to a limit.

use std::{
    ffi::OsString,
    path::{Path, PathBuf},
    process::ExitStatus,
};

use rho_protocol::{
    methods::{
        GitDiff, GitDiffParams, GIT_DIFF, GIT_DIFF_MAX_BYTES, HOST_STREAM_FAILURE_MAX_BYTES,
    },
    Caller, ClientEnvironment, ErrorCode, HostStreamWriter, RpcError,
};
use tokio::{
    io::{AsyncBufReadExt as _, AsyncReadExt as _, BufReader},
    process::{ChildStdout, Command},
};

use super::{
    absolute, failed, git_command, host_path, log_call, spawn_stream, toplevel, Machine,
    PIPE_READ_BYTES,
};
use crate::git::{did_not_start, git_failure, output_within, Running, UNTRACKED_FILES};

/// Where each file's patch starts, after the newline that ends the file
/// before: rho-ui cuts a patch here, so it keeps whole files.
const FILE_START: &[u8] = b"\ndiff --git ";

/// `git diff` as rho-ui ran it: no colors or external diff tool a user's
/// configuration may set, so the patch is one a client reads, and names
/// that are not ASCII left as they are rather than quoted. Its headers name
/// files `a/…` and `b/…` whatever `diff.noprefix` or `diff.mnemonicPrefix`
/// say, and it takes no optional lock, as on the index it would refresh,
/// so it never races the user's own git.
const DIFF: &[&str] = &[
    "--no-optional-locks",
    "-c",
    "core.quotepath=off",
    "diff",
    "--no-color",
    "--no-ext-diff",
    "--src-prefix=a/",
    "--dst-prefix=b/",
];

/// Answers `rho/git/diff`: from the top of the work tree `folder` is in,
/// the changes to tracked files against `HEAD`, or the empty tree before
/// the first commit, then each untracked file git does not ignore as a new
/// one, as rho-ui's script printed them. Fails before the stream opens
/// when git cannot say what to diff against or does not start.
pub(super) async fn diff(
    machine: &Machine,
    caller: Caller,
    params: GitDiffParams,
) -> Result<GitDiff, RpcError> {
    let GitDiffParams { folder, limit, .. } = params;
    log_call(&caller, GIT_DIFF, [&folder]);
    let folder = absolute(&folder)?;
    if limit > GIT_DIFF_MAX_BYTES {
        return Err(RpcError::new(
            ErrorCode::InvalidParams,
            format!("limit {limit} is past the most a diff streams, {GIT_DIFF_MAX_BYTES}"),
        ));
    }
    let environment = machine.login_environment().await;
    // Not a folder, no git, or in no repository, as rho-ui's script told.
    let Some(top) = toplevel(folder, &environment).await.map_err(failed)? else {
        return Ok(GitDiff::NotRepo);
    };
    let Ok(top_path) = host_path(&top) else {
        return Ok(GitDiff::NotRepo);
    };
    let base = base(&top, &environment).await?;
    let tracked = Running::start(
        git_command(&top, &environment)
            .args(DIFF)
            .args([base.as_str(), "--"]),
        HOST_STREAM_FAILURE_MAX_BYTES,
    )
    .map_err(|error| failed(did_not_start(&top, &error)))?;
    let stream = spawn_stream(&caller, move |writer| {
        stream_changes(Patch::new(writer, limit), top, environment, tracked)
    })?;
    Ok(GitDiff::Patch {
        top: top_path,
        stream,
    })
}

/// What the repository at `top` is diffed against: `HEAD`, or before the
/// first commit the empty tree. Fails when git doesn't answer within its
/// deadline, rather than taking a `HEAD` it couldn't read for none.
async fn base(top: &Path, environment: &ClientEnvironment) -> Result<String, RpcError> {
    let head = output_within(
        git_command(top, environment).args(["rev-parse", "-q", "--verify", "HEAD"]),
        top,
    )
    .await
    .map_err(|no_output| failed(no_output.message(top)))?;
    if head.status.success() {
        return Ok("HEAD".to_owned());
    }
    // Hashed from an empty stdin, so a repository whose objects are named
    // by SHA-256 gets its own empty tree.
    let output = output_within(
        git_command(top, environment).args(["hash-object", "-t", "tree", "--stdin"]),
        top,
    )
    .await
    .map_err(|no_output| failed(no_output.message(top)))?;
    if !output.status.success() {
        return Err(failed(git_failure(&output.stderr, output.status)));
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}

/// Why the patch stopped before git was done.
enum Stop {
    /// A file did not fit in the limit: the stream ends truncated.
    Cut,
    /// The client closed the stream.
    Closed,
    /// git failed, or could not be read, for this reason.
    Failed(String),
}

/// What a patch's next bytes complete.
#[derive(Debug, Default, PartialEq, Eq)]
struct Split {
    /// The whole files to write, in order, each within the limit.
    files: Vec<Vec<u8>>,
    /// Whether the patch is cut after `files`: the next file does not fit,
    /// so nothing more of it is kept.
    cut: bool,
}

/// A patch cut into whole files, each complete once the next one starts or
/// the patch ends, and kept only while all kept fit in `limit` bytes, so a
/// stream holds what rho-ui's `cut` kept. [`Patch`] writes what it keeps.
struct Splitter {
    limit: u64,
    /// The bytes of the files kept so far.
    kept: u64,
    /// The file under way, from its start: the only part of the patch held.
    file: Vec<u8>,
    /// How much of `file` was searched for the next file's start.
    searched: usize,
}

impl Splitter {
    fn new(limit: u64) -> Self {
        Self {
            limit,
            kept: 0,
            file: Vec::new(),
            searched: 0,
        }
    }

    /// Takes in the patch's next bytes, however git's reads cut it. Nothing
    /// is pushed once a split is cut.
    fn push(&mut self, bytes: &[u8]) -> Split {
        let mut split = Split::default();
        self.file.extend_from_slice(bytes);
        loop {
            // A start the last push cut short may end in these bytes.
            let from = self.searched.saturating_sub(FILE_START.len() - 1);
            let Some(at) = find(&self.file[from..], FILE_START) else {
                break;
            };
            // Up to the newline that ends it.
            let next = self.file.split_off(from + at + 1);
            let file = std::mem::replace(&mut self.file, next);
            self.searched = 0;
            if !self.keep(file, &mut split) {
                return split;
            }
        }
        self.searched = self.file.len();
        // The file under way holds at least this, whatever comes next: the
        // rest may start the next file. Cut now when even that won't fit.
        let least = self.file.len().saturating_sub(FILE_START.len() - 1) as u64;
        split.cut = self.kept + least > self.limit;
        split
    }

    /// Ends the patch: its last file, if it fits.
    fn end(mut self) -> Split {
        let mut split = Split::default();
        let last = std::mem::take(&mut self.file);
        self.keep(last, &mut split);
        split
    }

    /// Keeps `file` in `split` when it fits after what was kept, else cuts
    /// `split`; whether it fit.
    fn keep(&mut self, file: Vec<u8>, split: &mut Split) -> bool {
        let kept = self.kept + file.len() as u64;
        if kept > self.limit {
            split.cut = true;
            return false;
        }
        self.kept = kept;
        if !file.is_empty() {
            split.files.push(file);
        }
        true
    }
}

/// The patch a `diff` stream carries: the whole files its [`Splitter`]
/// keeps.
struct Patch {
    writer: HostStreamWriter,
    splitter: Splitter,
}

impl Patch {
    fn new(writer: HostStreamWriter, limit: u64) -> Self {
        Self {
            writer,
            splitter: Splitter::new(limit),
        }
    }

    /// Takes in what git printed next, writing each file it ends.
    async fn take(&mut self, bytes: &[u8]) -> Result<(), Stop> {
        let split = self.splitter.push(bytes);
        write_split(&mut self.writer, split).await
    }

    /// Ends the stream as `stopped` says: once git is done, after the last
    /// file, if it fits.
    async fn end(self, stopped: Result<(), Stop>) {
        let Self {
            mut writer,
            splitter,
        } = self;
        let stopped = match stopped {
            Ok(()) => write_split(&mut writer, splitter.end()).await,
            Err(stop) => Err(stop),
        };
        match stopped {
            Ok(()) => writer.finish(),
            Err(Stop::Cut) => writer.truncate(),
            Err(Stop::Closed) => {}
            Err(Stop::Failed(message)) => writer.fail(message),
        }
    }
}

/// Writes the files `split` completes, then stops when it is cut.
async fn write_split(writer: &mut HostStreamWriter, split: Split) -> Result<(), Stop> {
    for file in split.files {
        writer.write(file).await.map_err(|_| Stop::Closed)?;
    }
    if split.cut {
        Err(Stop::Cut)
    } else {
        Ok(())
    }
}

/// Streams the changes in the repository at `top`: what `tracked`, the
/// diff of its tracked files, prints, then each untracked file's.
async fn stream_changes(
    mut patch: Patch,
    top: PathBuf,
    environment: ClientEnvironment,
    tracked: Running,
) {
    let stopped = write_changes(&mut patch, &top, &environment, tracked).await;
    patch.end(stopped).await;
}

/// Feeds `patch` what `tracked` prints, then each untracked file git does
/// not ignore as a new one, in the order `ls-files` lists them. Diffs no
/// more of them once one does not fit, as rho-ui's `diff_here` did not.
/// Returning early drops the git running, which kills it.
async fn write_changes(
    patch: &mut Patch,
    top: &Path,
    environment: &ClientEnvironment,
    mut tracked: Running,
) -> Result<(), Stop> {
    feed(patch, &mut tracked.stdout).await?;
    tracked
        .finish(ExitStatus::success)
        .await
        .map_err(Stop::Failed)?;
    let mut untracked = start(git_command(top, environment).args(UNTRACKED_FILES), top)?;
    let mut names = BufReader::new(&mut untracked.stdout);
    let mut name = Vec::new();
    loop {
        name.clear();
        let read = names
            .read_until(0, &mut name)
            .await
            .map_err(|error| Stop::Failed(format!("Couldn't read what git listed: {error}")))?;
        if read == 0 {
            break;
        }
        if name.last() == Some(&0) {
            name.pop();
        }
        // One this machine cannot name cannot be diffed.
        let Some(file) = os_name(&name).filter(|file| !file.is_empty()) else {
            continue;
        };
        let mut git = start(
            git_command(top, environment)
                .args(DIFF)
                .args(["--no-index", "--", "/dev/null"])
                .arg(file),
            top,
        )?;
        feed(patch, &mut git.stdout).await?;
        git.finish(diffed).await.map_err(Stop::Failed)?;
    }
    drop(names);
    untracked
        .finish(ExitStatus::success)
        .await
        .map_err(Stop::Failed)
}

/// Starts `command`, git in `top`, once the stream is open: one that
/// doesn't start fails the stream, naming the folder.
fn start(command: &mut Command, top: &Path) -> Result<Running, Stop> {
    Running::start(command, HOST_STREAM_FAILURE_MAX_BYTES)
        .map_err(|error| Stop::Failed(did_not_start(top, &error)))
}

/// Whether `diff --no-index` ended as it should: 0 when its files are the
/// same, 1 when they differ, as for every new file.
fn diffed(status: &ExitStatus) -> bool {
    status.success() || status.code() == Some(1)
}

/// Feeds `patch` all that `stdout`, git's, prints, until it ends or the
/// client closes the stream.
async fn feed(patch: &mut Patch, stdout: &mut ChildStdout) -> Result<(), Stop> {
    let mut buffer = vec![0; PIPE_READ_BYTES];
    loop {
        let read = tokio::select! {
            read = stdout.read(&mut buffer) => read,
            () = patch.writer.closed() => return Err(Stop::Closed),
        };
        let read =
            read.map_err(|error| Stop::Failed(format!("Couldn't read git's diff: {error}")))?;
        if read == 0 {
            return Ok(());
        }
        patch.take(&buffer[..read]).await?;
    }
}

/// Where `needle` first is in `haystack`.
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

/// A path `ls-files` printed, as an argument: its bytes on Unix.
#[cfg(unix)]
fn os_name(bytes: &[u8]) -> Option<OsString> {
    use std::os::unix::ffi::OsStrExt as _;
    Some(std::ffi::OsStr::from_bytes(bytes).to_owned())
}

/// A path `ls-files` printed, as an argument: git prints UTF-8 here.
#[cfg(not(unix))]
fn os_name(bytes: &[u8]) -> Option<OsString> {
    String::from_utf8(bytes.to_vec()).ok().map(OsString::from)
}

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