#![cfg_attr(
not(all(
feature = "github",
feature = "gitlab",
feature = "gitea",
feature = "azure-devops",
feature = "bitbucket",
feature = "gerrit"
)),
allow(dead_code)
)]
use serde::{Deserialize, Serialize};
use crate::http::{HttpRequest, HttpResponse, HttpTransport};
use crate::model::{IssueSummary, PullRequestState, PullRequestSummary};
use crate::{Error, Result};
mod cache;
#[cfg(feature = "gitea")]
pub(crate) mod gitea;
#[cfg(feature = "github")]
pub(crate) mod github;
#[cfg(feature = "gitlab")]
pub(crate) mod gitlab;
mod namespace;
#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
mod tests;
#[cfg(all(test, feature = "github", feature = "gitlab", feature = "gitea"))]
mod tests_namespaces;
#[cfg(all(
test,
feature = "github",
feature = "gitlab",
feature = "gitea",
feature = "azure-devops",
feature = "bitbucket",
feature = "gerrit"
))]
mod tests_wave2;
pub use cache::{
cache_path, AccountCache, CachedAccount, ACCOUNT_CACHE_FILE, ACCOUNT_TTL, ACCOUNT_TTL_SECS,
};
pub use namespace::{compile as compile_namespace_regex, first_regex_error, NamespaceFilter};
pub const DEFAULT_LIMIT: usize = 300;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountQuery {
pub review_requests: bool,
pub open_requests: bool,
pub assigned_issues: bool,
pub include_drafts: bool,
pub namespaces: Vec<String>,
#[serde(default)]
pub namespaces_regex: bool,
pub limit: usize,
}
impl AccountQuery {
pub fn row_limit(&self) -> usize {
if self.limit == 0 {
DEFAULT_LIMIT
} else {
self.limit
}
}
pub fn search_namespaces(&self) -> &[String] {
if self.namespaces_regex {
&[]
} else {
&self.namespaces
}
}
pub fn is_empty(&self) -> bool {
!(self.review_requests || self.open_requests || self.assigned_issues)
}
pub fn fingerprint(&self) -> String {
let mut spaces: Vec<String> = self.namespaces.iter().map(|n| n.to_lowercase()).collect();
spaces.sort();
let text = format!(
"r{}o{}i{}d{}l{}x{}|{}",
self.review_requests as u8,
self.open_requests as u8,
self.assigned_issues as u8,
self.include_drafts as u8,
self.row_limit(),
self.namespaces_regex as u8,
spaces.join(",")
);
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for b in text.bytes() {
hash ^= u64::from(b);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
format!("{hash:016x}")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountPr {
pub project: String,
#[serde(default)]
pub clone_url: String,
#[serde(flatten)]
pub pr: PullRequestSummary,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountIssue {
pub project: String,
#[serde(default)]
pub clone_url: String,
#[serde(flatten)]
pub issue: IssueSummary,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountItems {
#[serde(default)]
pub prs: Vec<AccountPr>,
#[serde(default)]
pub issues: Vec<AccountIssue>,
#[serde(default)]
pub truncated: bool,
#[serde(default)]
pub notes: Vec<String>,
}
pub fn supports(kind: crate::IntegrationKind) -> bool {
use gitpoulpi_config::ApiFamily;
match kind.family() {
ApiFamily::Github
| ApiFamily::Gitlab
| ApiFamily::Gitea
| ApiFamily::AzureDevops
| ApiFamily::Gerrit => true,
ApiFamily::Bitbucket => kind == crate::IntegrationKind::BitbucketDataCenter,
_ => false,
}
}
pub const NO_BITBUCKET_CLOUD: &str = "Bitbucket Cloud has no account-wide pull request \
endpoint (its lists are per repository); Bitbucket Data Center does";
pub(crate) fn is_fatal(error: &Error) -> bool {
matches!(
error,
Error::Unauthorized { .. } | Error::RateLimited { .. } | Error::Http(_)
)
}
pub(crate) fn clone_url(integration: &crate::Integration, project: &str) -> String {
crate::spec::web_base(integration)
.map(|base| format!("{base}/{project}.git"))
.unwrap_or_default()
}
#[derive(Default)]
pub(crate) struct Collector {
prs: Vec<AccountPr>,
issues: Vec<AccountIssue>,
notes: Vec<String>,
cut: bool,
}
impl Collector {
pub(crate) fn note(&mut self, text: impl Into<String>) {
self.notes.push(text.into());
}
pub(crate) fn cut(&mut self, note: impl Into<String>) {
self.cut = true;
self.notes.push(note.into());
}
pub(crate) fn failed(&mut self, what: &str, error: Error) -> Result<()> {
if is_fatal(&error) {
return Err(error);
}
self.notes.push(format!("{what}: {error}"));
Ok(())
}
pub(crate) fn add_pr(&mut self, row: AccountPr) {
let seen = self
.prs
.iter_mut()
.find(|p| p.project == row.project && p.pr.number == row.pr.number);
match seen {
Some(old) => {
old.pr.review_requested |= row.pr.review_requested;
for reviewer in row.pr.reviewers {
if !old.pr.reviewers.contains(&reviewer) {
old.pr.reviewers.push(reviewer);
}
}
}
None => self.prs.push(row),
}
}
pub(crate) fn add_issue(&mut self, row: AccountIssue) {
let seen = self
.issues
.iter()
.any(|i| i.project == row.project && i.issue.number == row.issue.number);
if !seen {
self.issues.push(row);
}
}
pub(crate) fn finish(mut self, query: &AccountQuery) -> AccountItems {
let limit = query.row_limit();
match NamespaceFilter::new(&query.namespaces, query.namespaces_regex) {
Ok(filter) if filter.is_empty() => {}
Ok(filter) => {
self.prs.retain(|p| filter.matches(&p.project));
self.issues.retain(|i| filter.matches(&i.project));
}
Err(why) => {
self.prs.clear();
self.issues.clear();
self.notes
.push(format!("invalid namespace expression {why}"));
}
}
if !query.include_drafts {
self.prs.retain(|p| p.pr.state != PullRequestState::Draft);
}
self.prs
.sort_by(|a, b| b.pr.updated_at.cmp(&a.pr.updated_at));
self.issues
.sort_by(|a, b| b.issue.updated_at.cmp(&a.issue.updated_at));
let mut truncated = self.cut;
if self.prs.len() > limit {
let more = self.prs.len() - limit;
self.prs.truncate(limit);
self.notes.push(format!(
"{more} more pull/merge requests are not listed (limit {limit})"
));
truncated = true;
}
if self.issues.len() > limit {
let more = self.issues.len() - limit;
self.issues.truncate(limit);
self.notes
.push(format!("{more} more issues are not listed (limit {limit})"));
truncated = true;
}
AccountItems {
prs: self.prs,
issues: self.issues,
truncated,
notes: self.notes,
}
}
}
pub(crate) struct Paging<'a> {
pub size_param: &'a str,
pub page_size: usize,
pub max_pages: usize,
pub max_rows: usize,
}
pub(crate) async fn get_rows<T>(
transport: &dyn HttpTransport,
request: &(dyn Fn(String) -> HttpRequest + Sync),
url: &str,
paging: &Paging<'_>,
what: &str,
rows: &(dyn Fn(&HttpResponse) -> Result<Vec<T>> + Sync),
) -> Result<Vec<T>> {
let sep = if url.contains('?') { '&' } else { '?' };
let mut out = Vec::new();
for page in 1..=paging.max_pages {
let full = format!(
"{url}{sep}{}={}&page={page}",
paging.size_param, paging.page_size
);
let response = transport.send(request(full)).await?;
response.error_for_status(what)?;
let page_rows = rows(&response)?;
let count = page_rows.len();
out.extend(page_rows);
if count < paging.page_size || out.len() >= paging.max_rows {
break;
}
}
Ok(out)
}