use std::sync::{Arc, OnceLock};
use crate::{Error, Result};
pub const ASSIGNMENT_BLOCKED: &str = "assignment is blocked for this repository";
#[async_trait::async_trait]
pub trait RepoScopes: Send + Sync {
fn assignment_blocked(&self, integration_id: &str, project: &str) -> bool;
async fn token(
&self,
integration_id: &str,
project: &str,
refresh: bool,
) -> Option<Result<String>>;
fn acts_as_bot(&self, integration_id: &str, project: &str) -> bool;
fn post_as(&self, _integration_id: &str, _project: &str) -> Option<String> {
None
}
fn learned_login(&self, _integration_id: &str, _project: &str) -> Option<String> {
None
}
fn learn_login(&self, _integration_id: &str, _project: &str, _login: &str) {}
}
static SCOPES: OnceLock<Arc<dyn RepoScopes>> = OnceLock::new();
pub fn install(scopes: Arc<dyn RepoScopes>) {
let _ = SCOPES.set(scopes);
}
pub(crate) fn installed() -> Option<&'static Arc<dyn RepoScopes>> {
SCOPES.get()
}
pub fn assignment_blocked(integration_id: &str, project: &str) -> bool {
installed().is_some_and(|s| s.assignment_blocked(integration_id, project))
}
pub fn acts_as_bot(integration_id: &str, project: &str) -> bool {
installed().is_some_and(|s| s.acts_as_bot(integration_id, project))
}
pub fn post_as(integration_id: &str, project: &str) -> Option<String> {
installed()
.and_then(|s| s.post_as(integration_id, project))
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty())
}
pub fn learned_login(integration_id: &str, project: &str) -> Option<String> {
installed().and_then(|s| s.learned_login(integration_id, project))
}
pub fn learn_login(integration_id: &str, project: &str, login: &str) {
if let Some(s) = installed() {
s.learn_login(integration_id, project, login);
}
}
#[cfg_attr(not(feature = "hosting"), allow(dead_code))]
pub(crate) fn refuse() -> Error {
Error::AssignmentBlocked
}
pub fn is_app_installation_token(token: &str) -> bool {
token.trim().starts_with("ghs_")
}
#[cfg_attr(not(feature = "github"), allow(dead_code))]
pub(crate) fn github_project_of(url: &str) -> Option<String> {
let path = url.split(['?', '#']).next()?;
let (_, rest) = path.split_once("/repos/")?;
let mut parts = rest.split('/');
let owner = parts.next().filter(|p| !p.is_empty())?;
let repo = parts.next().filter(|p| !p.is_empty())?;
Some(format!("{owner}/{repo}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_project_of_an_api_url_is_owner_and_repo() {
assert_eq!(
github_project_of("https://api.example.com/repos/acme/app/issues/3/comments?x=1"),
Some("acme/app".to_string())
);
assert_eq!(github_project_of("https://api.example.com/user"), None);
assert_eq!(
github_project_of("https://api.example.com/repos/acme"),
None
);
}
#[test]
fn an_installation_token_is_recognised_by_its_prefix() {
assert!(is_app_installation_token("ghs_abc"));
assert!(!is_app_installation_token("ghp_abc"));
assert!(!is_app_installation_token("github_pat_abc"));
}
}