mit_commit_message_lints/mit/lib/
authors.rs

1use std::{
2    collections::{btree_map::IntoIter, BTreeMap, HashSet},
3    convert::TryFrom,
4};
5
6use crate::mit::lib::{
7    author::Author,
8    errors::{DeserializeAuthorsError, SerializeAuthorsError},
9};
10
11/// Collection of authors
12#[derive(Debug, Eq, PartialEq, Clone, Default)]
13pub struct Authors<'a> {
14    /// A btree of the authors
15    pub authors: BTreeMap<String, Author<'a>>,
16}
17
18impl<'a> Authors<'a> {
19    /// From a list of initials get te ones that aren't in our config
20    #[must_use]
21    pub fn missing_initials(&'a self, authors_initials: Vec<&'a str>) -> Vec<&'a str> {
22        let configured: HashSet<_> = self.authors.keys().map(String::as_str).collect();
23        let from_cli: HashSet<_> = authors_initials.into_iter().collect();
24        from_cli.difference(&configured).copied().collect()
25    }
26
27    /// Create a new author collection
28    #[must_use]
29    pub const fn new(authors: BTreeMap<String, Author<'a>>) -> Self {
30        Self { authors }
31    }
32
33    /// Get some authors by their initials
34    #[must_use]
35    pub fn get(&self, author_initials: &'a [&'a str]) -> Vec<&'a Author<'_>> {
36        author_initials
37            .iter()
38            .filter_map(|initial| self.authors.get(*initial))
39            .collect()
40    }
41
42    /// Merge two lists of authors
43    ///
44    /// This is used if the user has a author config file, and the authors are
45    /// also saved in the vcs config
46    #[must_use]
47    pub fn merge(&self, authors: &Self) -> Self {
48        Self {
49            authors: authors
50                .authors
51                .iter()
52                .fold(self.authors.clone(), |mut acc, (key, value)| {
53                    acc.insert(key.clone(), value.clone());
54                    acc
55                }),
56        }
57    }
58
59    /// Generate an example authors list
60    ///
61    /// Used to show the user what their config file might look like
62    #[must_use]
63    pub fn example() -> Self {
64        let mut store = BTreeMap::new();
65        store.insert(
66            "ae".into(),
67            Author::new("Anyone Else".into(), "anyone@example.com".into(), None),
68        );
69        store.insert(
70            "se".into(),
71            Author::new("Someone Else".into(), "someone@example.com".into(), None),
72        );
73        store.insert(
74            "bt".into(),
75            Author::new(
76                "Billie Thompson".into(),
77                "billie@example.com".into(),
78                Some("0A46826A".into()),
79            ),
80        );
81        Self::new(store)
82    }
83}
84
85impl<'a> IntoIterator for Authors<'a> {
86    type IntoIter = IntoIter<String, Author<'a>>;
87    type Item = (String, Author<'a>);
88
89    fn into_iter(self) -> Self::IntoIter {
90        self.authors.into_iter()
91    }
92}
93
94impl<'a> TryFrom<&'a str> for Authors<'a> {
95    type Error = DeserializeAuthorsError;
96
97    fn try_from(input: &str) -> std::result::Result<Self, Self::Error> {
98        serde_yaml::from_str(input)
99            .or_else(|yaml_error| {
100                toml::from_str(input).map_err(|toml_error| {
101                    DeserializeAuthorsError::new(input, &yaml_error, &toml_error)
102                })
103            })
104            .map(Self::new)
105    }
106}
107
108impl TryFrom<String> for Authors<'_> {
109    type Error = DeserializeAuthorsError;
110
111    fn try_from(input: String) -> std::result::Result<Self, Self::Error> {
112        serde_yaml::from_str(&input)
113            .or_else(|yaml_error| {
114                toml::from_str(&input).map_err(|toml_error| {
115                    DeserializeAuthorsError::new(&input, &yaml_error, &toml_error)
116                })
117            })
118            .map(Authors::new)
119    }
120}
121
122impl<'a> TryFrom<Authors<'a>> for String {
123    type Error = SerializeAuthorsError;
124
125    fn try_from(value: Authors<'a>) -> Result<Self, Self::Error> {
126        toml::to_string(&value.authors).map_err(SerializeAuthorsError)
127    }
128}