1use std::path::{Path, PathBuf};
13
14pub use fallow_output::{RoutingFacts, RoutingUnit};
15use rustc_hash::FxHashSet;
16
17use fallow_config::ResolvedConfig;
18use fallow_engine::churn::{ChurnResult, ChurnWindowUnit, SinceDuration, analyze_churn_cached};
19use fallow_engine::health::ownership::{
20 ContributorId, OwnershipContext, OwnershipWithIdentities, compile_bot_globs,
21 compute_ownership_with_identities,
22};
23
24const AUDIT_CHURN_WINDOW_MONTHS: u64 = 12;
29
30#[must_use]
33pub fn audit_churn(root: &Path, config: &ResolvedConfig) -> Option<ChurnResult> {
34 let since = SinceDuration::relative(
35 AUDIT_CHURN_WINDOW_MONTHS,
36 ChurnWindowUnit::Months,
37 format!("{AUDIT_CHURN_WINDOW_MONTHS} months"),
38 );
39 analyze_churn_cached(root, &since, &config.cache_dir, config.no_cache).map(|(churn, _)| churn)
40}
41
42#[must_use]
47#[expect(
48 clippy::implicit_hasher,
49 reason = "callers always pass the audit changed-file FxHashSet; generalizing the hasher adds noise"
50)]
51pub fn compute_routing(
52 root: &Path,
53 config: &ResolvedConfig,
54 changed_files: &FxHashSet<PathBuf>,
55) -> RoutingFacts {
56 audit_churn(root, config).map_or_else(RoutingFacts::default, |churn| {
57 compute_routing_from_churn(root, config, changed_files, &churn)
58 })
59}
60
61#[must_use]
64#[expect(
65 clippy::implicit_hasher,
66 reason = "callers always pass the audit changed-file FxHashSet; generalizing the hasher adds noise"
67)]
68pub fn compute_routing_from_churn(
69 root: &Path,
70 config: &ResolvedConfig,
71 changed_files: &FxHashSet<PathBuf>,
72 churn_result: &ChurnResult,
73) -> RoutingFacts {
74 let ownership_cfg = &config.health.ownership;
75 let Ok(bot_globs) = compile_bot_globs(&ownership_cfg.bot_patterns) else {
76 return RoutingFacts::default();
77 };
78 let codeowners = crate::ownership::load_codeowners(root, config)
81 .ok()
82 .flatten();
83 let now_secs = churn_result.clock.epoch_secs();
86 let ctx = OwnershipContext {
87 author_pool: &churn_result.author_pool,
88 bot_globs: &bot_globs,
89 codeowners: codeowners.as_ref(),
90 email_mode: ownership_cfg.email_mode,
91 now_secs,
92 };
93
94 let reviewer = Reviewer {
98 ids: fallow_engine::repo_refs::current_user_identities(root),
99 email: fallow_engine::repo_refs::current_user_email(root),
100 };
101
102 let mut units: Vec<RoutingUnit> = changed_files
103 .iter()
104 .filter_map(|abs| route_one(abs, root, churn_result, &ctx, &reviewer))
105 .collect();
106 units.sort_by(|a, b| a.file.cmp(&b.file));
107 RoutingFacts { units }
108}
109
110fn expert_is_self(expert: &str, self_ids: &[String]) -> bool {
113 let normalized = expert.trim_start_matches('@').to_ascii_lowercase();
114 self_ids
115 .iter()
116 .any(|id| id.trim_start_matches('@').to_ascii_lowercase() == normalized)
117}
118
119struct Reviewer {
121 ids: Vec<String>,
123 email: Option<String>,
125}
126
127impl Reviewer {
128 fn is_contributor(&self, id: ContributorId<'_>, rendered: &str) -> bool {
131 expert_is_self(rendered, &self.ids)
132 || self
133 .email
134 .as_deref()
135 .is_some_and(|email| ContributorId::new(email).same_person(id))
136 }
137}
138
139fn select_experts(owned: &OwnershipWithIdentities<'_>, reviewer: &Reviewer) -> Vec<String> {
143 let metrics = &owned.metrics;
144 if let Some(owner) = &metrics.declared_owner {
145 if expert_is_self(owner, &reviewer.ids) {
146 return Vec::new();
147 }
148 return vec![owner.clone()];
149 }
150 let top = (&metrics.top_contributor, owned.top_contributor);
151 let reviewers = metrics
152 .suggested_reviewers
153 .iter()
154 .zip(owned.suggested_reviewers.iter().copied())
155 .take(2);
156 let mut expert: Vec<String> = Vec::new();
157 for (entry, id) in std::iter::once(top).chain(reviewers) {
158 if reviewer.is_contributor(id, &entry.identifier) || expert.contains(&entry.identifier) {
159 continue;
160 }
161 expert.push(entry.identifier.clone());
162 }
163 expert
164}
165
166fn route_one(
170 abs: &Path,
171 root: &Path,
172 churn_result: &ChurnResult,
173 ctx: &OwnershipContext<'_>,
174 reviewer: &Reviewer,
175) -> Option<RoutingUnit> {
176 let file_churn = churn_result.files.get(abs)?;
177 let relative = abs.strip_prefix(root).unwrap_or(abs);
178 let owned = compute_ownership_with_identities(file_churn, relative, ctx)?;
179 let expert = select_experts(&owned, reviewer);
182 if expert.is_empty() {
183 return None;
184 }
185
186 Some(RoutingUnit {
187 file: relative.to_string_lossy().replace('\\', "/"),
188 expert,
189 bus_factor_one: owned.metrics.bus_factor == 1,
190 })
191}
192
193#[cfg(test)]
194mod tests {
195 use fallow_engine::health::ownership::{ContributorId, OwnershipWithIdentities};
196 use fallow_output::{
197 ContributorEntry, ContributorIdentifierFormat, OwnershipMetrics, OwnershipState,
198 };
199
200 fn contributor(id: &str) -> ContributorEntry {
201 ContributorEntry {
202 identifier: id.to_string(),
203 format: ContributorIdentifierFormat::Handle,
204 share: 1.0,
205 stale_days: 1,
206 commits: 5,
207 }
208 }
209
210 fn metrics(declared: Option<&str>, bus_factor: u32) -> OwnershipMetrics {
211 OwnershipMetrics {
212 bus_factor,
213 contributor_count: 1,
214 top_contributor: contributor("alice"),
215 recent_contributors: vec![],
216 suggested_reviewers: vec![contributor("bob")],
217 declared_owner: declared.map(str::to_string),
218 unowned: None,
219 ownership_state: OwnershipState::Active,
220 drift: false,
221 drift_reason: None,
222 }
223 }
224
225 #[test]
226 fn current_reviewer_is_excluded_from_routing() {
227 let self_ids = vec![
228 "bart".to_string(),
229 "bart@waardenburg.dev".to_string(),
230 "Bart Waardenburg".to_string(),
231 ];
232 assert!(super::expert_is_self("bart", &self_ids));
235 assert!(super::expert_is_self("Bart", &self_ids));
236 assert!(super::expert_is_self("@bart", &self_ids));
237 assert!(super::expert_is_self("bart@waardenburg.dev", &self_ids));
238 assert!(!super::expert_is_self("alice", &self_ids));
240 assert!(!super::expert_is_self("@team/ui", &self_ids));
241 assert!(!super::expert_is_self("bart", &[]));
243 }
244
245 fn owned<'a>(
246 metrics: OwnershipMetrics,
247 top: &'a str,
248 reviewers: &[&'a str],
249 ) -> OwnershipWithIdentities<'a> {
250 OwnershipWithIdentities {
251 metrics,
252 top_contributor: ContributorId::new(top),
253 suggested_reviewers: reviewers.iter().copied().map(ContributorId::new).collect(),
254 }
255 }
256
257 fn reviewer(ids: &[&str], email: Option<&str>) -> super::Reviewer {
258 super::Reviewer {
259 ids: ids.iter().map(|id| (*id).to_string()).collect(),
260 email: email.map(str::to_string),
261 }
262 }
263
264 #[test]
265 fn declared_owner_wins() {
266 let owned = owned(
267 metrics(Some("@team/web"), 3),
268 "alice@x.test",
269 &["bob@x.test"],
270 );
271 assert_eq!(
272 super::select_experts(&owned, &reviewer(&[], None)),
273 vec!["@team/web".to_string()]
274 );
275 }
276
277 #[test]
278 fn falls_back_to_git_contributors() {
279 let owned = owned(metrics(None, 2), "alice@x.test", &["bob@x.test"]);
280 assert_eq!(
281 super::select_experts(&owned, &reviewer(&[], None)),
282 vec!["alice".to_string(), "bob".to_string()]
283 );
284 }
285
286 #[test]
287 fn anonymized_reviewer_is_not_routed_to_self() {
288 let mut m = metrics(None, 1);
289 m.top_contributor = contributor("xxh3:0123456789abcdef");
290 m.suggested_reviewers = vec![];
291 let experts = super::select_experts(
292 &owned(m, "bart@corp.com", &[]),
293 &reviewer(&["bart", "bart@corp.com"], Some("bart@corp.com")),
294 );
295 assert!(experts.is_empty(), "{experts:?}");
296 }
297
298 #[test]
299 fn reviewer_with_a_second_email_is_not_routed_to_self() {
300 let mut m = metrics(None, 1);
301 m.top_contributor = contributor("bart~corp.com");
302 m.suggested_reviewers = vec![contributor("bart~gmail.com")];
303 let experts = super::select_experts(
304 &owned(m, "bart@corp.com", &["bart@gmail.com"]),
305 &reviewer(&["bart", "bart@gmail.com"], Some("bart@gmail.com")),
306 );
307 assert!(experts.is_empty(), "{experts:?}");
308 }
309
310 #[test]
311 fn other_contributor_stays_an_expert_in_each_mode() {
312 let me = reviewer(&["bart", "bart@corp.com"], Some("bart@corp.com"));
313 for identifier in ["alice", "alice@corp.com", "xxh3:00000000000000aa"] {
314 let mut m = metrics(None, 1);
315 m.top_contributor = contributor(identifier);
316 m.suggested_reviewers = vec![];
317 assert_eq!(
318 super::select_experts(&owned(m, "alice@corp.com", &[]), &me),
319 vec![identifier.to_string()]
320 );
321 }
322 }
323
324 #[test]
325 fn declared_owner_that_is_the_reviewer_is_dropped() {
326 let me = reviewer(&["bart"], None);
327 let own = owned(metrics(Some("@bart"), 1), "alice@x.test", &["bob@x.test"]);
328 assert!(super::select_experts(&own, &me).is_empty());
329 let team = owned(
330 metrics(Some("@team/web"), 1),
331 "alice@x.test",
332 &["bob@x.test"],
333 );
334 assert_eq!(
335 super::select_experts(&team, &me),
336 vec!["@team/web".to_string()]
337 );
338 }
339}