1use 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
17pub const DEFAULT_SETTLE: Duration = Duration::from_secs(20);
20
21pub struct Selection<'a> {
23 pub prs: &'a [String],
24 pub mine: bool,
25 pub search: Option<&'a str>,
26 pub repo: &'a [String],
27 pub checkout: &'a dyn Checkout,
29}
30
31pub trait Checkout {
34 fn repo(&self) -> Option<Repo>;
36 fn branch(&self) -> Option<String>;
38}
39
40pub 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#[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 #[serde(skip_serializing_if = "Option::is_none")]
64 pub entire: Option<Availability>,
65}
66
67pub 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
86fn 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
118pub type Refused = (Exit, String);
120
121pub 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 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 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}