rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The `rho/git/*` host calls on the daemon's machine (`docs/protocol.md`,
//! "Git on the daemon's machine"): rho-ui's reading of repositories and
//! cloning of one, which it ran over ssh as shell scripts, ported from
//! those scripts and the Rust twins it ran on its own machine. Each call
//! runs `git` with the login environment, never letting it prompt, and is
//! logged with the folders it names, a clone's URL without its
//! credentials; never an origin's URL or what git said.
//!
//! This module answers the calls, reading repositories for `repos` itself:
//! from their `.git` files (`dot_git`), and with git only where those could
//! answer otherwise. `diff` and `clone` do the rest.

use std::{
    fs::Metadata,
    path::{Component, Path, PathBuf},
    process::Output,
};

use futures_util::{stream, StreamExt as _};
use rho_protocol::{
    methods::{
        GitCloneParams, GitCloneResponse, GitDiff, GitDiffParams, GitFolder, GitHead, GitIcon,
        GitRepo, GitReposParams, GitReposResponse, HostPath, GIT_REPOS,
    },
    Caller, ClientEnvironment, GitService, RpcError,
};

#[cfg(unix)]
use super::machine::kill_group;
use super::{
    machine::{
        absolute, blocking, failed, host_path, log_call, log_call_counted, spawn_stream, Machine,
    },
    machine_fs::{canonical, check_name, make_root, modified_ns, project_root},
};
use crate::git::{host_command as git_command, output_within, NoOutput};

mod clone;
mod diff;
mod dot_git;

/// The most folders `repos` asks git about at once.
//
// As `pull_requests::checkout::RESOLVES_AT_ONCE`: at most 8 git processes
// run. A folder `dot_git` cannot read runs 3 to 4 git calls, one after
// another (`rev-parse --show-toplevel`, `symbolic-ref`, `rev-parse HEAD` for
// a detached one, `config`): a sidebar of 30 repositories answered in 173 ms
// (median of 7; 160 to 181 ms) through the daemon on a 24-core Linux
// machine (2026-12-03), all through git. Chosen; a longer list only takes
// longer.
const REPOS_AT_ONCE: usize = 8;

/// The most bytes one read takes from git's output.
//
// Linux's default pipe capacity (64 KiB, pipe(7)): one read takes all that
// git could write before it waited.
const PIPE_READ_BYTES: usize = 64 << 10;

impl GitService for Machine {
    async fn repos(
        &self,
        caller: Caller,
        params: GitReposParams,
    ) -> Result<GitReposResponse, RpcError> {
        let GitReposParams {
            folders,
            icon_candidates,
            ..
        } = params;
        log_call_counted(&caller, GIT_REPOS, &folders);
        for folder in &folders {
            absolute(folder)?;
        }
        let environment = self.login_environment().await;
        let files = dot_git::Files::for_environment(&environment);
        let (environment, candidates) = (&environment, icon_candidates.as_slice());
        let folders = stream::iter(folders)
            .map(move |folder| look_at(folder, environment, files, candidates))
            .buffered(REPOS_AT_ONCE)
            .collect::<Vec<_>>()
            .await
            .into_iter()
            .collect::<Result<_, _>>()?;
        Ok(GitReposResponse::new(folders))
    }

    /// Answered in `diff.rs`.
    async fn diff(&self, caller: Caller, params: GitDiffParams) -> Result<GitDiff, RpcError> {
        diff::diff(self, caller, params).await
    }

    /// Answered in `clone.rs`.
    async fn clone_repo(
        &self,
        caller: Caller,
        params: GitCloneParams,
    ) -> Result<GitCloneResponse, RpcError> {
        clone::clone_repo(self, caller, params).await
    }
}

/// What git prints for `args` in `folder`, less its newline, when it
/// succeeds within [`crate::git::GIT_DEADLINE`] and prints UTF-8; `None`
/// when it fails, is missing, runs past the deadline, or `folder` is gone,
/// so a repository git doesn't answer for in time reads as none, as the
/// sidebar `repos` answers would rather show.
async fn git_line(folder: &Path, environment: &ClientEnvironment, args: &[&str]) -> Option<String> {
    git_answer(folder, environment, args).await.ok().flatten()
}

/// [`git_line`], with git running past its deadline an error saying so: for
/// a call that would otherwise answer or advise wrongly, as "not a
/// repository" or "remove it".
async fn git_answer(
    folder: &Path,
    environment: &ClientEnvironment,
    args: &[&str],
) -> Result<Option<String>, String> {
    let output = match output_within(git_command(folder, environment).args(args), folder).await {
        Ok(output) => output,
        Err(late @ NoOutput::Late) => return Err(late.message(folder)),
        Err(NoOutput::DidNotStart(_)) => return Ok(None),
    };
    Ok(line_of(output))
}

/// The line git printed, when it succeeded and printed UTF-8.
fn line_of(output: Output) -> Option<String> {
    if !output.status.success() {
        return None;
    }
    let mut line = String::from_utf8(output.stdout).ok()?;
    if line.ends_with('\n') {
        line.pop();
    }
    Some(line)
}

/// The top of the work tree `folder` is in, its symlinks resolved, as git
/// decides it, `safe.directory` included; `None` outside one, in a bare
/// repository, when git is missing or names a path that is not UTF-8, or
/// when that path can't be resolved, as when it is gone since. An error
/// when git runs past its deadline ([`git_answer`]).
async fn toplevel(
    folder: &Path,
    environment: &ClientEnvironment,
) -> Result<Option<PathBuf>, String> {
    let Some(top) = git_answer(folder, environment, &["rev-parse", "--show-toplevel"]).await?
    else {
        return Ok(None);
    };
    let top = PathBuf::from(top);
    // Git for Windows prints `C:/x/y`: resolved, it is spelled as
    // `rho/fs/look` spells it.
    Ok(blocking(move || canonical(&top).ok()).await.ok().flatten())
}

/// Where a folder `repos` answers is, by its project.
enum Place {
    /// In a work tree whose project can travel: git reads the repository.
    Repo(HostPath),
    /// In none, or in one whose project is not UTF-8: the folder resolved,
    /// or as asked when it can't be.
    Outside(HostPath),
}

/// Who names what a repository holds, for `look_at`.
enum Reader {
    /// Its `.git` files did, as git would.
    Files(GitRepo),
    /// Git does.
    Git,
}

/// What `repos` answers for `folder`, which is absolute: where it is
/// first, then, only in a repository, what it holds; each read by `files`
/// when there are some, or by git where those could answer otherwise.
async fn look_at(
    folder: HostPath,
    environment: &ClientEnvironment,
    files: Option<dot_git::Files>,
    candidates: &[String],
) -> Result<GitFolder, RpcError> {
    let path = PathBuf::from(folder.as_str());
    let read = match files {
        Some(files) => {
            let path = path.clone();
            blocking(move || files.read(&path)).await?
        }
        None => Err(dot_git::AskGit),
    };
    let (top, reader) = match read {
        Ok(Some(dot_git::Checkout { top, repo })) => (Some(top), Reader::Files(repo)),
        // No top: outside a repository, where nothing is read.
        Ok(None) => (None, Reader::Git),
        Err(dot_git::AskGit) => (
            toplevel(&path, environment).await.ok().flatten(),
            Reader::Git,
        ),
    };
    let candidates = candidates.to_vec();
    let (place, icon) = blocking(move || place(folder, top, &candidates)).await?;
    let (repo, project) = match place {
        Place::Repo(project) => {
            let repo = match reader {
                Reader::Files(repo) => repo,
                Reader::Git => read_repo(&path, environment).await,
            };
            (Some(repo), project)
        }
        Place::Outside(project) => (None, project),
    };
    Ok(GitFolder::new(repo, project, icon))
}

/// Where `folder`, in the work tree whose top is `top` if any, is, and the
/// first of `candidates` in its project. A repository whose project is not
/// UTF-8 cannot travel, so it answers as one git cannot read.
fn place(
    folder: HostPath,
    top: Option<PathBuf>,
    candidates: &[String],
) -> (Place, Option<GitIcon>) {
    let path = PathBuf::from(folder.as_str());
    let in_repo = top
        .map(|top| project_root(&top))
        .and_then(|root| Some((host_path(&root).ok()?, root)));
    let (place, root) = match in_repo {
        Some((project, root)) => (Place::Repo(project), root),
        None => {
            let resolved = canonical(&path)
                .ok()
                .and_then(|real| Some((host_path(&real).ok()?, real)));
            match resolved {
                Some((project, real)) => (Place::Outside(project), real),
                None => (Place::Outside(folder), path),
            }
        }
    };
    let icon = icon(&root, candidates);
    (place, icon)
}

/// What the repository `folder` is in names: `HEAD`'s branch, unborn ones
/// included, or else its commit, and `origin`'s URL as configured, which
/// `config --get` prints without `insteadOf` rewrites.
async fn read_repo(folder: &Path, environment: &ClientEnvironment) -> GitRepo {
    let head = match git_line(folder, environment, &["symbolic-ref", "-q", "HEAD"]).await {
        Some(reference) => Some(GitHead::Branch { reference }),
        None => git_line(
            folder,
            environment,
            &["rev-parse", "-q", "--verify", "HEAD"],
        )
        .await
        .map(|commit| GitHead::Detached { commit }),
    };
    let origin_url = git_line(
        folder,
        environment,
        &["config", "--get", "remote.origin.url"],
    )
    .await;
    GitRepo::new(head, origin_url)
}

/// The first of `candidates` that is a file in `project` through any
/// symlink, with the size and stamp `rho/fs/read` answers for it. The file
/// is never read: a client reads it with `rho/fs/read` when the stamp is
/// new to it.
fn icon(project: &Path, candidates: &[String]) -> Option<GitIcon> {
    candidates.iter().find_map(|candidate| {
        let path = project.join(within(candidate)?);
        let metadata = std::fs::metadata(path).ok().filter(Metadata::is_file)?;
        Some(GitIcon::new(
            candidate.clone(),
            metadata.len(),
            modified_ns(&metadata),
        ))
    })
}

/// `candidate`, `/`-joined, as a path within a folder: `None` for one
/// that is empty, absolute, or has a `.` or `..` part, which could name a
/// file outside the project.
fn within(candidate: &str) -> Option<PathBuf> {
    candidate
        .split('/')
        .map(|part| {
            let mut components = Path::new(part).components();
            matches!(
                (components.next(), components.next()),
                (Some(Component::Normal(_)), None)
            )
            .then_some(part)
        })
        .collect()
}

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