rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What the tests of the host calls on this machine share.

use std::{num::NonZeroU32, path::Path, process::Command};

use base64::Engine as _;
use rho_protocol::{
    methods::{HostPath, HostStreamEnd, HostStreamId, HostStreamReadParams},
    Caller, ClientInfo, ConnectionId,
};

use super::{machine::Machine, machine_fs::canonical};

pub(super) fn caller() -> Caller {
    caller_on(1)
}

/// The caller of a call on the connection numbered `connection`.
pub(super) fn caller_on(connection: u64) -> Caller {
    Caller::new(
        ConnectionId::new(connection),
        ClientInfo {
            name: "test".to_owned(),
            version: "0".to_owned(),
        },
    )
}

pub(super) fn machine() -> Machine {
    Machine::without_login(Path::new("/nonexistent/.rho"))
}

/// A machine whose calls run with `variables` alone as the login's
/// environment, not the test process's, so the programs they find on its
/// `PATH` are the test's.
pub(super) fn machine_in(variables: &[(&str, &str)]) -> Machine {
    let environment = variables
        .iter()
        .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
        .collect();
    Machine::with_environment(Path::new("/nonexistent/.rho"), environment)
}

pub(super) fn host(path: &Path) -> HostPath {
    HostPath::new(path.to_str().unwrap())
}

/// `path` resolved, as the calls answer it.
pub(super) fn real(path: &Path) -> HostPath {
    host(&canonical(path).unwrap())
}

/// Runs git in `dir`, as [`git_command`] makes it, answering what it
/// printed, trimmed.
pub(super) fn git(dir: &Path, args: &[&str]) -> String {
    let output = git_command(dir, args).output().unwrap();
    assert!(
        output.status.success(),
        "git {args:?} failed in {}: {}",
        dir.display(),
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).unwrap().trim().to_owned()
}

/// git in `dir` with `args`, as a user with a name and no signing, and
/// none of the developer's own configuration, global or system.
pub(super) fn git_command(dir: &Path, args: &[&str]) -> Command {
    let mut command = Command::new("git");
    for name in crate::git::LOCATION_ENV {
        command.env_remove(name);
    }
    command
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .args([
            "-c",
            "user.name=rho",
            "-c",
            "user.email=rho@example.com",
            "-c",
            "commit.gpgsign=false",
        ])
        .args(args)
        .current_dir(dir);
    command
}

/// A repository at `dir` on branch `main`, committing `files` (path,
/// contents).
pub(super) fn repository(dir: &Path, files: &[(&str, &str)]) {
    std::fs::create_dir_all(dir).unwrap();
    git(dir, &["init", "-q"]);
    git(dir, &["symbolic-ref", "HEAD", "refs/heads/main"]);
    for (path, contents) in files {
        let path = dir.join(path);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, contents).unwrap();
    }
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-q", "-m", "files"]);
}

/// Everything `stream` carries, and how it ended.
pub(super) async fn read_out(caller: &Caller, stream: HostStreamId) -> (Vec<u8>, HostStreamEnd) {
    let mut bytes = Vec::new();
    loop {
        let read = caller
            .read_stream(HostStreamReadParams::new(
                stream.clone(),
                bytes.len() as u64,
                NonZeroU32::new(1 << 20).unwrap(),
            ))
            .await
            .unwrap();
        bytes.extend(
            base64::engine::general_purpose::STANDARD
                .decode(read.data)
                .unwrap(),
        );
        if let Some(end) = read.end {
            return (bytes, end);
        }
    }
}