Skip to main content

fallow_api/
ownership.rs

1//! Owner-group reach of a changeset for the review brief.
2//!
3//! Maps the changed files and the impact closure to CODEOWNERS owner groups:
4//! how many groups the change reaches, which groups it reaches only through
5//! the closure, and whether each independent slice of the partition has one
6//! owner. Reads the CODEOWNERS file only. It does not read git history, so it
7//! does not depend on the churn walk behind `routing`.
8//!
9//! Advisory brief data; never gates.
10
11use std::path::Path;
12
13pub use fallow_output::{OWNER_GROUP_CAP, OwnerGroupFact, OwnershipFacts, OwnershipSliceFact};
14use rustc_hash::{FxHashMap, FxHashSet};
15
16use fallow_config::ResolvedConfig;
17use fallow_engine::codeowners::{CodeOwners, UNOWNED_LABEL};
18use fallow_engine::module_graph::PartitionOrderPaths;
19
20/// Load the project CODEOWNERS file: the configured `codeowners` path when
21/// set, else the first of the standard locations.
22///
23/// Returns `Ok(None)` when no path is configured and no standard location
24/// holds a file that parses, so the brief omits the section.
25///
26/// # Errors
27///
28/// Returns the reason when a configured `codeowners` path cannot be read or
29/// does not parse. The caller reports it, because the user asked for that
30/// file.
31pub fn load_codeowners(root: &Path, config: &ResolvedConfig) -> Result<Option<CodeOwners>, String> {
32    match config.codeowners.as_deref() {
33        Some(path) => CodeOwners::load(root, Some(path))
34            .map(Some)
35            .map_err(|error| format!("codeowners path `{path}`: {error}")),
36        None => Ok(CodeOwners::discover(root).ok()),
37    }
38}
39
40/// Owner label of a path: the primary owner, or the unowned label.
41fn owner_label<'a>(codeowners: &'a CodeOwners, path: &str) -> &'a str {
42    codeowners
43        .owner_of(Path::new(path))
44        .unwrap_or(UNOWNED_LABEL)
45}
46
47/// Compute the ownership section.
48///
49/// `changed` and `affected` are root-relative, forward-slashed paths.
50/// `affected` is the full, uncapped impact closure (files affected but not in
51/// the diff), never the serialized sample. `partition` supplies the
52/// independent slices and the changed files of each unit.
53#[must_use]
54pub fn compute_ownership_facts(
55    codeowners: &CodeOwners,
56    changed: &[String],
57    affected: &[String],
58    partition: Option<&PartitionOrderPaths>,
59) -> OwnershipFacts {
60    let mut changed_owners: FxHashMap<&str, &str> = FxHashMap::default();
61    let mut counts: FxHashMap<&str, (usize, usize)> = FxHashMap::default();
62    for path in changed {
63        let owner = owner_label(codeowners, path);
64        changed_owners.insert(path.as_str(), owner);
65        counts.entry(owner).or_default().0 += 1;
66    }
67    for path in affected {
68        counts.entry(owner_label(codeowners, path)).or_default().1 += 1;
69    }
70
71    let unowned_direct_count = counts.get(UNOWNED_LABEL).map_or(0, |&(direct, _)| direct);
72    let transitive_only_count = counts.values().filter(|&&(direct, _)| direct == 0).count();
73    let group_count = counts.len();
74
75    let mut groups: Vec<OwnerGroupFact> = counts
76        .into_iter()
77        .map(|(owner, (direct_count, affected_count))| OwnerGroupFact {
78            owner: owner.to_string(),
79            direct_count,
80            affected_count,
81        })
82        .collect();
83    groups.sort_by(|a, b| {
84        b.direct_count
85            .cmp(&a.direct_count)
86            .then_with(|| b.affected_count.cmp(&a.affected_count))
87            .then_with(|| a.owner.cmp(&b.owner))
88    });
89    let groups_omitted = groups.len().saturating_sub(OWNER_GROUP_CAP);
90    groups.truncate(OWNER_GROUP_CAP);
91
92    OwnershipFacts {
93        group_count,
94        transitive_only_count,
95        unowned_direct_count,
96        groups,
97        groups_omitted,
98        slices: partition.map_or_else(Vec::new, |partition| {
99            slice_owners(partition, &|file: &str| {
100                changed_owners
101                    .get(file)
102                    .copied()
103                    .unwrap_or_else(|| owner_label(codeowners, file))
104            })
105        }),
106    }
107}
108
109/// The owner set of each independent slice, aligned by index with
110/// `independent_slices`. Empty when the partition has fewer than two slices,
111/// the same rule that keeps `independent_slices` off the wire.
112///
113/// The owner set of a slice is never empty: the partition builds its slices
114/// from its own units, so each slice directory has a unit with at least one
115/// changed file, and each file has an owner or the unowned label.
116///
117/// The owners come from the changed files of each unit, not from the module
118/// directory, because a CODEOWNERS rule can split a directory.
119fn slice_owners<'a>(
120    partition: &PartitionOrderPaths,
121    owner_of: &dyn Fn(&str) -> &'a str,
122) -> Vec<OwnershipSliceFact> {
123    if partition.independent_slices.len() < 2 {
124        return Vec::new();
125    }
126    let files_by_dir: FxHashMap<&str, &[String]> = partition
127        .units
128        .iter()
129        .map(|unit| (unit.module_dir.as_str(), unit.files.as_slice()))
130        .collect();
131    partition
132        .independent_slices
133        .iter()
134        .map(|module_dirs| {
135            let owners: FxHashSet<&str> = module_dirs
136                .iter()
137                .filter_map(|dir| files_by_dir.get(dir.as_str()))
138                .flat_map(|files| files.iter())
139                .map(|file| owner_of(file))
140                .collect();
141            let mut owners: Vec<String> = owners.into_iter().map(str::to_string).collect();
142            owners.sort_unstable();
143            debug_assert!(
144                !owners.is_empty(),
145                "slice {module_dirs:?} has no unit with changed files"
146            );
147            OwnershipSliceFact {
148                module_dirs: module_dirs.clone(),
149                separable: owners.len() == 1,
150                owners,
151            }
152        })
153        .collect()
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use fallow_engine::module_graph::ReviewUnitPaths;
160
161    fn paths(items: &[&str]) -> Vec<String> {
162        items.iter().map(|item| (*item).to_string()).collect()
163    }
164
165    fn owners(content: &str) -> CodeOwners {
166        CodeOwners::parse(content).expect("valid CODEOWNERS")
167    }
168
169    fn group(owner: &str, direct_count: usize, affected_count: usize) -> OwnerGroupFact {
170        OwnerGroupFact {
171            owner: owner.to_string(),
172            direct_count,
173            affected_count,
174        }
175    }
176
177    fn partition(units: &[(&str, &[&str])], slices: &[&[&str]]) -> PartitionOrderPaths {
178        PartitionOrderPaths {
179            units: units
180                .iter()
181                .map(|(dir, files)| ReviewUnitPaths {
182                    module_dir: (*dir).to_string(),
183                    files: paths(files),
184                })
185                .collect(),
186            order: Vec::new(),
187            independent_slices: slices.iter().map(|slice| paths(slice)).collect(),
188        }
189    }
190
191    #[test]
192    fn all_unowned_files_form_one_unowned_group() {
193        let facts = compute_ownership_facts(
194            &owners("docs/ @docs\n"),
195            &paths(&["src/a.ts", "src/b.ts"]),
196            &paths(&["src/c.ts"]),
197            None,
198        );
199        assert_eq!(facts.group_count, 1);
200        assert_eq!(facts.unowned_direct_count, 2);
201        assert_eq!(facts.transitive_only_count, 0);
202        assert_eq!(facts.groups, vec![group(UNOWNED_LABEL, 2, 1)]);
203    }
204
205    #[test]
206    fn one_owner_owns_the_change_and_its_closure() {
207        let facts = compute_ownership_facts(
208            &owners("* @org/web\n"),
209            &paths(&["src/a.ts"]),
210            &paths(&["src/b.ts", "src/c.ts"]),
211            None,
212        );
213        assert_eq!(facts.group_count, 1);
214        assert_eq!(facts.unowned_direct_count, 0);
215        assert_eq!(facts.groups, vec![group("@org/web", 1, 2)]);
216    }
217
218    #[test]
219    fn a_group_reached_only_through_the_closure_is_transitive_only() {
220        let facts = compute_ownership_facts(
221            &owners("src/web/ @org/web\nsrc/tokens/ @org/design\nsrc/api/ @org/api\n"),
222            &paths(&["src/web/a.ts", "src/web/b.ts", "src/tokens/t.ts"]),
223            &paths(&["src/api/x.ts", "src/api/y.ts", "src/web/c.ts"]),
224            None,
225        );
226        assert_eq!(facts.group_count, 3);
227        assert_eq!(facts.transitive_only_count, 1);
228        assert_eq!(
229            facts.groups,
230            vec![
231                group("@org/web", 2, 1),
232                group("@org/design", 1, 0),
233                group("@org/api", 0, 2),
234            ]
235        );
236    }
237
238    #[test]
239    fn a_gitlab_negation_makes_the_file_unowned() {
240        let facts = compute_ownership_facts(
241            &owners("src/ @org/web\n!src/generated/\n"),
242            &paths(&["src/a.ts", "src/generated/types.ts"]),
243            &[],
244            None,
245        );
246        assert_eq!(facts.unowned_direct_count, 1);
247        assert_eq!(
248            facts.groups,
249            vec![group(UNOWNED_LABEL, 1, 0), group("@org/web", 1, 0)]
250        );
251    }
252
253    #[test]
254    fn groups_beyond_the_cap_are_counted_not_dropped_silently() {
255        let rules = (0..OWNER_GROUP_CAP + 3).fold(String::new(), |mut acc, i| {
256            use std::fmt::Write as _;
257            let _ = writeln!(acc, "pkg{i:02}/ @team{i:02}");
258            acc
259        });
260        let changed: Vec<String> = (0..OWNER_GROUP_CAP + 3)
261            .map(|i| format!("pkg{i:02}/index.ts"))
262            .collect();
263        let facts = compute_ownership_facts(&owners(&rules), &changed, &[], None);
264        assert_eq!(facts.group_count, OWNER_GROUP_CAP + 3);
265        assert_eq!(facts.groups.len(), OWNER_GROUP_CAP);
266        assert_eq!(facts.groups_omitted, 3);
267    }
268
269    #[test]
270    fn ties_sort_by_owner_so_the_order_is_deterministic() {
271        let facts = compute_ownership_facts(
272            &owners("c/ @c\na/ @a\nb/ @b\n"),
273            &paths(&["c/x.ts", "b/x.ts", "a/x.ts"]),
274            &[],
275            None,
276        );
277        let order: Vec<&str> = facts.groups.iter().map(|g| g.owner.as_str()).collect();
278        assert_eq!(order, vec!["@a", "@b", "@c"]);
279    }
280
281    #[test]
282    fn slices_align_with_the_partition_and_flag_one_owner_as_separable() {
283        let partition = partition(
284            &[
285                ("src/app", &["src/app/main.ts"]),
286                ("src/core", &["src/core/lib.ts"]),
287                ("src/tools", &["src/tools/cli.ts"]),
288            ],
289            &[&["src/app", "src/core"], &["src/tools"]],
290        );
291        let facts = compute_ownership_facts(
292            &owners("src/app/ @team/app\nsrc/core/ @team/core\nsrc/tools/ @team/tools\n"),
293            &paths(&["src/app/main.ts", "src/core/lib.ts", "src/tools/cli.ts"]),
294            &[],
295            Some(&partition),
296        );
297        assert_eq!(
298            facts.slices,
299            vec![
300                OwnershipSliceFact {
301                    module_dirs: paths(&["src/app", "src/core"]),
302                    owners: paths(&["@team/app", "@team/core"]),
303                    separable: false,
304                },
305                OwnershipSliceFact {
306                    module_dirs: paths(&["src/tools"]),
307                    owners: paths(&["@team/tools"]),
308                    separable: true,
309                },
310            ]
311        );
312    }
313
314    #[test]
315    fn slice_owners_come_from_files_so_a_rule_can_split_a_directory() {
316        let partition = partition(
317            &[
318                ("src/a", &["src/a/x.ts", "src/a/y.ts"]),
319                ("src/b", &["src/b/z.ts"]),
320            ],
321            &[&["src/a"], &["src/b"]],
322        );
323        let facts = compute_ownership_facts(
324            &owners("src/ @team/all\nsrc/a/y.ts @team/y\n"),
325            &paths(&["src/a/x.ts", "src/a/y.ts", "src/b/z.ts"]),
326            &[],
327            Some(&partition),
328        );
329        assert_eq!(facts.slices[0].owners, paths(&["@team/all", "@team/y"]));
330        assert!(!facts.slices[0].separable);
331        assert!(facts.slices[1].separable);
332    }
333
334    #[test]
335    fn an_unowned_slice_counts_the_unowned_label_as_its_owner() {
336        let partition = partition(
337            &[("src/a", &["src/a/x.ts"]), ("src/b", &["src/b/z.ts"])],
338            &[&["src/a"], &["src/b"]],
339        );
340        let facts = compute_ownership_facts(
341            &owners("src/a/ @team/a\n"),
342            &paths(&["src/a/x.ts", "src/b/z.ts"]),
343            &[],
344            Some(&partition),
345        );
346        assert_eq!(facts.slices[1].owners, paths(&[UNOWNED_LABEL]));
347        assert!(facts.slices[1].separable);
348    }
349
350    #[test]
351    fn a_single_slice_emits_no_slice_owners() {
352        let partition = partition(&[("src", &["src/a.ts"])], &[&["src"]]);
353        let facts = compute_ownership_facts(
354            &owners("* @org/web\n"),
355            &paths(&["src/a.ts"]),
356            &[],
357            Some(&partition),
358        );
359        assert!(facts.slices.is_empty());
360    }
361
362    #[test]
363    fn a_slice_file_outside_the_changed_list_still_gets_its_owner() {
364        let partition = partition(
365            &[
366                ("src/a", &["src/a/x.ts", "src/a/extra.ts"]),
367                ("src/b", &["src/b/z.ts"]),
368            ],
369            &[&["src/a"], &["src/b"]],
370        );
371        let facts = compute_ownership_facts(
372            &owners("src/ @team/all\nsrc/a/extra.ts @team/extra\n"),
373            &paths(&["src/a/x.ts", "src/b/z.ts"]),
374            &[],
375            Some(&partition),
376        );
377        assert_eq!(facts.slices[0].owners, paths(&["@team/all", "@team/extra"]));
378        assert_eq!(facts.slices[1].owners, paths(&["@team/all"]));
379    }
380}