1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use std::{
    collections::BTreeMap,
    fmt::{Debug, Display, Formatter},
    iter::Rev,
    vec::IntoIter,
};

use itertools::Itertools;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::{collect_repo_events, collect_user_events, Result};

pub mod query;

#[derive(Default, Serialize, Deserialize)]
pub struct Authors {
    inner: BTreeMap<String, CommitAuthor>,
}

#[derive(Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AuthorQuery {
    Nothing,
    User(String),
    Repo(String, String),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CommitAuthor {
    pub name: String,
    pub email: String,
    pub count: usize,
}

impl Authors {
    pub fn clear(&mut self) {
        self.inner.clear()
    }
    pub fn get(&self, name: &str) -> Option<&CommitAuthor> {
        self.inner.get(name)
    }
    pub fn insert(&mut self, author: CommitAuthor) {
        match self.inner.get_mut(&author.name) {
            Some(s) => s.count += author.count,
            None => self.insert_force(author),
        }
    }
    pub fn insert_force(&mut self, author: CommitAuthor) {
        self.inner.insert(author.name.clone(), author);
    }
    pub fn items(&self) -> Vec<CommitAuthor> {
        self.into_iter().cloned().collect()
    }
    pub fn count_commits(&self) -> usize {
        self.inner.iter().map(|v| v.1.count).sum()
    }
}

impl Debug for Authors {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_list().entries(self.items().iter()).finish()
    }
}
impl Display for Authors {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_list().entries(self.items().iter()).finish()
    }
}

impl<'i> IntoIterator for &'i Authors {
    type Item = &'i CommitAuthor;
    type IntoIter = Rev<IntoIter<&'i CommitAuthor>>;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.values().sorted_by_key(|v| v.count).rev()
    }
}