Skip to main content

gitfox_client/models/
principal.rs

1use serde::{Deserialize, Serialize};
2
3/// A user or service account, as GitFox reports it inside other resources.
4///
5/// Every field is optional: which ones an instance populates varies, and no
6/// command should fail because a display name was absent.
7#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
8pub struct Principal {
9    #[serde(default)]
10    pub id: Option<i64>,
11    #[serde(default)]
12    pub uid: Option<String>,
13    #[serde(default)]
14    pub display_name: Option<String>,
15    #[serde(default)]
16    pub email: Option<String>,
17}
18
19impl Principal {
20    /// The most useful name available, preferring the login over the full name
21    /// because that is what a caller would type back into `--author`.
22    pub fn label(&self) -> String {
23        self.uid
24            .clone()
25            .or_else(|| self.display_name.clone())
26            .or_else(|| self.email.clone())
27            .unwrap_or_else(|| "(unknown)".to_string())
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn label_prefers_the_login_then_the_display_name() {
37        let full = Principal {
38            uid: Some("whw".into()),
39            display_name: Some("Haowei".into()),
40            ..Default::default()
41        };
42        assert_eq!(full.label(), "whw");
43
44        let named = Principal {
45            display_name: Some("Haowei".into()),
46            ..Default::default()
47        };
48        assert_eq!(named.label(), "Haowei");
49        assert_eq!(Principal::default().label(), "(unknown)");
50    }
51}