rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho/forge/pull_request/act`: commenting on, marking ready or draft, or
//! merging a pull request with `gh pr`, by its repository and in no
//! checkout, ported from rho-ui's `forge/gh_actions.rs` (its
//! `ACTION_SCRIPT` and `action_here`).

use rho_protocol::{
    methods::{
        ForgePullRequestActParams, ForgePullRequestActResponse, ForgePullRequestAction,
        PullRequestMergeMethod, FORGE_PULL_REQUEST_ACT,
    },
    Caller, ErrorCode, RpcError,
};

use super::{
    absolute, failed, gh_command, log_call, supervised_output, supervised_output_with_input,
    within_deadline, Machine,
};
use crate::app::pull_requests::gh_failure;

/// Answers `rho/forge/pull_request/act`: runs `gh pr` on the pull request
/// with `--repo`, so it reads no checkout. Refuses an action or merge
/// method this daemon doesn't know, or a head that isn't a whole commit id,
/// before `gh` runs. When `gh` fails, the call fails with the first line it
/// said.
pub(super) async fn act(
    machine: &Machine,
    caller: Caller,
    params: ForgePullRequestActParams,
) -> Result<ForgePullRequestActResponse, RpcError> {
    let ForgePullRequestActParams {
        gh,
        pull_request,
        action,
        ..
    } = params;
    let repo = format!(
        "{}/{}/{}",
        pull_request.host, pull_request.owner, pull_request.name
    );
    // The pull request and what is done to it, never a comment's text.
    let shown = format!("{}/{pull_request}", pull_request.host);
    tracing::info_span!("forge_act", pull_request = %shown, action = kind(&action))
        .in_scope(|| log_call(&caller, FORGE_PULL_REQUEST_ACT, [&gh]));
    let Pr {
        verb,
        options,
        input,
    } = pr(action)?;
    let gh = absolute(&gh)?;
    within_deadline(async {
        let environment = machine.login_environment().await;
        let mut command = gh_command(gh, &environment);
        command
            .args(["pr", verb])
            .arg(pull_request.number.to_string())
            .arg(format!("--repo={repo}"))
            .args(options);
        let output = match input {
            Some(input) => supervised_output_with_input(&mut command, input).await,
            None => supervised_output(&mut command).await,
        };
        let output =
            output.map_err(|error| failed(format!("Couldn't run {}: {error}", gh.display())))?;
        if output.status.success() {
            Ok(ForgePullRequestActResponse::default())
        } else {
            Err(failed(gh_failure(&output.stderr, output.status)))
        }
    })
    .await
}

/// What `action` is, for the log.
fn kind(action: &ForgePullRequestAction) -> &'static str {
    match action {
        ForgePullRequestAction::Comment { .. } => "comment",
        ForgePullRequestAction::Ready => "ready",
        ForgePullRequestAction::Draft => "draft",
        ForgePullRequestAction::Merge { .. } => "merge",
        _ => "unknown",
    }
}

/// The `gh pr` command that does an action.
struct Pr {
    verb: &'static str,
    /// After the pull request and its repository. Each value is given after
    /// `=`, so one that starts with `-` is never read as an option.
    options: Vec<String>,
    /// What `gh` reads on its standard input, which is otherwise empty.
    input: Option<Vec<u8>>,
}

/// The `gh pr` command that does `action`. A comment's text goes on `gh`'s
/// standard input (`--body-file=-`), never in an argument: Linux refuses
/// one over 128 KiB (`MAX_ARG_STRLEN`, execve(2)), and GitHub takes
/// comments of up to 65,536 characters, up to 256 KiB of UTF-8. A merge
/// passes `--match-head-commit`, so a head the person hasn't seen is never
/// merged, and never `--delete-branch`: a session may still work on the
/// branch.
fn pr(action: ForgePullRequestAction) -> Result<Pr, RpcError> {
    let (verb, options, input) = match action {
        ForgePullRequestAction::Comment { body } => (
            "comment",
            vec!["--body-file=-".to_owned()],
            Some(body.into_bytes()),
        ),
        ForgePullRequestAction::Ready => ("ready", Vec::new(), None),
        ForgePullRequestAction::Draft => ("ready", vec!["--undo".to_owned()], None),
        ForgePullRequestAction::Merge { method, head_oid } => {
            let method = match method {
                PullRequestMergeMethod::Merge => "--merge",
                PullRequestMergeMethod::Squash => "--squash",
                PullRequestMergeMethod::Rebase => "--rebase",
                _ => return Err(unknown("merge method")),
            };
            whole_commit(&head_oid)?;
            let options = vec![method.to_owned(), format!("--match-head-commit={head_oid}")];
            ("merge", options, None)
        }
        _ => return Err(unknown("action")),
    };
    Ok(Pr {
        verb,
        options,
        input,
    })
}

/// Refuses a `head_oid` that isn't a whole commit id: 40 hex digits in a
/// SHA-1 repository or 64 in a SHA-256 one, git's two object formats.
fn whole_commit(head_oid: &str) -> Result<(), RpcError> {
    let hex = head_oid.bytes().all(|byte| byte.is_ascii_hexdigit());
    if hex && matches!(head_oid.len(), 40 | 64) {
        return Ok(());
    }
    let digits = if hex {
        "hex digits"
    } else {
        "characters, not all hex"
    };
    Err(RpcError::new(
        ErrorCode::InvalidParams,
        format!(
            "head_oid isn't a whole commit id, 40 hex digits (SHA-1) or 64 (SHA-256): it has {} {digits}.",
            head_oid.chars().count()
        ),
    ))
}

/// Refuses a `what` this daemon doesn't know, as one a newer client names.
fn unknown(what: &str) -> RpcError {
    RpcError::new(
        ErrorCode::InvalidParams,
        format!("This daemon doesn't know that {what}."),
    )
}