rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho/git/clone`: cloning a repository into a folder, or finding it
//! cloned there already, ported from rho-ui's project picker
//! (`cloning.rs`, its `SCRIPT` and `clone_here`), with git's progress
//! streamed and a stopped or failed clone removed.

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

use rho_protocol::{
    methods::{GitCloneParams, GitCloneResponse, GIT_CLONE, HOST_STREAM_FAILURE_MAX_BYTES},
    Caller, ClientEnvironment, ErrorCode, HostStreamWriter, RpcError,
};
use tokio::{
    io::AsyncReadExt as _,
    process::{Child, Command},
};

#[cfg(unix)]
use super::kill_group;
use super::{
    absolute, blocking, canonical, check_name, failed, git_answer, git_command, host_path,
    log_call, make_root, spawn_stream, toplevel, Machine, PIPE_READ_BYTES,
};
use crate::git::{
    forbid_prompts, git_failure, output_within, SshCommand, SSH_COMMAND_CONFIG, SSH_COMMAND_ENV,
};

/// How a clone ended.
enum Ended {
    Done,
    Failed(String),
    /// The client closed its stream.
    Stopped,
}

/// Answers `rho/git/clone`: makes `folder`, then answers `name` in it at
/// once, taken as it is when it holds a clone of `url` with a commit, or
/// cloned into from a spawned task that streams git's progress. Refuses
/// anything else there before any stream opens.
///
/// A clone that stops or fails is removed, but one the daemon can't stop
/// cleanly may be left partway: a daemon restart ends it with no cleanup,
/// and a stop on Windows kills git but not the helpers it started, which
/// may still hold or write the folder. The next clone into it refuses what
/// it finds: a clone of `url` with no commit yet, as git leaves one
/// stopped while it fetches, with a message telling the user to remove it.
/// A restart before git starts, while the ssh command is read, leaves the
/// empty folder, which reads as holding something else.
pub(super) async fn clone_repo(
    machine: &Machine,
    caller: Caller,
    params: GitCloneParams,
) -> Result<GitCloneResponse, RpcError> {
    let GitCloneParams {
        url, folder, name, ..
    } = params;
    let shown = without_credentials(&url);
    // The host call's line, with what it clones as the span it is in.
    tracing::info_span!("git_clone", url = %shown, folder_name = %name)
        .in_scope(|| log_call(&caller, GIT_CLONE, [&folder]));
    let folder = absolute(&folder)?.to_path_buf();
    check_name(&name)?;
    if url.starts_with('-') {
        return Err(RpcError::new(
            ErrorCode::InvalidParams,
            format!("the URL {shown} starts with '-', which git would take for an option"),
        ));
    }
    let root = blocking(move || make_root(&folder)).await??;
    let dest = root.join(&name);
    let path = host_path(&dest)?;
    let environment = machine.login_environment().await;
    // Made here, before git runs, so a second call finds it taken, and
    // this call knows it is its own to remove when the clone stops or
    // fails. git clones into an empty folder.
    let made = {
        let dest = dest.clone();
        blocking(move || std::fs::create_dir(dest)).await?
    };
    match made {
        Ok(()) => {}
        Err(error) if error.kind() == ErrorKind::AlreadyExists => {
            already_there(&dest, &url, &shown, &environment).await?;
            return Ok(GitCloneResponse::new(path, None));
        }
        Err(error) => return Err(failed(format!("Couldn't make {}: {error}", dest.display()))),
    }
    let ssh = ssh_command(&root, &environment).await;
    let command = clone_command(&root, &environment, ssh, &url, &dest);
    match spawn_stream(&caller, |writer| run_clone(command, dest.clone(), writer)) {
        Ok(progress) => Ok(GitCloneResponse::new(path, Some(progress))),
        Err(error) => {
            // Empty still, so never recursive.
            let _ = tokio::fs::remove_dir(&dest).await;
            Err(error)
        }
    }
}

/// `url` as the daemon logs and shows it: without the user and password
/// a URL may carry, as a token in `https://user:token@host/…`, even when
/// it is not one `url::Url` parses. An scp-like `git@host:path` has no
/// password and is left as it is.
pub(super) fn without_credentials(url: &str) -> String {
    let Ok(mut parsed) = url::Url::parse(url) else {
        return without_userinfo(url);
    };
    if parsed.username().is_empty() && parsed.password().is_none() {
        return url.to_owned();
    }
    // Fail only for a URL with no host, as `url::Url` reads it.
    if parsed.set_password(None).is_err() || parsed.set_username("").is_err() {
        return without_userinfo(url);
    }
    parsed.to_string()
}

/// `url` less what comes between its `://` and its last `@`, for a URL
/// `url::Url` can't read: its password may hold a `/`, so this may drop a
/// path's part too, which only shows less.
fn without_userinfo(url: &str) -> String {
    let Some((scheme, rest)) = url.split_once("://") else {
        return url.to_owned();
    };
    match rest.rfind('@') {
        Some(at) => format!("{scheme}://{}", &rest[at + 1..]),
        None => url.to_owned(),
    }
}

/// Whose ssh command a clone from `folder` runs: the user's when the
/// login's environment or git's configuration sets one. git's default when
/// git can't say, as when it fails or runs past its deadline: the clone
/// then only runs ssh in batch mode.
async fn ssh_command(folder: &Path, environment: &ClientEnvironment) -> SshCommand {
    if environment
        .iter()
        .any(|(name, _)| SSH_COMMAND_ENV.contains(&name))
    {
        return SshCommand::UserConfigured;
    }
    let exit = output_within(
        git_command(folder, environment).args(SSH_COMMAND_CONFIG),
        folder,
    )
    .await
    .ok()
    .and_then(|output| output.status.code());
    SshCommand::from_config_exit(exit).unwrap_or(SshCommand::Default)
}

/// Takes `dest`, which was there before the call, when it holds a clone
/// of `url` with a commit; refuses anything else, a clone with no commit
/// yet included, which is what one under way into it looks like, or one
/// cut short.
async fn already_there(
    dest: &Path,
    url: &str,
    shown: &str,
    environment: &ClientEnvironment,
) -> Result<(), RpcError> {
    let path = dest.display();
    // git running past its deadline is said as such, never read as
    // something to remove.
    if !is_clone_of(dest, url, environment).await.map_err(failed)? {
        return Err(failed(format!("{path} already holds something else.")));
    }
    if git_answer(dest, environment, &["rev-parse", "-q", "--verify", "HEAD"])
        .await
        .map_err(failed)?
        .is_none()
    {
        return Err(failed(format!(
            "{path} holds a clone of {shown} with no commit yet: one is under way, or was cut short; if so, remove it to clone again."
        )));
    }
    Ok(())
}

/// Whether `dest` is the top of a work tree whose `origin` is `url` as
/// configured: not a folder inside another repository, whose `origin`
/// git would read instead.
async fn is_clone_of(
    dest: &Path,
    url: &str,
    environment: &ClientEnvironment,
) -> Result<bool, String> {
    let Some(top) = toplevel(dest, environment).await? else {
        return Ok(false);
    };
    let resolved = {
        let dest = dest.to_path_buf();
        blocking(move || canonical(&dest)).await
    };
    if !matches!(resolved, Ok(Ok(real)) if real == top) {
        return Ok(false);
    }
    Ok(
        git_answer(dest, environment, &["config", "--get", "remote.origin.url"])
            .await?
            .is_some_and(|origin| origin == url),
    )
}

/// `git clone` of `url` into `dest`, run from `root`, never prompting
/// ([`forbid_prompts`]; its own session on Unix also lets a stop kill all
/// it started), and never running the command an `ext::` URL names,
/// whatever the user's configuration allows. Its progress goes to stderr.
fn clone_command(
    root: &Path,
    environment: &ClientEnvironment,
    ssh: SshCommand,
    url: &str,
    dest: &Path,
) -> Command {
    let mut command = git_command(root, environment);
    forbid_prompts(command.as_std_mut(), ssh);
    // It outranks every `protocol.*.allow`, the one below included.
    command.env_remove("GIT_ALLOW_PROTOCOL");
    command
        .args([
            "-c",
            "protocol.ext.allow=never",
            "clone",
            "--progress",
            "--",
        ])
        .arg(url)
        .arg(dest)
        .stdout(Stdio::null())
        .stderr(Stdio::piped());
    command
}

/// Runs a clone into `dest`, which this call made, streaming what git says
/// to `writer`. A clone that stops or fails leaves nothing at `dest`:
/// removed before the stream ends, so a client that asks again on hearing
/// it finds the path free.
async fn run_clone(command: Command, dest: PathBuf, mut writer: HostStreamWriter) {
    let mut ended = clone(command, &mut writer).await;
    if !matches!(ended, Ended::Done) {
        // A known limit: a clone the user started into `dest` from a
        // terminal once git emptied it is removed with it.
        let removed = {
            let dest = dest.clone();
            blocking(move || std::fs::remove_dir_all(dest)).await
        };
        let error = match removed {
            Ok(Ok(())) => None,
            Ok(Err(error)) => Some(error.to_string()),
            Err(error) => Some(error.message),
        };
        if let Some(error) = error {
            tracing::warn!(path = %dest.display(), "couldn't remove a clone that stopped or failed: {error}");
            if let Ended::Failed(message) = &mut ended {
                *message = format!("{message}\nCouldn't remove {}: {error}", dest.display());
            }
        }
    }
    match ended {
        Ended::Done => writer.finish(),
        Ended::Failed(message) => writer.fail(message),
        Ended::Stopped => {}
    }
}

/// Runs `command`, a clone, writing what it says to `writer` as it comes,
/// until it ends or the client closes the stream.
async fn clone(mut command: Command, writer: &mut HostStreamWriter) -> Ended {
    let mut git = match command.spawn() {
        Ok(git) => git,
        Err(error) => return Ended::Failed(format!("Couldn't run git: {error}")),
    };
    let Some(mut stderr) = git.stderr.take() else {
        stop(git).await;
        return Ended::Failed("git's output was not piped".to_owned());
    };
    let mut said = Said::default();
    let mut buffer = vec![0; PIPE_READ_BYTES];
    loop {
        let read = tokio::select! {
            read = stderr.read(&mut buffer) => Some(read),
            () = writer.closed() => None,
        };
        let read = match read {
            None => return stop(git).await,
            Some(Ok(0)) => break,
            Some(Ok(read)) => read,
            Some(Err(error)) => {
                stop(git).await;
                return Ended::Failed(format!("Couldn't read what git said: {error}"));
            }
        };
        said.push(&buffer[..read]);
        if writer.write(buffer[..read].to_vec()).await.is_err() {
            return stop(git).await;
        }
    }
    let status = tokio::select! {
        status = git.wait() => Some(status),
        () = writer.closed() => None,
    };
    match status {
        None => stop(git).await,
        Some(Ok(status)) if status.success() => Ended::Done,
        Some(Ok(status)) => Ended::Failed(said.words(status)),
        Some(Err(error)) => Ended::Failed(format!("Couldn't wait for git: {error}")),
    }
}

/// Stops a clone: kills git and, on Unix, all it started in its session,
/// as a remote helper, ssh and `index-pack`, so nothing writes into the
/// folder once it is removed; then waits for git.
async fn stop(mut git: Child) -> Ended {
    #[cfg(unix)]
    kill_group(git.id());
    let _ = git.start_kill();
    let _ = git.wait().await;
    Ended::Stopped
}

/// The last of what git said, up to what a failed stream carries: its
/// last words when it fails.
#[derive(Default)]
struct Said(Vec<u8>);

impl Said {
    fn push(&mut self, bytes: &[u8]) {
        self.0.extend_from_slice(bytes);
        let over = self.0.len().saturating_sub(HOST_STREAM_FAILURE_MAX_BYTES);
        self.0.drain(..over);
    }

    /// git's last words as a terminal shows them: each line as its last
    /// progress update, after a `\r`, left it.
    fn words(&self, status: ExitStatus) -> String {
        let said = String::from_utf8_lossy(&self.0);
        let shown = said
            .split('\n')
            .filter_map(|line| line.rsplit('\r').find(|part| !part.trim().is_empty()))
            .collect::<Vec<_>>()
            .join("\n");
        git_failure(shown.as_bytes(), status)
    }
}