Skip to content

g1t/services/repos/src/contributors.rs

159 lines6,790 bytesCodeBlame
1//! Who made a repository: the authors of the commits on its default branch,
2//! each matched to their account by an address they confirmed (or their
3//! noreply address), g1t as itself, and anyone else by the name on their
4//! commits. Several addresses of one account count as one contributor.
5
6use std::collections::{BTreeMap, HashMap};
7
8use g1t_contracts::about::{Contributor, ContributorKind, MAX_CONTRIBUTOR_WEEKS, MAX_CONTRIBUTORS, WeekCommits, next_week, week_of};
9use g1t_contracts::accounts::EmailOwner;
10
11/// The address g1t's own commits carry.
12pub const G1T_EMAIL: &str = "g1t@users.noreply.g1t.sh";
13
14/// One commit's author, as history gives it.
15#[derive(Clone, Debug)]
16pub struct Authored {
17 pub name: String,
18 pub email: String,
19 /// RFC 3339.
20 pub at: String,
21}
22
23/// Whether a commit's author is g1t itself.
24pub fn is_g1t(author: &Authored) -> bool {
25 author.email.eq_ignore_ascii_case(G1T_EMAIL)
26}
27
28#[derive(Default)]
29struct Tally {
30 kind: Option<ContributorKind>,
31 name: String,
32 username: Option<String>,
33 avatar: Option<String>,
34 commits: u32,
35 first_at: String,
36 last_at: String,
37 weeks: BTreeMap<String, u32>,
38}
39
40/// The contributors, most commits first (then by name), at most
41/// `MAX_CONTRIBUTORS`, the most active `MAX_CONTRIBUTOR_WEEKS` with their
42/// weeks; how many there are; and every commit by week, oldest first, with
43/// the empty weeks between.
44pub fn tally(commits: &[Authored], owners: &HashMap<String, EmailOwner>) -> (Vec<Contributor>, u32, Vec<WeekCommits>) {
45 let mut by_key: HashMap<String, Tally> = HashMap::new();
46 let mut all_weeks: BTreeMap<String, u32> = BTreeMap::new();
47 for commit in commits {
48 let email = commit.email.trim().to_ascii_lowercase();
49 let (key, kind, name, username, avatar) = if is_g1t(commit) {
50 ("g1t".to_owned(), ContributorKind::G1t, "g1t".to_owned(), None, None)
51 } else if let Some(owner) = owners.get(&email) {
52 (format!("user:{}", owner.id), ContributorKind::User, owner.username.clone(), Some(owner.username.clone()), owner.avatar.clone())
53 } else {
54 let key = if email.is_empty() { format!("name:{}", commit.name.trim().to_lowercase()) } else { format!("email:{email}") };
55 (key, ContributorKind::Author, commit.name.trim().to_owned(), None, None)
56 };
57 let tally = by_key.entry(key).or_default();
58 if tally.kind.is_none() {
59 *tally = Tally { kind: Some(kind), name, username, avatar, first_at: commit.at.clone(), last_at: commit.at.clone(), ..Tally::default() };
60 }
61 tally.commits += 1;
62 if commit.at < tally.first_at {
63 tally.first_at = commit.at.clone();
64 }
65 if commit.at > tally.last_at {
66 tally.last_at = commit.at.clone();
67 }
68 if let Some(week) = week_of(&commit.at) {
69 *tally.weeks.entry(week.clone()).or_default() += 1;
70 *all_weeks.entry(week).or_default() += 1;
71 }
72 }
73 let total = by_key.len() as u32;
74 let mut tallies: Vec<Tally> = by_key.into_values().collect();
75 tallies.sort_by(|a, b| b.commits.cmp(&a.commits).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())));
76 tallies.truncate(MAX_CONTRIBUTORS);
77 let contributors = tallies
78 .into_iter()
79 .enumerate()
80 .map(|(rank, tally)| Contributor {
81 kind: tally.kind.unwrap_or(ContributorKind::Author),
82 name: tally.name,
83 username: tally.username,
84 avatar: tally.avatar,
85 commits: tally.commits,
86 first_at: tally.first_at,
87 last_at: tally.last_at,
88 weeks: if rank < MAX_CONTRIBUTOR_WEEKS {
89 tally.weeks.into_iter().map(|(week, commits)| WeekCommits { week, commits }).collect()
90 } else {
91 Vec::new()
92 },
93 })
94 .collect();
95 (contributors, total, filled(&all_weeks))
96}
97
98/// Every week from the first to the last, with none for those without.
99fn filled(weeks: &BTreeMap<String, u32>) -> Vec<WeekCommits> {
100 let (Some(first), Some(last)) = (weeks.keys().next(), weeks.keys().next_back()) else {
101 return Vec::new();
102 };
103 let mut out = Vec::new();
104 let mut week = first.clone();
105 // At most twenty years of weeks, whatever the dates say.
106 while week <= *last && out.len() < 1_100 {
107 out.push(WeekCommits { commits: weeks.get(&week).copied().unwrap_or(0), week: week.clone() });
108 match next_week(&week) {
109 Some(next) => week = next,
110 None => break,
111 }
112 }
113 out
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 fn authored(name: &str, email: &str, at: &str) -> Authored {
121 Authored { name: name.into(), email: email.into(), at: at.into() }
122 }
123
124 #[test]
125 fn authors_are_matched_merged_and_ranked() {
126 let commits = vec![
127 authored("Ada", "ada@example.com", "2026-10-07T10:00:00Z"),
128 authored("Ada L", "ADA@work.example", "2026-09-30T10:00:00Z"),
129 authored("g1t", G1T_EMAIL, "2026-10-06T10:00:00Z"),
130 authored("g1t", G1T_EMAIL, "2026-10-01T10:00:00Z"),
131 authored("g1t", G1T_EMAIL, "2026-09-20T10:00:00Z"),
132 authored("Sam", "sam@example.com", "2026-09-16T10:00:00Z"),
133 ];
134 let ada = EmailOwner { id: "usr_ada".into(), username: "ada".into(), avatar: Some("abc".into()) };
135 let owners = HashMap::from([("ada@example.com".to_owned(), ada.clone()), ("ada@work.example".to_owned(), ada)]);
136 let (contributors, total, weeks) = tally(&commits, &owners);
137 assert_eq!(total, 3);
138 assert_eq!(contributors[0].kind, ContributorKind::G1t);
139 assert_eq!(contributors[0].commits, 3);
140 assert_eq!(contributors[1].username.as_deref(), Some("ada"));
141 assert_eq!(contributors[1].commits, 2, "both of Ada's addresses");
142 assert_eq!(contributors[1].first_at, "2026-09-30T10:00:00Z");
143 assert_eq!(contributors[1].last_at, "2026-10-07T10:00:00Z");
144 assert_eq!(contributors[1].avatar.as_deref(), Some("abc"));
145 assert_eq!(contributors[2].kind, ContributorKind::Author);
146 assert_eq!(contributors[2].name, "Sam");
147 // Weeks of 2026-09-14 through 2026-10-05, none skipped.
148 let named: Vec<(&str, u32)> = weeks.iter().map(|week| (week.week.as_str(), week.commits)).collect();
149 assert_eq!(named, vec![("2026-09-14", 2), ("2026-09-21", 0), ("2026-09-28", 2), ("2026-10-05", 2)]);
150 assert_eq!(contributors[1].weeks.len(), 2);
151 }
152
153 #[test]
154 fn no_history_is_no_one() {
155 let (contributors, total, weeks) = tally(&[], &HashMap::new());
156 assert!(contributors.is_empty() && weeks.is_empty());
157 assert_eq!(total, 0);
158 }
159}