use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use blyte_agent::approval::{Approval, Approver, LandDetails};
use crate::publish::{output_detail, run_gh, run_git};
use crate::requests::{
check_request_ownership, load_published_record, write_published_record, RequestOwnership,
RequestOwnershipError,
};
use crate::serve::Surface;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullRequestInfo {
pub number: u64,
pub state: String,
pub is_draft: bool,
pub title: String,
pub head_ref_name: String,
pub head_ref_oid: String,
pub base_ref_name: String,
pub mergeable: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckReport {
pub passed: bool,
pub exit_code: Option<i32>,
pub output_tail: String,
pub output_log: PathBuf,
}
pub const CHECK_OUTPUT_TAIL_BYTES: usize = 4000;
const PR_VIEW_JSON_FIELDS: &str =
"number,state,isDraft,title,headRefName,headRefOid,baseRefName,mergeable";
pub fn view_pull_request(root: &Path, url: &str) -> Result<PullRequestInfo, String> {
view_pull_request_with_gh(root, "gh", url)
}
pub fn view_pull_request_with_gh(
root: &Path,
gh: &str,
url: &str,
) -> Result<PullRequestInfo, String> {
let out = run_gh(
root,
OsStr::new(gh),
&["pr", "view", url, "--json", PR_VIEW_JSON_FIELDS],
"gh pr view",
)?;
let value: serde_json::Value = serde_json::from_slice(&out.stdout)
.map_err(|e| format!("gh pr view returned invalid JSON: {e}"))?;
let obj = value
.as_object()
.ok_or_else(|| "gh pr view did not return a JSON object".to_string())?;
Ok(PullRequestInfo {
number: required_u64(obj, "number")?,
state: required_string(obj, "state")?,
is_draft: required_bool(obj, "isDraft")?,
title: required_string(obj, "title")?,
head_ref_name: required_string(obj, "headRefName")?,
head_ref_oid: required_string(obj, "headRefOid")?,
base_ref_name: required_string(obj, "baseRefName")?,
mergeable: required_string(obj, "mergeable")?,
})
}
fn required_u64(
obj: &serde_json::Map<String, serde_json::Value>,
field: &str,
) -> Result<u64, String> {
match obj.get(field) {
None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
Some(v) => v
.as_u64()
.ok_or_else(|| format!("gh pr view returned invalid {field}")),
}
}
fn required_bool(
obj: &serde_json::Map<String, serde_json::Value>,
field: &str,
) -> Result<bool, String> {
match obj.get(field) {
None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
Some(v) => v
.as_bool()
.ok_or_else(|| format!("gh pr view returned invalid {field}")),
}
}
fn required_string(
obj: &serde_json::Map<String, serde_json::Value>,
field: &str,
) -> Result<String, String> {
match obj.get(field) {
None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
Some(v) => v
.as_str()
.map(String::from)
.ok_or_else(|| format!("gh pr view returned invalid {field}")),
}
}
pub fn check_landable(info: &PullRequestInfo, published_commit: &str) -> Result<(), String> {
if info.state != "OPEN" {
return Err(format!(
"pull request #{} is not open (state: {})",
info.number, info.state
));
}
if info.is_draft {
return Err(format!("pull request #{} is a draft", info.number));
}
if info.mergeable == "CONFLICTING" {
return Err(format!(
"pull request #{} conflicts with {}",
info.number, info.base_ref_name
));
}
if info.head_ref_oid != published_commit {
return Err(format!(
"pull request #{} head {} is not the published commit {published_commit}",
info.number, info.head_ref_oid
));
}
Ok(())
}
fn land_worktree_rel_path(number: u64) -> PathBuf {
Path::new(".wt").join(format!("land-{number}"))
}
pub fn land_worktree_path(root: &Path, number: u64) -> PathBuf {
root.join(land_worktree_rel_path(number))
}
pub fn land_check_log_path(root: &Path, number: u64) -> PathBuf {
root.join(".wt").join(format!("land-{number}.check.log"))
}
pub fn expand_check_command(command: &str, number: u64) -> String {
command.replace("{pr}", &number.to_string())
}
pub fn run_land_check(
root: &Path,
command: &str,
number: u64,
commit: &str,
) -> Result<CheckReport, String> {
let wt_rel = land_worktree_rel_path(number);
let wt_path = root.join(&wt_rel);
if wt_path.exists() || wt_path.symlink_metadata().is_ok() {
let display = wt_path.display();
return Err(format!(
"{display} already exists: another landing check is running, or one was interrupted; remove it with git worktree remove --force {display}"
));
}
let add_out = Command::new("git")
.args(["worktree", "add", "--detach"])
.arg(&wt_rel)
.arg(commit)
.current_dir(root)
.env("GIT_TERMINAL_PROMPT", "0")
.output()
.map_err(|e| format!("failed to run git worktree add: {e}"))?;
if !add_out.status.success() {
let detail = output_detail(&add_out);
return Err(format!("git worktree add failed: {detail}"));
}
let expanded = expand_check_command(command, number);
let output_log = land_check_log_path(root, number);
let check_res = execute_check(&wt_path, &expanded, output_log);
let remove_res = remove_land_worktree(root, &wt_rel, &wt_path);
match (check_res, remove_res) {
(Ok(report), Ok(())) => Ok(report),
(Ok(_), Err(remove_err)) => Err(remove_err),
(Err(check_err), Ok(())) => Err(check_err),
(Err(check_err), Err(remove_err)) => Err(format!("{check_err}; {remove_err}")),
}
}
fn execute_check(
wt_path: &Path,
expanded: &str,
output_log: PathBuf,
) -> Result<CheckReport, String> {
let (mut reader, writer) =
std::io::pipe().map_err(|e| format!("could not run the land check: {e}"))?;
let writer_err = writer
.try_clone()
.map_err(|e| format!("could not run the land check: {e}"))?;
let mut command = Command::new("sh");
command
.args(["-c", expanded])
.current_dir(wt_path)
.stdin(Stdio::null())
.stdout(Stdio::from(writer))
.stderr(Stdio::from(writer_err));
blyte_agent::shell::scrub_harness(&mut command);
let mut child = command
.spawn()
.map_err(|e| format!("could not run the land check: {e}"))?;
drop(command);
let mut output_bytes = Vec::new();
let read_res = reader.read_to_end(&mut output_bytes);
let status = child
.wait()
.map_err(|e| format!("could not run the land check: {e}"))?;
read_res.map_err(|e| format!("could not run the land check: {e}"))?;
if let Some(parent) = output_log.parent() {
std::fs::create_dir_all(parent).map_err(|e| {
format!(
"could not write the land check output to {}: {e}",
output_log.display()
)
})?;
}
std::fs::write(&output_log, &output_bytes).map_err(|e| {
format!(
"could not write the land check output to {}: {e}",
output_log.display()
)
})?;
let exit_code = status.code();
let passed = exit_code == Some(0);
let output_tail = tail_utf8(&output_bytes, CHECK_OUTPUT_TAIL_BYTES);
Ok(CheckReport {
passed,
exit_code,
output_tail,
output_log,
})
}
fn remove_land_worktree(root: &Path, wt_rel: &Path, wt_path: &Path) -> Result<(), String> {
let out = Command::new("git")
.args(["worktree", "remove", "--force"])
.arg(wt_rel)
.current_dir(root)
.env("GIT_TERMINAL_PROMPT", "0")
.output()
.map_err(|e| format!("failed to remove worktree {}: {e}", wt_path.display()))?;
if !out.status.success() {
let detail = output_detail(&out);
return Err(format!(
"failed to remove worktree {}: {detail}",
wt_path.display()
));
}
Ok(())
}
fn tail_utf8(bytes: &[u8], max_bytes: usize) -> String {
let text = String::from_utf8_lossy(bytes);
if text.len() <= max_bytes {
return text.into_owned();
}
let mut start = text.len() - max_bytes;
while !text.is_char_boundary(start) {
start += 1;
}
text[start..].to_string()
}
pub fn merge_pull_request(root: &Path, url: &str, commit: &str) -> Result<(), String> {
merge_pull_request_with_gh(root, "gh", url, commit)
}
pub fn merge_pull_request_with_gh(
root: &Path,
gh: &str,
url: &str,
commit: &str,
) -> Result<(), String> {
run_gh(
root,
OsStr::new(gh),
&[
"pr",
"merge",
url,
"--squash",
"--match-head-commit",
commit,
],
"gh pr merge",
)?;
Ok(())
}
pub fn update_default_branch(root: &Path, base: &str) -> Result<String, String> {
let fetch = run_git(root, &["fetch", "--quiet", "origin", base])?;
if !fetch.status.success() {
let detail = output_detail(&fetch);
return Err(format!("git fetch origin {base} failed: {detail}"));
}
let head = run_git(root, &["rev-parse", "--abbrev-ref", "HEAD"])?;
if !head.status.success() {
let detail = output_detail(&head);
return Err(format!(
"could not read current branch in {}: {detail}",
root.display()
));
}
let branch = String::from_utf8_lossy(&head.stdout).trim().to_string();
if branch != base {
return Ok(format!(
"fetched origin/{base}; {} is on {branch}, left as it was",
root.display()
));
}
let status = run_git(root, &["status", "--porcelain"])?;
if !status.status.success() {
let detail = output_detail(&status);
return Err(format!(
"could not read git status in {}: {detail}",
root.display()
));
}
if !String::from_utf8_lossy(&status.stdout).trim().is_empty() {
return Ok(format!(
"fetched origin/{base}; {} has uncommitted changes, left as it was",
root.display()
));
}
let remote_ref = format!("origin/{base}");
let merge = run_git(root, &["merge", "--ff-only", &remote_ref])?;
if !merge.status.success() {
let detail = output_detail(&merge);
return Err(format!("git merge --ff-only {remote_ref} failed: {detail}"));
}
Ok(format!(
"fetched origin/{base} and fast-forwarded {base} in {}",
root.display()
))
}
pub trait Lander: Send + Sync {
fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String>;
fn check(
&self,
root: &Path,
command: &str,
number: u64,
commit: &str,
) -> Result<CheckReport, String>;
fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String>;
fn update(&self, root: &Path, base: &str) -> Result<String, String>;
}
pub struct RealLander;
impl Lander for RealLander {
fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String> {
view_pull_request(root, url)
}
fn check(
&self,
root: &Path,
command: &str,
number: u64,
commit: &str,
) -> Result<CheckReport, String> {
run_land_check(root, command, number, commit)
}
fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String> {
merge_pull_request(root, url, commit)
}
fn update(&self, root: &Path, base: &str) -> Result<String, String> {
update_default_branch(root, base)
}
}
pub struct SurfaceLandTool {
surface: Arc<Surface>,
approver: Arc<dyn Approver>,
lander: Arc<dyn Lander>,
}
impl SurfaceLandTool {
pub fn new(surface: Arc<Surface>) -> Self {
let approver: Arc<dyn Approver> = surface.session.approver();
Self {
surface,
approver,
lander: Arc::new(RealLander),
}
}
pub fn with_lander(
surface: Arc<Surface>,
approver: Arc<dyn Approver>,
lander: Arc<dyn Lander>,
) -> Self {
Self {
surface,
approver,
lander,
}
}
}
impl blyte_agent::tools::LandTool for SurfaceLandTool {
fn land(&self, request: &str) -> Result<String, String> {
land_request(
&self.surface,
self.approver.as_ref(),
self.lander.as_ref(),
request,
)
}
}
pub fn land_request(
surface: &Surface,
approver: &dyn Approver,
lander: &dyn Lander,
request: &str,
) -> Result<String, String> {
if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
return Err(format!(
"cannot land during a turn started by another surface ({started_by})"
));
}
crate::dispatch::validate_request_id(request)?;
match check_request_ownership(surface, request) {
Ok(RequestOwnership::Owned) => {}
Ok(RequestOwnership::OtherSurface) => {
return Err(format!("request {request} belongs to another surface"));
}
Ok(RequestOwnership::Unowned) => {
return Err(format!("request {request} was not started by this surface"));
}
Ok(RequestOwnership::NotFound) => {
return Err(format!("unknown request {request}"));
}
Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
return Err(msg);
}
}
let mut published = load_published_record(&surface.root, request)?;
let (Some(url), Some(pushed_commit)) = (
published.pull_request_url.clone(),
published.pushed_commit.clone(),
) else {
return Err(format!(
"request {request} has no pull request: publish it first"
));
};
if published.landed_head.is_some() {
return Err(format!("request {request} is already landed ({url})"));
}
let land_check = match crate::config::load_with_fallback(&surface.root)? {
Some((cfg, _)) => match cfg.surface.land_check {
Some(cmd) => cmd,
None => {
return Err(
"no landing check is set: add land_check to [surface] in blyte.toml, the command that must pass before a merge ({pr} is replaced by the pull request number)"
.to_string(),
);
}
},
None => {
return Err(
"no landing check is set: add land_check to [surface] in blyte.toml, the command that must pass before a merge ({pr} is replaced by the pull request number)"
.to_string(),
);
}
};
let _in_flight = surface
.requests
.try_begin_publish(request)
.ok_or_else(|| format!("request {request} is already being published or landed"))?;
let info = lander.view(&surface.root, &url)?;
check_landable(&info, &pushed_commit)?;
let expanded = expand_check_command(&land_check, info.number);
let report = lander.check(&surface.root, &land_check, info.number, &pushed_commit)?;
if !report.passed {
let code = match report.exit_code {
Some(c) => c.to_string(),
None => "signal".to_string(),
};
return Err(format!(
"the landing check failed (exit {code}): {expanded}\nfull output: {}\n{}",
report.output_log.display(),
report.output_tail
));
}
let details = LandDetails {
request: request.to_string(),
pull_request_url: url.clone(),
number: info.number,
title: info.title.clone(),
branch: info.head_ref_name.clone(),
base: info.base_ref_name.clone(),
commit: pushed_commit.clone(),
check_command: expanded,
};
match approver.ask_land(&details) {
Approval::Approved => {}
Approval::Denied => {
return Err("the user declined".to_string());
}
Approval::Unavailable => {
return Err("merge approval is not available here".to_string());
}
}
lander.merge(&surface.root, &url, &pushed_commit)?;
published.landed_head = Some(pushed_commit.clone());
write_published_record(&surface.root, request, &published)?;
let notice = format!(
"Merged pull request #{} ({url}) into {} at {pushed_commit}",
info.number, info.base_ref_name
);
if let Err(e) = surface
.session
.record_decision(request, "land", Some(¬ice), None)
{
surface.session.record_error(&format!(
"failed to record land decision for {request}: {e}"
));
}
let update_line = match lander.update(&surface.root, &info.base_ref_name) {
Ok(msg) => msg,
Err(err) => format!("could not update {}: {err}", surface.root.display()),
};
Ok(format!("{notice}\n{update_line}"))
}