Skip to main content

jouet_github/pr/
next.rs

1//! `jouet pr next`: the one thing a PR needs next, after Kent C. Dodds'
2//! `ship-pr.mjs`.
3//!
4//! The order is fixed and the first state that applies wins: merged, closed,
5//! draft, conflict, mergeability still unknown, behind its base, failing
6//! checks, pending checks, changes requested, unresolved threads, open
7//! Entire findings, another failing Entire gate, waiting on approval,
8//! blocked by another branch protection rule, auto-merge, and finally ready
9//! to merge. The states come from what `pr status` fetched,
10//! and its attention codes and messages, so the two commands never disagree.
11
12use super::status::{PrStatus, State};
13use crate::forge::Forge;
14use serde::Serialize;
15use std::fmt::Write as _;
16
17/// Whose move it is.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
19#[serde(rename_all = "snake_case")]
20pub enum Kind {
21    /// Nothing is left for the agent to do: merged, closed, or ready for a
22    /// person to land.
23    Done,
24    /// The agent must do something.
25    Act,
26    /// Waiting on someone or something else: CI, a reviewer, GitHub.
27    Wait,
28}
29
30/// The next action, as a fixed code.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
32#[serde(rename_all = "snake_case")]
33pub enum Action {
34    Merged,
35    Closed,
36    Draft,
37    Conflict,
38    MergeableUnknown,
39    BehindBase,
40    ChecksFailing,
41    ChecksPending,
42    ChangesRequested,
43    UnresolvedThreads,
44    EntireFindings,
45    EntireGates,
46    AwaitingApproval,
47    Blocked,
48    AutoMerge,
49    ReadyToMerge,
50}
51
52impl Action {
53    pub fn kind(self) -> Kind {
54        match self {
55            Self::Merged | Self::Closed | Self::ReadyToMerge => Kind::Done,
56            Self::Draft
57            | Self::Conflict
58            | Self::BehindBase
59            | Self::ChecksFailing
60            | Self::ChangesRequested
61            | Self::UnresolvedThreads
62            | Self::EntireFindings => Kind::Act,
63            Self::MergeableUnknown
64            | Self::ChecksPending
65            | Self::EntireGates
66            | Self::AwaitingApproval
67            | Self::Blocked
68            | Self::AutoMerge => Kind::Wait,
69        }
70    }
71
72    pub fn as_str(self) -> &'static str {
73        match self {
74            Self::Merged => "merged",
75            Self::Closed => "closed",
76            Self::Draft => "draft",
77            Self::Conflict => "conflict",
78            Self::MergeableUnknown => "mergeable_unknown",
79            Self::BehindBase => "behind_base",
80            Self::ChecksFailing => "checks_failing",
81            Self::ChecksPending => "checks_pending",
82            Self::ChangesRequested => "changes_requested",
83            Self::UnresolvedThreads => "unresolved_threads",
84            Self::EntireFindings => "entire_findings",
85            Self::EntireGates => "entire_gates",
86            Self::AwaitingApproval => "awaiting_approval",
87            Self::Blocked => "blocked",
88            Self::AutoMerge => "auto_merge",
89            Self::ReadyToMerge => "ready_to_merge",
90        }
91    }
92}
93
94/// What a PR needs next, why, and the command that does it.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
96pub struct Next {
97    pub action: Action,
98    pub kind: Kind,
99    /// One line on why this is the next action.
100    pub reason: String,
101    /// The command that addresses it; absent when there is nothing to run.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub command: Option<String>,
104}
105
106/// GitHub's merge states that let a PR merge. `unstable` means a check that
107/// branch protection does not require is failing, and `has_hooks` that the
108/// server has pre-receive hooks; neither stops a merge.
109const MERGEABLE_STATES: [&str; 3] = ["clean", "unstable", "has_hooks"];
110
111/// Works through the states in order and returns the first that applies.
112/// `pr` must have been finished by `Fetched::finish`, which fills in its
113/// attention codes.
114pub fn next(pr: &PrStatus) -> Next {
115    let name = pr.name();
116    let forge = pr.forge_kind();
117    let qualified = name.rsplit_once('#').map_or("", |(r, _)| r).to_string();
118    let attention = |code: &str| {
119        pr.attention
120            .iter()
121            .find(|a| a.code == code)
122            .map(|a| a.message.clone())
123    };
124    let step = |action: Action, reason: String, command: Option<String>| Next {
125        action,
126        kind: action.kind(),
127        reason,
128        command,
129    };
130    let update = format!("git fetch origin {0} && git merge origin/{0}", pr.base);
131    match pr.state {
132        State::Merged => return step(Action::Merged, "Merged".into(), None),
133        State::Closed => {
134            return step(
135                Action::Closed,
136                "Closed without merging; reopen it to continue".into(),
137                None,
138            );
139        }
140        State::Open | State::Draft => {}
141    }
142    if let Some(reason) = attention("draft") {
143        return step(
144            Action::Draft,
145            reason,
146            match forge {
147                Forge::GitHub => Some(format!("gh pr ready {} --repo {}", pr.number, pr.repo)),
148                Forge::GitLab => Some(format!(
149                    "glab mr update {} --ready -R {qualified}",
150                    pr.number
151                )),
152                // A Forgejo draft is a `WIP:` title, which no command clears.
153                Forge::Forgejo => None,
154                Forge::Entire => Some(format!(
155                    "entire trail update --branch {} --status open --repo et/{}",
156                    pr.head, pr.repo
157                )),
158            },
159        );
160    }
161    if let Some(reason) = attention("conflict") {
162        return step(Action::Conflict, reason, Some(update));
163    }
164    if let Some(reason) = attention("mergeable_unknown") {
165        return step(
166            Action::MergeableUnknown,
167            reason,
168            Some(format!("jouet wait pr {name} --until mergeable")),
169        );
170    }
171    if let Some(reason) = attention("behind_base") {
172        return step(Action::BehindBase, reason, Some(update));
173    }
174    if let Some(reason) = attention("checks_failing") {
175        return step(
176            Action::ChecksFailing,
177            reason,
178            Some(format!("jouet wait ci {name}")),
179        );
180    }
181    let checks = &pr.checks;
182    // No checks yet, but not for long enough that `pr status` calls them
183    // missing: they are still being registered.
184    let registering = checks.total() == 0 && attention("checks_missing").is_none();
185    if checks.pending > 0 || registering {
186        let reason = if checks.pending > 0 {
187            format!("{} of {} checks pending", checks.pending, checks.total())
188        } else {
189            "Waiting for checks to register on the new head".into()
190        };
191        return step(
192            Action::ChecksPending,
193            reason,
194            Some(format!("jouet wait ci {name}")),
195        );
196    }
197    if let Some(reason) = attention("changes_requested") {
198        return step(
199            Action::ChangesRequested,
200            reason,
201            Some(format!("jouet pr threads {name} --include-reviews")),
202        );
203    }
204    if let Some(reason) = attention("unresolved_threads") {
205        return step(
206            Action::UnresolvedThreads,
207            reason,
208            Some(format!("jouet pr threads {name}")),
209        );
210    }
211    if let Some(reason) = attention("entire_findings") {
212        return step(
213            Action::EntireFindings,
214            reason,
215            Some(format!("jouet pr threads {name}")),
216        );
217    }
218    if let Some(reason) = attention("entire_gates") {
219        return step(
220            Action::EntireGates,
221            reason,
222            Some(format!("jouet pr status {name}")),
223        );
224    }
225    if pr.review.as_deref() == Some("review_required") {
226        return step(
227            Action::AwaitingApproval,
228            "Waiting for an approving review".into(),
229            Some(format!("jouet wait pr {name} --until approved")),
230        );
231    }
232    if pr.merge_state == "unknown" {
233        return step(
234            Action::MergeableUnknown,
235            format!(
236                "{} has not finished computing the merge state; run again shortly",
237                forge.name()
238            ),
239            Some(format!("jouet wait pr {name} --until mergeable")),
240        );
241    }
242    if !MERGEABLE_STATES.contains(&pr.merge_state.as_str()) {
243        return step(
244            Action::Blocked,
245            match forge {
246                Forge::GitHub => format!(
247                    "GitHub reports the merge as {} by branch protection or a ruleset",
248                    pr.merge_state
249                ),
250                _ => format!("{} reports the merge as {}", forge.name(), pr.merge_state),
251            },
252            Some(format!("jouet wait pr {name} --until any-change")),
253        );
254    }
255    if pr.auto_merge {
256        return step(
257            Action::AutoMerge,
258            format!("Auto-merge is enabled; {} will merge it", forge.name()),
259            Some(format!("jouet wait pr {name} --until merged")),
260        );
261    }
262    let land = match forge {
263        Forge::GitHub => Some(format!("jouet pr land {name}")),
264        Forge::GitLab => Some(format!("glab mr merge {} -R {qualified}", pr.number)),
265        Forge::Forgejo => Some(format!("tea pulls merge {} --repo {}", pr.number, pr.repo)),
266        // The entire CLI has no command that merges a trail.
267        Forge::Entire => None,
268    };
269    let mut reason = ready_reason(pr);
270    if land.is_none() {
271        let _ = write!(reason, "; merge it on entire.com: {}", pr.url);
272    }
273    step(Action::ReadyToMerge, reason, land)
274}
275
276/// `Checks pass (46/46), approved, no unresolved threads`.
277fn ready_reason(pr: &PrStatus) -> String {
278    let checks = &pr.checks;
279    let checks = if checks.total() == 0 {
280        "No checks ran".to_string()
281    } else {
282        format!("Checks pass ({}/{})", checks.pass, checks.total())
283    };
284    let review = if pr.review.as_deref() == Some("approved") {
285        "approved"
286    } else {
287        "no review required"
288    };
289    format!("{checks}, {review}, no unresolved threads")
290}
291
292#[cfg(test)]
293#[path = "next_tests.rs"]
294mod tests;