Skip to main content

blyte_cli/
land.rs

1use std::ffi::OsStr;
2use std::io::Read;
3use std::path::{Path, PathBuf};
4use std::process::{Command, Stdio};
5use std::sync::Arc;
6
7use blyte_agent::approval::{Approval, Approver, LandDetails};
8
9use crate::publish::{output_detail, run_gh, run_git};
10use crate::requests::{
11    check_request_ownership, load_published_record, write_published_record, RequestOwnership,
12    RequestOwnershipError,
13};
14use crate::serve::Surface;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct PullRequestInfo {
18    pub number: u64,
19    pub state: String,
20    pub is_draft: bool,
21    pub title: String,
22    pub head_ref_name: String,
23    pub head_ref_oid: String,
24    pub base_ref_name: String,
25    pub mergeable: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct CheckReport {
30    pub passed: bool,
31    pub exit_code: Option<i32>,
32    pub output_tail: String,
33    pub output_log: PathBuf,
34}
35
36pub const CHECK_OUTPUT_TAIL_BYTES: usize = 4000;
37
38const PR_VIEW_JSON_FIELDS: &str =
39    "number,state,isDraft,title,headRefName,headRefOid,baseRefName,mergeable";
40
41pub fn view_pull_request(root: &Path, url: &str) -> Result<PullRequestInfo, String> {
42    view_pull_request_with_gh(root, "gh", url)
43}
44
45pub fn view_pull_request_with_gh(
46    root: &Path,
47    gh: &str,
48    url: &str,
49) -> Result<PullRequestInfo, String> {
50    let out = run_gh(
51        root,
52        OsStr::new(gh),
53        &["pr", "view", url, "--json", PR_VIEW_JSON_FIELDS],
54        "gh pr view",
55    )?;
56
57    let value: serde_json::Value = serde_json::from_slice(&out.stdout)
58        .map_err(|e| format!("gh pr view returned invalid JSON: {e}"))?;
59    let obj = value
60        .as_object()
61        .ok_or_else(|| "gh pr view did not return a JSON object".to_string())?;
62
63    Ok(PullRequestInfo {
64        number: required_u64(obj, "number")?,
65        state: required_string(obj, "state")?,
66        is_draft: required_bool(obj, "isDraft")?,
67        title: required_string(obj, "title")?,
68        head_ref_name: required_string(obj, "headRefName")?,
69        head_ref_oid: required_string(obj, "headRefOid")?,
70        base_ref_name: required_string(obj, "baseRefName")?,
71        mergeable: required_string(obj, "mergeable")?,
72    })
73}
74
75fn required_u64(
76    obj: &serde_json::Map<String, serde_json::Value>,
77    field: &str,
78) -> Result<u64, String> {
79    match obj.get(field) {
80        None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
81        Some(v) => v
82            .as_u64()
83            .ok_or_else(|| format!("gh pr view returned invalid {field}")),
84    }
85}
86
87fn required_bool(
88    obj: &serde_json::Map<String, serde_json::Value>,
89    field: &str,
90) -> Result<bool, String> {
91    match obj.get(field) {
92        None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
93        Some(v) => v
94            .as_bool()
95            .ok_or_else(|| format!("gh pr view returned invalid {field}")),
96    }
97}
98
99fn required_string(
100    obj: &serde_json::Map<String, serde_json::Value>,
101    field: &str,
102) -> Result<String, String> {
103    match obj.get(field) {
104        None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
105        Some(v) => v
106            .as_str()
107            .map(String::from)
108            .ok_or_else(|| format!("gh pr view returned invalid {field}")),
109    }
110}
111
112pub fn check_landable(info: &PullRequestInfo, published_commit: &str) -> Result<(), String> {
113    if info.state != "OPEN" {
114        return Err(format!(
115            "pull request #{} is not open (state: {})",
116            info.number, info.state
117        ));
118    }
119    if info.is_draft {
120        return Err(format!("pull request #{} is a draft", info.number));
121    }
122    if info.mergeable == "CONFLICTING" {
123        return Err(format!(
124            "pull request #{} conflicts with {}",
125            info.number, info.base_ref_name
126        ));
127    }
128    if info.head_ref_oid != published_commit {
129        return Err(format!(
130            "pull request #{} head {} is not the published commit {published_commit}",
131            info.number, info.head_ref_oid
132        ));
133    }
134    Ok(())
135}
136
137fn land_worktree_rel_path(number: u64) -> PathBuf {
138    Path::new(".wt").join(format!("land-{number}"))
139}
140
141pub fn land_worktree_path(root: &Path, number: u64) -> PathBuf {
142    root.join(land_worktree_rel_path(number))
143}
144
145pub fn land_check_log_path(root: &Path, number: u64) -> PathBuf {
146    root.join(".wt").join(format!("land-{number}.check.log"))
147}
148
149pub fn expand_check_command(command: &str, number: u64) -> String {
150    command.replace("{pr}", &number.to_string())
151}
152
153pub fn run_land_check(
154    root: &Path,
155    command: &str,
156    number: u64,
157    commit: &str,
158) -> Result<CheckReport, String> {
159    let wt_rel = land_worktree_rel_path(number);
160    let wt_path = root.join(&wt_rel);
161    if wt_path.exists() || wt_path.symlink_metadata().is_ok() {
162        let display = wt_path.display();
163        return Err(format!(
164            "{display} already exists: another landing check is running, or one was interrupted; remove it with git worktree remove --force {display}"
165        ));
166    }
167
168    let add_out = Command::new("git")
169        .args(["worktree", "add", "--detach"])
170        .arg(&wt_rel)
171        .arg(commit)
172        .current_dir(root)
173        .env("GIT_TERMINAL_PROMPT", "0")
174        .output()
175        .map_err(|e| format!("failed to run git worktree add: {e}"))?;
176    if !add_out.status.success() {
177        let detail = output_detail(&add_out);
178        return Err(format!("git worktree add failed: {detail}"));
179    }
180
181    let expanded = expand_check_command(command, number);
182    let output_log = land_check_log_path(root, number);
183    let check_res = execute_check(&wt_path, &expanded, output_log);
184    let remove_res = remove_land_worktree(root, &wt_rel, &wt_path);
185    match (check_res, remove_res) {
186        (Ok(report), Ok(())) => Ok(report),
187        (Ok(_), Err(remove_err)) => Err(remove_err),
188        (Err(check_err), Ok(())) => Err(check_err),
189        (Err(check_err), Err(remove_err)) => Err(format!("{check_err}; {remove_err}")),
190    }
191}
192
193fn execute_check(
194    wt_path: &Path,
195    expanded: &str,
196    output_log: PathBuf,
197) -> Result<CheckReport, String> {
198    let (mut reader, writer) =
199        std::io::pipe().map_err(|e| format!("could not run the land check: {e}"))?;
200    let writer_err = writer
201        .try_clone()
202        .map_err(|e| format!("could not run the land check: {e}"))?;
203
204    let mut command = Command::new("sh");
205    command
206        .args(["-c", expanded])
207        .current_dir(wt_path)
208        .stdin(Stdio::null())
209        .stdout(Stdio::from(writer))
210        .stderr(Stdio::from(writer_err));
211    blyte_agent::shell::scrub_harness(&mut command);
212    let mut child = command
213        .spawn()
214        .map_err(|e| format!("could not run the land check: {e}"))?;
215    drop(command);
216
217    let mut output_bytes = Vec::new();
218    let read_res = reader.read_to_end(&mut output_bytes);
219    let status = child
220        .wait()
221        .map_err(|e| format!("could not run the land check: {e}"))?;
222    read_res.map_err(|e| format!("could not run the land check: {e}"))?;
223
224    if let Some(parent) = output_log.parent() {
225        std::fs::create_dir_all(parent).map_err(|e| {
226            format!(
227                "could not write the land check output to {}: {e}",
228                output_log.display()
229            )
230        })?;
231    }
232    std::fs::write(&output_log, &output_bytes).map_err(|e| {
233        format!(
234            "could not write the land check output to {}: {e}",
235            output_log.display()
236        )
237    })?;
238
239    let exit_code = status.code();
240    let passed = exit_code == Some(0);
241    let output_tail = tail_utf8(&output_bytes, CHECK_OUTPUT_TAIL_BYTES);
242    Ok(CheckReport {
243        passed,
244        exit_code,
245        output_tail,
246        output_log,
247    })
248}
249
250fn remove_land_worktree(root: &Path, wt_rel: &Path, wt_path: &Path) -> Result<(), String> {
251    let out = Command::new("git")
252        .args(["worktree", "remove", "--force"])
253        .arg(wt_rel)
254        .current_dir(root)
255        .env("GIT_TERMINAL_PROMPT", "0")
256        .output()
257        .map_err(|e| format!("failed to remove worktree {}: {e}", wt_path.display()))?;
258    if !out.status.success() {
259        let detail = output_detail(&out);
260        return Err(format!(
261            "failed to remove worktree {}: {detail}",
262            wt_path.display()
263        ));
264    }
265    Ok(())
266}
267
268fn tail_utf8(bytes: &[u8], max_bytes: usize) -> String {
269    let text = String::from_utf8_lossy(bytes);
270    if text.len() <= max_bytes {
271        return text.into_owned();
272    }
273    let mut start = text.len() - max_bytes;
274    while !text.is_char_boundary(start) {
275        start += 1;
276    }
277    text[start..].to_string()
278}
279
280pub fn merge_pull_request(root: &Path, url: &str, commit: &str) -> Result<(), String> {
281    merge_pull_request_with_gh(root, "gh", url, commit)
282}
283
284pub fn merge_pull_request_with_gh(
285    root: &Path,
286    gh: &str,
287    url: &str,
288    commit: &str,
289) -> Result<(), String> {
290    run_gh(
291        root,
292        OsStr::new(gh),
293        &[
294            "pr",
295            "merge",
296            url,
297            "--squash",
298            "--match-head-commit",
299            commit,
300        ],
301        "gh pr merge",
302    )?;
303    Ok(())
304}
305
306pub fn update_default_branch(root: &Path, base: &str) -> Result<String, String> {
307    let fetch = run_git(root, &["fetch", "--quiet", "origin", base])?;
308    if !fetch.status.success() {
309        let detail = output_detail(&fetch);
310        return Err(format!("git fetch origin {base} failed: {detail}"));
311    }
312
313    let head = run_git(root, &["rev-parse", "--abbrev-ref", "HEAD"])?;
314    if !head.status.success() {
315        let detail = output_detail(&head);
316        return Err(format!(
317            "could not read current branch in {}: {detail}",
318            root.display()
319        ));
320    }
321    let branch = String::from_utf8_lossy(&head.stdout).trim().to_string();
322    if branch != base {
323        return Ok(format!(
324            "fetched origin/{base}; {} is on {branch}, left as it was",
325            root.display()
326        ));
327    }
328
329    let status = run_git(root, &["status", "--porcelain"])?;
330    if !status.status.success() {
331        let detail = output_detail(&status);
332        return Err(format!(
333            "could not read git status in {}: {detail}",
334            root.display()
335        ));
336    }
337    if !String::from_utf8_lossy(&status.stdout).trim().is_empty() {
338        return Ok(format!(
339            "fetched origin/{base}; {} has uncommitted changes, left as it was",
340            root.display()
341        ));
342    }
343
344    let remote_ref = format!("origin/{base}");
345    let merge = run_git(root, &["merge", "--ff-only", &remote_ref])?;
346    if !merge.status.success() {
347        let detail = output_detail(&merge);
348        return Err(format!("git merge --ff-only {remote_ref} failed: {detail}"));
349    }
350    Ok(format!(
351        "fetched origin/{base} and fast-forwarded {base} in {}",
352        root.display()
353    ))
354}
355
356pub trait Lander: Send + Sync {
357    fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String>;
358    fn check(
359        &self,
360        root: &Path,
361        command: &str,
362        number: u64,
363        commit: &str,
364    ) -> Result<CheckReport, String>;
365    fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String>;
366    fn update(&self, root: &Path, base: &str) -> Result<String, String>;
367}
368
369pub struct RealLander;
370
371impl Lander for RealLander {
372    fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String> {
373        view_pull_request(root, url)
374    }
375
376    fn check(
377        &self,
378        root: &Path,
379        command: &str,
380        number: u64,
381        commit: &str,
382    ) -> Result<CheckReport, String> {
383        run_land_check(root, command, number, commit)
384    }
385
386    fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String> {
387        merge_pull_request(root, url, commit)
388    }
389
390    fn update(&self, root: &Path, base: &str) -> Result<String, String> {
391        update_default_branch(root, base)
392    }
393}
394
395pub struct SurfaceLandTool {
396    surface: Arc<Surface>,
397    approver: Arc<dyn Approver>,
398    lander: Arc<dyn Lander>,
399}
400
401impl SurfaceLandTool {
402    pub fn new(surface: Arc<Surface>) -> Self {
403        let approver: Arc<dyn Approver> = surface.session.approver();
404        Self {
405            surface,
406            approver,
407            lander: Arc::new(RealLander),
408        }
409    }
410
411    pub fn with_lander(
412        surface: Arc<Surface>,
413        approver: Arc<dyn Approver>,
414        lander: Arc<dyn Lander>,
415    ) -> Self {
416        Self {
417            surface,
418            approver,
419            lander,
420        }
421    }
422}
423
424impl blyte_agent::tools::LandTool for SurfaceLandTool {
425    fn land(&self, request: &str) -> Result<String, String> {
426        land_request(
427            &self.surface,
428            self.approver.as_ref(),
429            self.lander.as_ref(),
430            request,
431        )
432    }
433}
434
435pub fn land_request(
436    surface: &Surface,
437    approver: &dyn Approver,
438    lander: &dyn Lander,
439    request: &str,
440) -> Result<String, String> {
441    if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
442        return Err(format!(
443            "cannot land during a turn started by another surface ({started_by})"
444        ));
445    }
446
447    crate::dispatch::validate_request_id(request)?;
448    match check_request_ownership(surface, request) {
449        Ok(RequestOwnership::Owned) => {}
450        Ok(RequestOwnership::OtherSurface) => {
451            return Err(format!("request {request} belongs to another surface"));
452        }
453        Ok(RequestOwnership::Unowned) => {
454            return Err(format!("request {request} was not started by this surface"));
455        }
456        Ok(RequestOwnership::NotFound) => {
457            return Err(format!("unknown request {request}"));
458        }
459        Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
460            return Err(msg);
461        }
462    }
463
464    let mut published = load_published_record(&surface.root, request)?;
465    let (Some(url), Some(pushed_commit)) = (
466        published.pull_request_url.clone(),
467        published.pushed_commit.clone(),
468    ) else {
469        return Err(format!(
470            "request {request} has no pull request: publish it first"
471        ));
472    };
473    if published.landed_head.is_some() {
474        return Err(format!("request {request} is already landed ({url})"));
475    }
476
477    let land_check = match crate::config::load_with_fallback(&surface.root)? {
478        Some((cfg, _)) => match cfg.surface.land_check {
479            Some(cmd) => cmd,
480            None => {
481                return Err(
482                    "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)"
483                        .to_string(),
484                );
485            }
486        },
487        None => {
488            return Err(
489                "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)"
490                    .to_string(),
491            );
492        }
493    };
494
495    let _in_flight = surface
496        .requests
497        .try_begin_publish(request)
498        .ok_or_else(|| format!("request {request} is already being published or landed"))?;
499
500    let info = lander.view(&surface.root, &url)?;
501    check_landable(&info, &pushed_commit)?;
502
503    let expanded = expand_check_command(&land_check, info.number);
504    let report = lander.check(&surface.root, &land_check, info.number, &pushed_commit)?;
505    if !report.passed {
506        let code = match report.exit_code {
507            Some(c) => c.to_string(),
508            None => "signal".to_string(),
509        };
510        return Err(format!(
511            "the landing check failed (exit {code}): {expanded}\nfull output: {}\n{}",
512            report.output_log.display(),
513            report.output_tail
514        ));
515    }
516
517    let details = LandDetails {
518        request: request.to_string(),
519        pull_request_url: url.clone(),
520        number: info.number,
521        title: info.title.clone(),
522        branch: info.head_ref_name.clone(),
523        base: info.base_ref_name.clone(),
524        commit: pushed_commit.clone(),
525        check_command: expanded,
526    };
527    match approver.ask_land(&details) {
528        Approval::Approved => {}
529        Approval::Denied => {
530            return Err("the user declined".to_string());
531        }
532        Approval::Unavailable => {
533            return Err("merge approval is not available here".to_string());
534        }
535    }
536
537    lander.merge(&surface.root, &url, &pushed_commit)?;
538
539    published.landed_head = Some(pushed_commit.clone());
540    write_published_record(&surface.root, request, &published)?;
541
542    let notice = format!(
543        "Merged pull request #{} ({url}) into {} at {pushed_commit}",
544        info.number, info.base_ref_name
545    );
546    if let Err(e) = surface
547        .session
548        .record_decision(request, "land", Some(&notice), None)
549    {
550        surface.session.record_error(&format!(
551            "failed to record land decision for {request}: {e}"
552        ));
553    }
554
555    let update_line = match lander.update(&surface.root, &info.base_ref_name) {
556        Ok(msg) => msg,
557        Err(err) => format!("could not update {}: {err}", surface.root.display()),
558    };
559
560    Ok(format!("{notice}\n{update_line}"))
561}