use serde::{Deserialize, Serialize};
use super::model::{Actor, ActorKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IdentityKind {
PersonalToken,
ProjectOrGroupBot,
AppBot,
LocalAuthor,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum TokenSource {
Profile { id: String },
RepoTokenCommand,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostingIdentity {
pub login: Option<String>,
pub display: String,
pub kind: IdentityKind,
pub source: TokenSource,
}
pub const UNKNOWN_APP_BOT: &str = "the GitHub App bot";
impl PostingIdentity {
pub fn new(login: Option<String>, kind: IdentityKind, source: TokenSource) -> Self {
let login = login
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty());
let display = match (&login, kind) {
(Some(l), _) => l.clone(),
(None, IdentityKind::AppBot) => UNKNOWN_APP_BOT.to_string(),
(None, _) => String::new(),
};
Self {
login,
display,
kind,
source,
}
}
pub fn authored(&self, actor: &Actor) -> Option<bool> {
let login = self.login.as_deref()?;
let same = login.eq_ignore_ascii_case(&actor.login);
Some(match self.kind {
IdentityKind::AppBot => same && actor.kind == ActorKind::Bot,
_ => same,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bot_identity(login: Option<&str>) -> PostingIdentity {
PostingIdentity::new(
login.map(str::to_string),
IdentityKind::AppBot,
TokenSource::RepoTokenCommand,
)
}
#[test]
fn authored_compares_logins_case_insensitively() {
let me = PostingIdentity::new(
Some("Octo".into()),
IdentityKind::PersonalToken,
TokenSource::Profile { id: "gh".into() },
);
assert_eq!(
me.authored(&Actor::new("octo", "Octo", ActorKind::User)),
Some(true)
);
assert_eq!(
me.authored(&Actor::new("other", "Other", ActorKind::User)),
Some(false)
);
}
#[test]
fn an_app_bot_needs_a_bot_author() {
let me = bot_identity(Some("my-app[bot]"));
assert_eq!(
me.authored(&Actor::new("My-App[bot]", "x", ActorKind::Bot)),
Some(true)
);
assert_eq!(
me.authored(&Actor::new("my-app[bot]", "x", ActorKind::User)),
Some(false)
);
}
#[test]
fn an_unknown_login_cannot_tell() {
let me = bot_identity(None);
assert_eq!(me.display, UNKNOWN_APP_BOT);
assert_eq!(
me.authored(&Actor::new("a[bot]", "a", ActorKind::Bot)),
None
);
assert_eq!(bot_identity(Some(" ")).login, None);
}
}