Skip to main content

jouet_github/
host.rs

1//! The host trait: what jouet's PR commands ask of a forge, answered by
2//! GitHub, GitLab, Forgejo or Entire in the same model types, so `pr status`,
3//! `pr threads` and the waits print the same output and exit the same way
4//! whichever forge a repository is on.
5//!
6//! A forge that has no equivalent of something says so through
7//! [`Host::lacks`] before anything is sent, and the command exits 4 with
8//! that reason rather than approximating it.
9
10use crate::entire_forge::EntireForge;
11use crate::forge::{self, Forge};
12use crate::pr::status::{self, FetchResult, Lookup};
13use crate::pr::target::{Repo, Target};
14use crate::pr::threads::{self, PrThreads, Pushed, Thread};
15use crate::{Client, forgejo, gitlab};
16use serde_json::json;
17use std::fmt::Write as _;
18
19/// What a forge may lack.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Feature {
22    /// `--search` with GitHub's search syntax.
23    Search,
24    /// Resolving and unresolving review threads.
25    Resolve,
26    /// Merging and updating a PR's branch: `pr land`.
27    Land,
28    /// The runs and jobs of one CI run: `wait run`.
29    Runs,
30    /// The history `ci explain` judges a failure by.
31    Explain,
32    /// Which checks branch protection requires: `wait ci --required`.
33    RequiredChecks,
34}
35
36pub trait Host {
37    fn forge(&self) -> Forge;
38
39    /// Why the forge cannot do `feature`, or `None` when it can.
40    fn lacks(&mut self, feature: Feature) -> Option<String>;
41
42    /// The PRs the lookups name, in the order named, as `pr status`
43    /// reports them before attention codes are derived.
44    fn fetch(&mut self, lookups: Vec<Lookup>) -> Result<FetchResult, String>;
45
46    /// A PR's review threads, and with `extra` its reviews and conversation
47    /// comments. `None` when there is no such PR.
48    fn threads(
49        &mut self,
50        target: &Target,
51        extra: bool,
52        bots: &[String],
53    ) -> Result<Option<PrThreads>, String>;
54
55    /// When `sha` (a prefix) was pushed to the PR.
56    fn pushed_at(&mut self, pr: &PrThreads, sha: &str) -> Result<Pushed, threads::Lookup>;
57
58    /// Files at commit `oid`, as `(path, text)`; a file that cannot be read
59    /// is left out.
60    fn files(
61        &mut self,
62        pr: &PrThreads,
63        oid: &str,
64        paths: &[String],
65    ) -> Result<Vec<(String, String)>, String>;
66
67    /// The commit the PR's diff is taken against.
68    fn merge_base(&mut self, pr: &PrThreads) -> Result<String, String>;
69
70    /// Whether `head` is on the PR's branch, for a head this clone cannot
71    /// place.
72    fn on_branch(&mut self, pr: &PrThreads, head: &str) -> Result<bool, String>;
73
74    /// Posts `body` as a reply in `thread`, returning the reply's URL.
75    fn reply(&mut self, pr: &PrThreads, thread: &Thread, body: &str) -> Result<String, String>;
76
77    /// Resolves or unresolves `thread`.
78    fn set_resolved(
79        &mut self,
80        pr: &PrThreads,
81        thread: &Thread,
82        resolved: bool,
83    ) -> Result<(), String>;
84}
85
86/// The host a repository is on: `github` for GitHub, else a new client for
87/// its GitLab, Forgejo or Entire host. `Err` names a host jouet does not know.
88pub fn connect(repo: &Repo) -> Result<Box<dyn Host>, String> {
89    match (repo.forge(), &repo.host) {
90        (Some(Forge::GitLab), Some(host)) => Ok(Box::new(gitlab::GitLab::new(host))),
91        (Some(Forge::Forgejo), Some(host)) => Ok(Box::new(forgejo::Forgejo::new(host))),
92        (Some(Forge::Entire), Some(_)) => Ok(Box::new(EntireForge::new())),
93        (_, Some(host)) if repo.forge().is_none() => Err(forge::unknown(host)),
94        _ => Ok(Box::new(Client::from_env())),
95    }
96}
97
98/// Runs `f` with the host `repo` is on: `github` for a GitHub repository,
99/// else a new client for its forge.
100pub fn with<T>(
101    repo: &Repo,
102    github: &mut Client,
103    f: impl FnOnce(&mut dyn Host) -> Result<T, String>,
104) -> Result<T, String> {
105    if repo.host.is_none() {
106        return f(github);
107    }
108    f(connect(repo)?.as_mut())
109}
110
111/// Fetches lookups that may be on several forges: GitHub's through
112/// `github`, every other host's through its own client, in the order each
113/// host was first named.
114pub fn fetch(github: &mut Client, lookups: Vec<Lookup>) -> Result<FetchResult, String> {
115    let mut groups: Vec<(Option<Repo>, Vec<Lookup>)> = Vec::new();
116    for lookup in lookups {
117        let repo = lookup.repo().filter(|r| r.host.is_some()).cloned();
118        let host = repo.as_ref().and_then(|r| r.host.clone());
119        match groups
120            .iter_mut()
121            .find(|(r, _)| r.as_ref().and_then(|r| r.host.clone()) == host)
122        {
123            Some((_, group)) => group.push(lookup),
124            None => groups.push((repo, vec![lookup])),
125        }
126    }
127    let mut result = FetchResult::default();
128    for (repo, group) in groups {
129        let fetched = match repo {
130            None => status::fetch(github, group)?,
131            Some(repo) => connect(&repo)?.fetch(group)?,
132        };
133        result.prs.extend(fetched.prs);
134        result.not_found.extend(fetched.not_found);
135        result.incomplete.extend(fetched.incomplete);
136    }
137    Ok(result)
138}
139
140const REPLY: &str = "mutation($id: ID!, $body: String!) {
141  addPullRequestReviewThreadReply(input: {pullRequestReviewThreadId: $id, body: $body}) { comment { url } }
142}";
143const RESOLVE: &str =
144    "mutation($id: ID!) { resolveReviewThread(input: {threadId: $id}) { thread { isResolved } } }";
145const UNRESOLVE: &str = "mutation($id: ID!) { unresolveReviewThread(input: {threadId: $id}) { thread { isResolved } } }";
146
147impl Host for Client {
148    fn forge(&self) -> Forge {
149        Forge::GitHub
150    }
151
152    fn lacks(&mut self, _feature: Feature) -> Option<String> {
153        None
154    }
155
156    fn fetch(&mut self, lookups: Vec<Lookup>) -> Result<FetchResult, String> {
157        status::fetch(self, lookups)
158    }
159
160    fn threads(
161        &mut self,
162        target: &Target,
163        extra: bool,
164        bots: &[String],
165    ) -> Result<Option<PrThreads>, String> {
166        threads::fetch(self, target, extra, bots)
167    }
168
169    fn pushed_at(&mut self, pr: &PrThreads, sha: &str) -> Result<Pushed, threads::Lookup> {
170        threads::pushed_at(self, pr, sha)
171    }
172
173    /// Reads every file in one GraphQL query.
174    fn files(
175        &mut self,
176        pr: &PrThreads,
177        oid: &str,
178        paths: &[String],
179    ) -> Result<Vec<(String, String)>, String> {
180        let mut q = String::from("query($o: String!, $r: String!");
181        let mut body = String::new();
182        let mut vars = json!({ "o": pr.repo.owner, "r": pr.repo.name });
183        for (i, path) in paths.iter().enumerate() {
184            let _ = write!(q, ", $e{i}: String!");
185            let _ = write!(
186                body,
187                " f{i}: object(expression: $e{i}) {{ ... on Blob {{ text }} }}"
188            );
189            vars[format!("e{i}")] = format!("{oid}:{path}").into();
190        }
191        let _ = write!(q, ") {{ repository(owner: $o, name: $r) {{{body} }} }}");
192        let data = self.graphql(&q, &vars)?;
193        Ok(paths
194            .iter()
195            .enumerate()
196            .filter_map(|(i, path)| {
197                let text = data["repository"][format!("f{i}")]["text"].as_str()?;
198                Some((path.clone(), text.to_string()))
199            })
200            .collect())
201    }
202
203    fn merge_base(&mut self, pr: &PrThreads) -> Result<String, String> {
204        let path = format!(
205            "/repos/{}/compare/{}...{}?per_page=1",
206            pr.repo, pr.base_oid, pr.head_oid
207        );
208        let compare = self
209            .rest_get(&path)?
210            .ok_or("GitHub could not compare the PR's base and head")?;
211        compare["merge_base_commit"]["sha"]
212            .as_str()
213            .map(str::to_string)
214            .ok_or_else(|| "GitHub's comparison names no merge base".into())
215    }
216
217    fn on_branch(&mut self, pr: &PrThreads, head: &str) -> Result<bool, String> {
218        let repo = pr.head_repo.as_ref().unwrap_or(&pr.repo);
219        let path = format!("/repos/{repo}/compare/{head}...{}", pr.head_oid);
220        let compare = self.rest_get(&path)?;
221        Ok(compare.is_some_and(|c| matches!(c["status"].as_str(), Some("ahead" | "identical"))))
222    }
223
224    fn reply(&mut self, _pr: &PrThreads, thread: &Thread, body: &str) -> Result<String, String> {
225        let data = self.mutate(REPLY, &json!({ "id": thread.node_id, "body": body }))?;
226        data["addPullRequestReviewThreadReply"]["comment"]["url"]
227            .as_str()
228            .map(str::to_string)
229            .ok_or_else(|| "GitHub did not post the reply".into())
230    }
231
232    fn set_resolved(
233        &mut self,
234        _pr: &PrThreads,
235        thread: &Thread,
236        resolved: bool,
237    ) -> Result<(), String> {
238        let (query, field, verb) = if resolved {
239            (RESOLVE, "resolveReviewThread", "resolve")
240        } else {
241            (UNRESOLVE, "unresolveReviewThread", "unresolve")
242        };
243        let data = self.mutate(query, &json!({ "id": thread.node_id }))?;
244        if data[field]["thread"]["isResolved"].as_bool() != Some(resolved) {
245            return Err(format!("GitHub did not {verb} the thread"));
246        }
247        Ok(())
248    }
249}