rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Running `git` for what it prints: to its end within [`GIT_DEADLINE`]
//! for a short read, or piped while a caller reads a long one, and what it
//! said when it failed. Host calls (`rho/fs/files`, `rho/git/*`) and a
//! session's checkout (`pull_requests::checkout`) run git this way.

use std::{
    io,
    path::Path,
    process::{ExitStatus, Output, Stdio},
};

use tokio::{
    io::AsyncReadExt as _,
    process::{Child, ChildStderr, ChildStdout, Command},
    task::JoinHandle,
};

use super::GIT_DEADLINE;

/// The `git` arguments that list, each ended by a NUL, the untracked files
/// git doesn't ignore: what `rho/fs/files` lists and `rho/git/diff` diffs.
pub(crate) const UNTRACKED_FILES: [&str; 4] = ["ls-files", "-z", "--others", "--exclude-standard"];

/// Why [`output_within`] has no output for a command.
#[derive(Debug)]
pub(crate) enum NoOutput {
    /// git didn't start, as when it is missing or its folder is gone.
    DidNotStart(io::Error),
    /// git ran past [`GIT_DEADLINE`] and was killed.
    Late,
}

impl NoOutput {
    /// Why, for people, of git run in `folder`.
    pub(crate) fn message(&self, folder: &Path) -> String {
        match self {
            Self::DidNotStart(error) => did_not_start(folder, error),
            Self::Late => format!(
                "git didn't answer within {} s in {}",
                GIT_DEADLINE.as_secs(),
                folder.display()
            ),
        }
    }
}

/// What `command`, git reading local files in `folder`, printed, run to its
/// end within [`GIT_DEADLINE`]. Past it git is killed, as `command` must
/// ask with `kill_on_drop`, and a warning names `folder`, git's arguments
/// and the deadline, whatever the caller makes of no answer.
pub(crate) async fn output_within(
    command: &mut Command,
    folder: &Path,
) -> Result<Output, NoOutput> {
    match tokio::time::timeout(GIT_DEADLINE, command.output()).await {
        Ok(output) => output.map_err(NoOutput::DidNotStart),
        Err(_) => {
            tracing::warn!(
                folder = %folder.display(),
                args = ?command.as_std().get_args().collect::<Vec<_>>(),
                deadline_secs = GIT_DEADLINE.as_secs(),
                "git didn't answer in time, so it was killed"
            );
            Err(NoOutput::Late)
        }
    }
}

/// A git command running with its output piped: the caller reads
/// [`Running::stdout`], while a task of its own reads stderr so git never
/// waits on a full pipe. Dropping it kills git when its command asked
/// `kill_on_drop`, as [`super::host_command`] does.
pub(crate) struct Running {
    child: Child,
    /// What git prints.
    pub(crate) stdout: ChildStdout,
    /// What git said on stderr, up to the bytes kept.
    said: JoinHandle<Vec<u8>>,
}

impl Running {
    /// Starts `command` with its stdout and stderr piped, keeping up to
    /// `keep` bytes of what it says for [`Running::finish`].
    pub(crate) fn start(command: &mut Command, keep: usize) -> io::Result<Self> {
        let mut child = command
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
            return Err(io::Error::other("git's output was not piped"));
        };
        Ok(Self {
            child,
            stdout,
            said: tokio::spawn(drain_stderr(stderr, keep)),
        })
    }

    /// Waits for git to end, once what it printed is read: `Ok` when `ok`
    /// takes how it exited, else why not, for people.
    pub(crate) async fn finish(
        mut self,
        ok: impl FnOnce(&ExitStatus) -> bool,
    ) -> Result<(), String> {
        let status = self
            .child
            .wait()
            .await
            .map_err(|error| format!("Couldn't wait for git: {error}"))?;
        if ok(&status) {
            return Ok(());
        }
        let said = self.said.await.unwrap_or_default();
        Err(git_failure(&said, status))
    }
}

/// Says, for people, that git couldn't start in `folder`.
pub(crate) fn did_not_start(folder: &Path, error: &io::Error) -> String {
    format!("Couldn't run git in {}: {error}", folder.display())
}

/// What git said when it failed: what it printed on stderr, or how it
/// exited when it printed nothing.
pub(crate) fn git_failure(stderr: &[u8], status: ExitStatus) -> String {
    let said = String::from_utf8_lossy(stderr);
    match said.trim() {
        "" => format!("git exited with {status}"),
        said => said.to_owned(),
    }
}

/// The first `keep` bytes a process prints on `stderr`, reading the rest
/// so the process never waits on a full pipe.
async fn drain_stderr(mut stderr: ChildStderr, keep: usize) -> Vec<u8> {
    let mut said = Vec::new();
    let _ = (&mut stderr).take(keep as u64).read_to_end(&mut said).await;
    let _ = tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await;
    said
}