gitpoulpi_hosting/conversation/
identity.rs1use serde::{Deserialize, Serialize};
4
5use super::model::{Actor, ActorKind};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum IdentityKind {
10 PersonalToken,
11 ProjectOrGroupBot,
13 AppBot,
15 LocalAuthor,
16 Unknown,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(tag = "source", rename_all = "snake_case")]
22pub enum TokenSource {
23 Profile { id: String },
25 RepoTokenCommand,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct PostingIdentity {
31 pub login: Option<String>,
33 pub display: String,
35 pub kind: IdentityKind,
36 pub source: TokenSource,
37}
38
39pub const UNKNOWN_APP_BOT: &str = "the GitHub App bot";
41
42impl PostingIdentity {
43 pub fn new(login: Option<String>, kind: IdentityKind, source: TokenSource) -> Self {
44 let login = login
45 .map(|l| l.trim().to_string())
46 .filter(|l| !l.is_empty());
47 let display = match (&login, kind) {
48 (Some(l), _) => l.clone(),
49 (None, IdentityKind::AppBot) => UNKNOWN_APP_BOT.to_string(),
50 (None, _) => String::new(),
51 };
52 Self {
53 login,
54 display,
55 kind,
56 source,
57 }
58 }
59
60 pub fn authored(&self, actor: &Actor) -> Option<bool> {
66 let login = self.login.as_deref()?;
67 let same = login.eq_ignore_ascii_case(&actor.login);
68 Some(match self.kind {
69 IdentityKind::AppBot => same && actor.kind == ActorKind::Bot,
70 _ => same,
71 })
72 }
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 fn bot_identity(login: Option<&str>) -> PostingIdentity {
80 PostingIdentity::new(
81 login.map(str::to_string),
82 IdentityKind::AppBot,
83 TokenSource::RepoTokenCommand,
84 )
85 }
86
87 #[test]
88 fn authored_compares_logins_case_insensitively() {
89 let me = PostingIdentity::new(
90 Some("Octo".into()),
91 IdentityKind::PersonalToken,
92 TokenSource::Profile { id: "gh".into() },
93 );
94 assert_eq!(
95 me.authored(&Actor::new("octo", "Octo", ActorKind::User)),
96 Some(true)
97 );
98 assert_eq!(
99 me.authored(&Actor::new("other", "Other", ActorKind::User)),
100 Some(false)
101 );
102 }
103
104 #[test]
105 fn an_app_bot_needs_a_bot_author() {
106 let me = bot_identity(Some("my-app[bot]"));
107 assert_eq!(
108 me.authored(&Actor::new("My-App[bot]", "x", ActorKind::Bot)),
109 Some(true)
110 );
111 assert_eq!(
112 me.authored(&Actor::new("my-app[bot]", "x", ActorKind::User)),
113 Some(false)
114 );
115 }
116
117 #[test]
118 fn an_unknown_login_cannot_tell() {
119 let me = bot_identity(None);
120 assert_eq!(me.display, UNKNOWN_APP_BOT);
121 assert_eq!(
122 me.authored(&Actor::new("a[bot]", "a", ActorKind::Bot)),
123 None
124 );
125 assert_eq!(bot_identity(Some(" ")).login, None);
126 }
127}