gitpoulpi_hosting/account/
mod.rs1#![cfg_attr(
21 not(all(
22 feature = "github",
23 feature = "gitlab",
24 feature = "gitea",
25 feature = "azure-devops",
26 feature = "bitbucket",
27 feature = "gerrit"
28 )),
29 allow(dead_code)
30)]
31
32use serde::{Deserialize, Serialize};
33
34use crate::http::{HttpRequest, HttpResponse, HttpTransport};
35use crate::model::{IssueSummary, PullRequestState, PullRequestSummary};
36use crate::{Error, Result};
37
38mod branches;
39mod cache;
40#[cfg(feature = "gitea")]
41pub(crate) mod gitea;
42#[cfg(feature = "github")]
43pub(crate) mod github;
44#[cfg(feature = "gitlab")]
45pub(crate) mod gitlab;
46mod namespace;
47#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
48mod tests;
49#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
50mod tests_branches;
51#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
52mod tests_namespaces;
53#[cfg(all(
54 test,
55 feature = "github",
56 feature = "gitlab",
57 feature = "gitea",
58 feature = "azure-devops",
59 feature = "bitbucket",
60 feature = "gerrit"
61))]
62mod tests_wave2;
63
64pub use cache::{
65 cache_path, AccountCache, CachedAccount, ACCOUNT_CACHE_FILE, ACCOUNT_TTL, ACCOUNT_TTL_SECS,
66};
67pub use namespace::{compile as compile_namespace_regex, first_regex_error, NamespaceFilter};
68
69pub const DEFAULT_LIMIT: usize = 300;
71
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct AccountQuery {
75 pub review_requests: bool,
77 pub open_requests: bool,
79 pub assigned_issues: bool,
81 pub include_drafts: bool,
83 pub namespaces: Vec<String>,
86 #[serde(default)]
89 pub namespaces_regex: bool,
90 pub limit: usize,
92}
93
94impl AccountQuery {
95 pub fn row_limit(&self) -> usize {
97 if self.limit == 0 {
98 DEFAULT_LIMIT
99 } else {
100 self.limit
101 }
102 }
103
104 pub fn search_namespaces(&self) -> &[String] {
108 if self.namespaces_regex {
109 &[]
110 } else {
111 &self.namespaces
112 }
113 }
114
115 pub fn is_empty(&self) -> bool {
117 !(self.review_requests || self.open_requests || self.assigned_issues)
118 }
119
120 pub fn fingerprint(&self) -> String {
123 let mut spaces: Vec<String> = self.namespaces.iter().map(|n| n.to_lowercase()).collect();
124 spaces.sort();
125 let text = format!(
126 "v2r{}o{}i{}d{}l{}x{}|{}",
127 self.review_requests as u8,
128 self.open_requests as u8,
129 self.assigned_issues as u8,
130 self.include_drafts as u8,
131 self.row_limit(),
132 self.namespaces_regex as u8,
133 spaces.join(",")
134 );
135 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
136 for b in text.bytes() {
137 hash ^= u64::from(b);
138 hash = hash.wrapping_mul(0x0100_0000_01b3);
139 }
140 format!("{hash:016x}")
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146pub struct AccountPr {
147 pub project: String,
149 #[serde(default)]
151 pub clone_url: String,
152 #[serde(flatten)]
153 pub pr: PullRequestSummary,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct AccountIssue {
159 pub project: String,
160 #[serde(default)]
161 pub clone_url: String,
162 #[serde(flatten)]
163 pub issue: IssueSummary,
164}
165
166#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
168pub struct AccountItems {
169 #[serde(default)]
170 pub prs: Vec<AccountPr>,
171 #[serde(default)]
172 pub issues: Vec<AccountIssue>,
173 #[serde(default)]
175 pub truncated: bool,
176 #[serde(default)]
178 pub notes: Vec<String>,
179}
180
181pub fn supports(kind: crate::IntegrationKind) -> bool {
184 use gitpoulpi_config::ApiFamily;
185 match kind.family() {
186 ApiFamily::Github
187 | ApiFamily::Gitlab
188 | ApiFamily::Gitea
189 | ApiFamily::AzureDevops
190 | ApiFamily::Gerrit => true,
191 ApiFamily::Bitbucket => kind == crate::IntegrationKind::BitbucketDataCenter,
193 _ => false,
194 }
195}
196
197pub const NO_BITBUCKET_CLOUD: &str = "Bitbucket Cloud has no account-wide pull request \
199 endpoint (its lists are per repository); Bitbucket Data Center does";
200
201pub(crate) fn is_fatal(error: &Error) -> bool {
203 matches!(
204 error,
205 Error::Unauthorized { .. } | Error::RateLimited { .. } | Error::Http(_)
206 )
207}
208
209pub(crate) fn clone_url(integration: &crate::Integration, project: &str) -> String {
211 crate::spec::web_base(integration)
212 .map(|base| format!("{base}/{project}.git"))
213 .unwrap_or_default()
214}
215
216#[derive(Default)]
219pub(crate) struct Collector {
220 prs: Vec<AccountPr>,
221 issues: Vec<AccountIssue>,
222 notes: Vec<String>,
223 cut: bool,
225}
226
227impl Collector {
228 pub(crate) fn note(&mut self, text: impl Into<String>) {
229 self.notes.push(text.into());
230 }
231
232 pub(crate) fn cut(&mut self, note: impl Into<String>) {
234 self.cut = true;
235 self.notes.push(note.into());
236 }
237
238 pub(crate) fn failed(&mut self, what: &str, error: Error) -> Result<()> {
241 if is_fatal(&error) {
242 return Err(error);
243 }
244 self.notes.push(format!("{what}: {error}"));
245 Ok(())
246 }
247
248 pub(crate) fn add_pr(&mut self, row: AccountPr) {
251 let seen = self
252 .prs
253 .iter_mut()
254 .find(|p| p.project == row.project && p.pr.number == row.pr.number);
255 match seen {
256 Some(old) => {
257 old.pr.review_requested |= row.pr.review_requested;
258 for reviewer in row.pr.reviewers {
259 if !old.pr.reviewers.contains(&reviewer) {
260 old.pr.reviewers.push(reviewer);
261 }
262 }
263 }
264 None => self.prs.push(row),
265 }
266 }
267
268 pub(crate) fn add_issue(&mut self, row: AccountIssue) {
269 let seen = self
270 .issues
271 .iter()
272 .any(|i| i.project == row.project && i.issue.number == row.issue.number);
273 if !seen {
274 self.issues.push(row);
275 }
276 }
277
278 pub(crate) fn finish(mut self, query: &AccountQuery) -> AccountItems {
279 let limit = query.row_limit();
280 match NamespaceFilter::new(&query.namespaces, query.namespaces_regex) {
283 Ok(filter) if filter.is_empty() => {}
284 Ok(filter) => {
285 self.prs.retain(|p| filter.matches(&p.project));
286 self.issues.retain(|i| filter.matches(&i.project));
287 }
288 Err(why) => {
289 self.prs.clear();
290 self.issues.clear();
291 self.notes
292 .push(format!("invalid namespace expression {why}"));
293 }
294 }
295 if !query.include_drafts {
296 self.prs.retain(|p| p.pr.state != PullRequestState::Draft);
297 }
298 self.prs
300 .sort_by(|a, b| b.pr.updated_at.cmp(&a.pr.updated_at));
301 self.issues
302 .sort_by(|a, b| b.issue.updated_at.cmp(&a.issue.updated_at));
303 let mut truncated = self.cut;
304 if self.prs.len() > limit {
305 let more = self.prs.len() - limit;
306 self.prs.truncate(limit);
307 self.notes.push(format!(
308 "{more} more pull/merge requests are not listed (limit {limit})"
309 ));
310 truncated = true;
311 }
312 if self.issues.len() > limit {
313 let more = self.issues.len() - limit;
314 self.issues.truncate(limit);
315 self.notes
316 .push(format!("{more} more issues are not listed (limit {limit})"));
317 truncated = true;
318 }
319 AccountItems {
320 prs: self.prs,
321 issues: self.issues,
322 truncated,
323 notes: self.notes,
324 }
325 }
326}
327
328pub(crate) struct Paging<'a> {
330 pub size_param: &'a str,
332 pub page_size: usize,
333 pub max_pages: usize,
334 pub max_rows: usize,
336}
337
338pub(crate) async fn get_rows<T>(
341 transport: &dyn HttpTransport,
342 request: &(dyn Fn(String) -> HttpRequest + Sync),
343 url: &str,
344 paging: &Paging<'_>,
345 what: &str,
346 rows: &(dyn Fn(&HttpResponse) -> Result<Vec<T>> + Sync),
347) -> Result<Vec<T>> {
348 let sep = if url.contains('?') { '&' } else { '?' };
349 let mut out = Vec::new();
350 for page in 1..=paging.max_pages {
351 let full = format!(
352 "{url}{sep}{}={}&page={page}",
353 paging.size_param, paging.page_size
354 );
355 let response = transport.send(request(full)).await?;
356 response.error_for_status(what)?;
357 let page_rows = rows(&response)?;
358 let count = page_rows.len();
359 out.extend(page_rows);
360 if count < paging.page_size || out.len() >= paging.max_rows {
361 break;
362 }
363 }
364 Ok(out)
365}