1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Feature {
22 Search,
24 Resolve,
26 Land,
28 Runs,
30 Explain,
32 RequiredChecks,
34}
35
36pub trait Host {
37 fn forge(&self) -> Forge;
38
39 fn lacks(&mut self, feature: Feature) -> Option<String>;
41
42 fn fetch(&mut self, lookups: Vec<Lookup>) -> Result<FetchResult, String>;
45
46 fn threads(
49 &mut self,
50 target: &Target,
51 extra: bool,
52 bots: &[String],
53 ) -> Result<Option<PrThreads>, String>;
54
55 fn pushed_at(&mut self, pr: &PrThreads, sha: &str) -> Result<Pushed, threads::Lookup>;
57
58 fn files(
61 &mut self,
62 pr: &PrThreads,
63 oid: &str,
64 paths: &[String],
65 ) -> Result<Vec<(String, String)>, String>;
66
67 fn merge_base(&mut self, pr: &PrThreads) -> Result<String, String>;
69
70 fn on_branch(&mut self, pr: &PrThreads, head: &str) -> Result<bool, String>;
73
74 fn reply(&mut self, pr: &PrThreads, thread: &Thread, body: &str) -> Result<String, String>;
76
77 fn set_resolved(
79 &mut self,
80 pr: &PrThreads,
81 thread: &Thread,
82 resolved: bool,
83 ) -> Result<(), String>;
84}
85
86pub 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
98pub 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
111pub 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 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}