use super::entire;
use super::status::{self, Fetched, Incomplete, Lookup, PrStatus};
use super::target::{self, Arg, Repo, Target};
use crate::entire::Availability;
use crate::forge::{self, Forge};
use crate::{Client, host};
use jouet_output::exit::Exit;
use jouet_output::time;
use serde::Serialize;
use std::fmt::Write as _;
use std::time::Duration;
pub const DEFAULT_SETTLE: Duration = Duration::from_secs(20);
pub struct Selection<'a> {
pub prs: &'a [String],
pub mine: bool,
pub search: Option<&'a str>,
pub repo: &'a [String],
pub checkout: &'a dyn Checkout,
}
pub trait Checkout {
fn repo(&self) -> Option<Repo>;
fn branch(&self) -> Option<String>;
}
pub struct Git;
impl Checkout for Git {
fn repo(&self) -> Option<Repo> {
target::repo_from_git()
}
fn branch(&self) -> Option<String> {
target::current_branch()
}
}
#[derive(Debug, Serialize)]
pub struct Report {
pub prs: Vec<PrStatus>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub not_found: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub incomplete: Vec<Incomplete>,
#[serde(skip_serializing_if = "Option::is_none")]
pub entire: Option<Availability>,
}
pub fn fetch(
client: &mut Client,
lookups: Vec<Lookup>,
settle: Duration,
) -> Result<Report, String> {
let mut fetched = host::fetch(client, lookups)?;
settle_each(client, &mut fetched.prs, settle)?;
let entire = entire::add(&mut fetched.prs);
let now = time::now();
Ok(Report {
prs: fetched.prs.into_iter().map(|p| p.finish(now)).collect(),
not_found: fetched.not_found,
incomplete: fetched.incomplete,
entire,
})
}
fn settle_each(client: &mut Client, prs: &mut [Fetched], settle: Duration) -> Result<(), String> {
let mut hosts: Vec<Option<String>> = Vec::new();
for pr in prs.iter() {
if !hosts.contains(&pr_host(pr)) {
hosts.push(pr_host(pr));
}
}
for h in hosts {
let (index, mut group): (Vec<usize>, Vec<Fetched>) = prs
.iter()
.enumerate()
.filter(|(_, p)| pr_host(p) == h)
.map(|(i, p)| (i, p.clone()))
.unzip();
let Some(repo) = group.first().and_then(|p| p.status().repository()) else {
continue;
};
host::with(&repo, client, |host| {
status::settle(host, &mut group, settle)
})?;
for (i, pr) in index.into_iter().zip(group) {
prs[i] = pr;
}
}
Ok(())
}
fn pr_host(pr: &Fetched) -> Option<String> {
pr.status().host.clone()
}
pub type Refused = (Exit, String);
pub fn lookups(args: &Selection<'_>) -> Result<Vec<Lookup>, Refused> {
let usage = |m: String| (Exit::Usage, m);
let repos = args
.repo
.iter()
.map(|r| {
Repo::parse(r).ok_or_else(|| {
usage(format!(
"--repo takes OWNER/NAME or HOST/OWNER/NAME, not `{r}`"
))
})
})
.collect::<Result<Vec<_>, _>>()?;
let git_repo = std::cell::OnceCell::new();
let git_repo = || git_repo.get_or_init(|| args.checkout.repo()).clone();
let repo_for = |arg: &str| match repos.as_slice() {
[repo] => Ok(repo.clone()),
[] => git_repo().ok_or_else(|| {
usage(format!(
"no --repo given and no GitHub remote here, so `{arg}` names no repository"
))
}),
_ => Err(usage(format!(
"`{arg}` is ambiguous with {} --repo values; write it as OWNER/REPO#N",
repos.len()
))),
};
let mut lookups = Vec::new();
for arg in args.prs {
let target = match Arg::parse(arg) {
Arg::Number(n) => Target::Number(repo_for(arg)?, n),
Arg::Branch(branch) => Target::Branch(repo_for(arg)?, branch),
Arg::InRepo(repo, n) => Target::Number(repo, n),
};
lookups.push(Lookup::Pr(target));
}
let scope: Vec<Repo> = if repos.is_empty() {
git_repo().into_iter().collect()
} else {
repos.clone()
};
let (on_github, elsewhere): (Vec<Repo>, Vec<Repo>) =
scope.into_iter().partition(|r| r.host.is_none());
if args.mine {
if !on_github.is_empty() || elsewhere.is_empty() {
lookups.push(search("is:open author:@me", &on_github));
}
lookups.extend(elsewhere.iter().cloned().map(Lookup::Mine));
}
if let Some(query) = args.search {
let scoped = ["repo:", "org:", "user:"]
.iter()
.any(|q| query.split_whitespace().any(|w| w.starts_with(q)));
if !scoped && let Some(repo) = elsewhere.first() {
let forge = repo.forge().map_or("another forge", Forge::name);
return Err((
Exit::Precondition,
format!(
"--search takes GitHub's search syntax, and {} is on {forge}, which has no equivalent; name the PRs, or use --mine",
repo.qualified()
),
));
}
lookups.push(search(query, if scoped { &[] } else { &on_github }));
}
if lookups.is_empty() {
let branch = args
.checkout
.branch()
.ok_or_else(|| usage("not on a branch: name a PR, or use --mine or --search".into()))?;
let repo = repo_for(&branch)?;
lookups.push(Lookup::Pr(Target::Branch(repo, branch)));
}
if let Some(host) = lookups
.iter()
.filter_map(Lookup::repo)
.find(|r| r.forge().is_none())
.and_then(|r| r.host.as_deref())
{
return Err((Exit::Precondition, forge::unknown(host)));
}
Ok(lookups)
}
fn search(query: &str, repos: &[Repo]) -> Lookup {
let mut query = format!("is:pr {query}");
for repo in repos {
let _ = write!(query, " repo:{repo}");
}
Lookup::Search {
query,
after: None,
listed: 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn searches_are_scoped_to_repos() {
let repos = [
Repo::parse("jdx/mise").unwrap(),
Repo::parse("jdx/hk").unwrap(),
];
assert_eq!(
search("is:open author:@me", &repos),
Lookup::Search {
query: "is:pr is:open author:@me repo:jdx/mise repo:jdx/hk".into(),
after: None,
listed: 0,
}
);
}
}