use arks_oid::Oid;
use arks_repo::Repository;
use std::sync::{Arc, OnceLock, RwLock};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefUpdate {
pub name: String,
pub old: Oid,
pub new: Oid,
}
impl RefUpdate {
pub fn is_create(&self) -> bool {
self.old.as_bytes().iter().all(|b| *b == 0)
}
pub fn is_delete(&self) -> bool {
self.new.as_bytes().iter().all(|b| *b == 0)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Pusher {
pub transport: &'static str,
pub verified_user: Option<String>,
pub authorization: Option<String>,
}
impl Pusher {
pub fn local() -> Self {
Self {
transport: "local",
..Self::default()
}
}
pub fn ssh() -> Self {
Self {
transport: "ssh",
..Self::default()
}
}
}
pub trait PushPolicy: Send + Sync {
fn check(
&self,
repo: &Repository,
pusher: &Pusher,
updates: &[RefUpdate],
) -> Vec<Option<String>>;
}
fn slot() -> &'static RwLock<Option<Arc<dyn PushPolicy>>> {
static SLOT: OnceLock<RwLock<Option<Arc<dyn PushPolicy>>>> = OnceLock::new();
SLOT.get_or_init(|| RwLock::new(None))
}
pub fn install_push_policy(policy: Option<Arc<dyn PushPolicy>>) {
if let Ok(mut g) = slot().write() {
*g = policy;
}
}
pub fn installed_push_policy() -> Option<Arc<dyn PushPolicy>> {
slot().read().ok().and_then(|g| g.clone())
}
pub(crate) fn verdicts(
policy: Option<&dyn PushPolicy>,
repo: &Repository,
pusher: &Pusher,
updates: &[RefUpdate],
) -> Vec<Option<String>> {
let Some(policy) = policy else {
return vec![None; updates.len()];
};
let out = policy.check(repo, pusher, updates);
if out.len() != updates.len() {
return vec![Some("push policy error".into()); updates.len()];
}
out.into_iter()
.map(|v| v.map(|r| r.replace(['\n', '\r'], " ")))
.collect()
}