Skip to main content

jouet_github/pr/
select.rs

1//! The PRs a command names: arguments, `--mine`, `--search` and `--repo`,
2//! turned into lookups and fetched. `jouet pr status`, `jouet pr next` and
3//! the routines' `github.prs` share it, so they always select the same PRs.
4
5use super::entire;
6use super::status::{self, Fetched, Incomplete, Lookup, PrStatus};
7use super::target::{self, Arg, Repo, Target};
8use crate::entire::Availability;
9use crate::forge::{self, Forge};
10use crate::{Client, host};
11use jouet_output::exit::Exit;
12use jouet_output::time;
13use serde::Serialize;
14use std::fmt::Write as _;
15use std::time::Duration;
16
17/// How long to wait for GitHub to compute an unknown mergeable state when
18/// `--settle` is not given.
19pub const DEFAULT_SETTLE: Duration = Duration::from_secs(20);
20
21/// The PRs a command names.
22pub struct Selection<'a> {
23    pub prs: &'a [String],
24    pub mine: bool,
25    pub search: Option<&'a str>,
26    pub repo: &'a [String],
27    /// Where the checkout's repository and branch come from.
28    pub checkout: &'a dyn Checkout,
29}
30
31/// The checkout a bare number or branch, and the current branch's PR, are
32/// read against.
33pub trait Checkout {
34    /// The GitHub repository the remotes name.
35    fn repo(&self) -> Option<Repo>;
36    /// The branch checked out.
37    fn branch(&self) -> Option<String>;
38}
39
40/// The checkout in this process's directory, through git.
41pub struct Git;
42
43impl Checkout for Git {
44    fn repo(&self) -> Option<Repo> {
45        target::repo_from_git()
46    }
47
48    fn branch(&self) -> Option<String> {
49        target::current_branch()
50    }
51}
52
53/// The PRs found, in the order they were named, and what was not.
54#[derive(Debug, Serialize)]
55pub struct Report {
56    pub prs: Vec<PrStatus>,
57    #[serde(skip_serializing_if = "Vec::is_empty")]
58    pub not_found: Vec<String>,
59    #[serde(skip_serializing_if = "Vec::is_empty")]
60    pub incomplete: Vec<Incomplete>,
61    /// Whether the `entire` CLI could be asked, when some PR's Entire
62    /// Gates check failed on findings or an out-of-date branch.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub entire: Option<Availability>,
65}
66
67/// Fetches the PRs the lookups name, waits up to `settle` for unknown
68/// mergeability, and derives their attention codes.
69pub fn fetch(
70    client: &mut Client,
71    lookups: Vec<Lookup>,
72    settle: Duration,
73) -> Result<Report, String> {
74    let mut fetched = host::fetch(client, lookups)?;
75    settle_each(client, &mut fetched.prs, settle)?;
76    let entire = entire::add(&mut fetched.prs);
77    let now = time::now();
78    Ok(Report {
79        prs: fetched.prs.into_iter().map(|p| p.finish(now)).collect(),
80        not_found: fetched.not_found,
81        incomplete: fetched.incomplete,
82        entire,
83    })
84}
85
86/// Settles the PRs of each host through that host.
87fn settle_each(client: &mut Client, prs: &mut [Fetched], settle: Duration) -> Result<(), String> {
88    let mut hosts: Vec<Option<String>> = Vec::new();
89    for pr in prs.iter() {
90        if !hosts.contains(&pr_host(pr)) {
91            hosts.push(pr_host(pr));
92        }
93    }
94    for h in hosts {
95        let (index, mut group): (Vec<usize>, Vec<Fetched>) = prs
96            .iter()
97            .enumerate()
98            .filter(|(_, p)| pr_host(p) == h)
99            .map(|(i, p)| (i, p.clone()))
100            .unzip();
101        let Some(repo) = group.first().and_then(|p| p.status().repository()) else {
102            continue;
103        };
104        host::with(&repo, client, |host| {
105            status::settle(host, &mut group, settle)
106        })?;
107        for (i, pr) in index.into_iter().zip(group) {
108            prs[i] = pr;
109        }
110    }
111    Ok(())
112}
113
114fn pr_host(pr: &Fetched) -> Option<String> {
115    pr.status().host.clone()
116}
117
118/// Why a selection cannot be fetched: its exit code and message.
119pub type Refused = (Exit, String);
120
121/// Turns the arguments and selectors into lookups, in the order given.
122/// Arguments that do not parse are usage errors (2); a host jouet does not
123/// know, or `--search` on a forge without GitHub's search, is refused (4).
124pub fn lookups(args: &Selection<'_>) -> Result<Vec<Lookup>, Refused> {
125    let usage = |m: String| (Exit::Usage, m);
126    let repos = args
127        .repo
128        .iter()
129        .map(|r| {
130            Repo::parse(r).ok_or_else(|| {
131                usage(format!(
132                    "--repo takes OWNER/NAME or HOST/OWNER/NAME, not `{r}`"
133                ))
134            })
135        })
136        .collect::<Result<Vec<_>, _>>()?;
137    let git_repo = std::cell::OnceCell::new();
138    let git_repo = || git_repo.get_or_init(|| args.checkout.repo()).clone();
139    let repo_for = |arg: &str| match repos.as_slice() {
140        [repo] => Ok(repo.clone()),
141        [] => git_repo().ok_or_else(|| {
142            usage(format!(
143                "no --repo given and no GitHub remote here, so `{arg}` names no repository"
144            ))
145        }),
146        _ => Err(usage(format!(
147            "`{arg}` is ambiguous with {} --repo values; write it as OWNER/REPO#N",
148            repos.len()
149        ))),
150    };
151    let mut lookups = Vec::new();
152    for arg in args.prs {
153        let target = match Arg::parse(arg) {
154            Arg::Number(n) => Target::Number(repo_for(arg)?, n),
155            Arg::Branch(branch) => Target::Branch(repo_for(arg)?, branch),
156            Arg::InRepo(repo, n) => Target::Number(repo, n),
157        };
158        lookups.push(Lookup::Pr(target));
159    }
160    // Searches cover every --repo, else this checkout's repository, else all
161    // of GitHub.
162    let scope: Vec<Repo> = if repos.is_empty() {
163        git_repo().into_iter().collect()
164    } else {
165        repos.clone()
166    };
167    let (on_github, elsewhere): (Vec<Repo>, Vec<Repo>) =
168        scope.into_iter().partition(|r| r.host.is_none());
169    if args.mine {
170        // GitLab and Forgejo have no search: each repository is asked.
171        if !on_github.is_empty() || elsewhere.is_empty() {
172            lookups.push(search("is:open author:@me", &on_github));
173        }
174        lookups.extend(elsewhere.iter().cloned().map(Lookup::Mine));
175    }
176    if let Some(query) = args.search {
177        let scoped = ["repo:", "org:", "user:"]
178            .iter()
179            .any(|q| query.split_whitespace().any(|w| w.starts_with(q)));
180        if !scoped && let Some(repo) = elsewhere.first() {
181            let forge = repo.forge().map_or("another forge", Forge::name);
182            return Err((
183                Exit::Precondition,
184                format!(
185                    "--search takes GitHub's search syntax, and {} is on {forge}, which has no equivalent; name the PRs, or use --mine",
186                    repo.qualified()
187                ),
188            ));
189        }
190        lookups.push(search(query, if scoped { &[] } else { &on_github }));
191    }
192    if lookups.is_empty() {
193        let branch = args
194            .checkout
195            .branch()
196            .ok_or_else(|| usage("not on a branch: name a PR, or use --mine or --search".into()))?;
197        let repo = repo_for(&branch)?;
198        lookups.push(Lookup::Pr(Target::Branch(repo, branch)));
199    }
200    if let Some(host) = lookups
201        .iter()
202        .filter_map(Lookup::repo)
203        .find(|r| r.forge().is_none())
204        .and_then(|r| r.host.as_deref())
205    {
206        return Err((Exit::Precondition, forge::unknown(host)));
207    }
208    Ok(lookups)
209}
210
211fn search(query: &str, repos: &[Repo]) -> Lookup {
212    let mut query = format!("is:pr {query}");
213    for repo in repos {
214        let _ = write!(query, " repo:{repo}");
215    }
216    Lookup::Search {
217        query,
218        after: None,
219        listed: 0,
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn searches_are_scoped_to_repos() {
229        let repos = [
230            Repo::parse("jdx/mise").unwrap(),
231            Repo::parse("jdx/hk").unwrap(),
232        ];
233        assert_eq!(
234            search("is:open author:@me", &repos),
235            Lookup::Search {
236                query: "is:pr is:open author:@me repo:jdx/mise repo:jdx/hk".into(),
237                after: None,
238                listed: 0,
239            }
240        );
241    }
242}