Skip to main content

fallow_api/
grouped_output.rs

1//! Shared grouped-output builders for programmatic and CLI consumers.
2
3use std::collections::BTreeMap;
4use std::path::Path;
5
6use fallow_engine::duplicates::CloneFingerprintSet;
7use fallow_types::duplicates::{CloneGroup, DuplicationReport, DuplicationStats};
8use fallow_types::results::AnalysisResults;
9use rustc_hash::{FxHashMap, FxHashSet};
10
11use crate::{
12    AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneFamilyFinding,
13    DuplicationGroup, DuplicationGrouping,
14};
15
16/// Canonical label for issues that cannot be attributed to a group.
17pub const UNOWNED_GROUP_LABEL: &str = "(unowned)";
18
19/// The group header part that names the opt-in component health signals of
20/// `results`, such as `; 3 health signals: 3 duplicate prop shapes`. Empty when
21/// there are none. Advisory signals do not count toward `total_issues`, so a group
22/// header names them next to the issue count. The human and markdown grouped
23/// reports share this text.
24#[must_use]
25pub fn health_signal_header_part(results: &AnalysisResults) -> String {
26    let kinds = [
27        (
28            results.prop_drilling_chains.len() - results.enforced_prop_drilling_count(),
29            "prop drilling chain",
30        ),
31        (
32            results.thin_wrappers.len() - results.enforced_thin_wrapper_count(),
33            "thin wrapper",
34        ),
35        (
36            results.duplicate_prop_shapes.len() - results.enforced_duplicate_prop_shape_count(),
37            "duplicate prop shape",
38        ),
39    ];
40    let count: usize = kinds.iter().map(|(n, _)| n).sum();
41    if count == 0 {
42        return String::new();
43    }
44    let parts: Vec<String> = kinds
45        .iter()
46        .filter(|(n, _)| *n > 0)
47        .map(|(n, label)| format!("{n} {label}{}", plural_suffix(*n)))
48        .collect();
49    format!(
50        "; {count} health signal{}: {}",
51        plural_suffix(count),
52        parts.join(", ")
53    )
54}
55
56const fn plural_suffix(count: usize) -> &'static str {
57    if count == 1 { "" } else { "s" }
58}
59
60/// A single grouped dead-code analysis bucket.
61pub struct ResultGroup {
62    /// Group label such as owner, directory, package, or section.
63    pub key: String,
64    /// Section default owners for section grouping.
65    ///
66    /// `None` for grouping modes without owner metadata. `Some(vec![])` for
67    /// groups that have no section owners.
68    pub owners: Option<Vec<String>>,
69    /// Issues belonging to this group.
70    pub results: AnalysisResults,
71}
72
73/// Partition analysis results into groups using caller-provided path resolvers.
74///
75/// The caller owns all environment-specific context, such as CODEOWNERS,
76/// package discovery, root-relative path normalization, or section metadata.
77#[must_use]
78pub fn group_analysis_results_with<F, O>(
79    results: &AnalysisResults,
80    mut key_for_path: F,
81    mut owners_for_path: O,
82    include_owners: bool,
83) -> Vec<ResultGroup>
84where
85    F: FnMut(&Path) -> String,
86    O: FnMut(&Path) -> Option<Vec<String>>,
87{
88    let mut group_owners: FxHashMap<String, Vec<String>> = FxHashMap::default();
89    let mut builder = GroupingBuilder::new(|path: &Path| {
90        let key = key_for_path(path);
91        if include_owners && !group_owners.contains_key(&key) {
92            let owners = owners_for_path(path).unwrap_or_default();
93            group_owners.insert(key.clone(), owners);
94        }
95        key
96    });
97    builder.group_symbol_issues(results);
98    builder.group_dependency_issues(results);
99    builder.group_relationship_issues(results);
100    builder.group_workspace_config_issues(results);
101    builder.group_component_health_issues(results);
102
103    finalize_groups(builder.into_groups(), group_owners, include_owners)
104}
105
106struct GroupingBuilder<F> {
107    groups: FxHashMap<String, AnalysisResults>,
108    key_for: F,
109}
110
111impl<F> GroupingBuilder<F>
112where
113    F: FnMut(&Path) -> String,
114{
115    fn new(key_for: F) -> Self {
116        Self {
117            groups: FxHashMap::default(),
118            key_for,
119        }
120    }
121
122    fn entry_for_path(&mut self, path: &Path) -> &mut AnalysisResults {
123        let key = (self.key_for)(path);
124        self.groups.entry(key).or_default()
125    }
126
127    fn entry_for_key(&mut self, key: String) -> &mut AnalysisResults {
128        self.groups.entry(key).or_default()
129    }
130
131    fn into_groups(self) -> FxHashMap<String, AnalysisResults> {
132        self.groups
133    }
134
135    fn group_symbol_issues(&mut self, results: &AnalysisResults) {
136        for item in &results.unused_files {
137            self.entry_for_path(&item.file.path)
138                .unused_files
139                .push(item.clone());
140        }
141        for item in &results.unused_exports {
142            self.entry_for_path(&item.export.path)
143                .unused_exports
144                .push(item.clone());
145        }
146        for item in &results.unused_types {
147            self.entry_for_path(&item.export.path)
148                .unused_types
149                .push(item.clone());
150        }
151        for item in &results.private_type_leaks {
152            self.entry_for_path(&item.leak.path)
153                .private_type_leaks
154                .push(item.clone());
155        }
156        for item in &results.deprecated_exports_in_use {
157            self.entry_for_path(&item.export.path)
158                .deprecated_exports_in_use
159                .push(item.clone());
160        }
161        for item in &results.unused_enum_members {
162            self.entry_for_path(&item.member.path)
163                .unused_enum_members
164                .push(item.clone());
165        }
166        for item in &results.unused_class_members {
167            self.entry_for_path(&item.member.path)
168                .unused_class_members
169                .push(item.clone());
170        }
171        for item in &results.unused_store_members {
172            self.entry_for_path(&item.member.path)
173                .unused_store_members
174                .push(item.clone());
175        }
176        for item in &results.unused_namespace_members {
177            self.entry_for_path(&item.member.path)
178                .unused_namespace_members
179                .push(item.clone());
180        }
181        for item in &results.unused_protected_class_members {
182            self.entry_for_path(&item.member.path)
183                .unused_protected_class_members
184                .push(item.clone());
185        }
186        for item in &results.unresolved_imports {
187            self.entry_for_path(&item.import.path)
188                .unresolved_imports
189                .push(item.clone());
190        }
191    }
192
193    fn group_dependency_issues(&mut self, results: &AnalysisResults) {
194        for item in &results.unused_dependencies {
195            self.entry_for_path(&item.dep.path)
196                .unused_dependencies
197                .push(item.clone());
198        }
199        for item in &results.unused_dev_dependencies {
200            self.entry_for_path(&item.dep.path)
201                .unused_dev_dependencies
202                .push(item.clone());
203        }
204        for item in &results.unused_optional_dependencies {
205            self.entry_for_path(&item.dep.path)
206                .unused_optional_dependencies
207                .push(item.clone());
208        }
209        for item in &results.type_only_dependencies {
210            self.entry_for_path(&item.dep.path)
211                .type_only_dependencies
212                .push(item.clone());
213        }
214        for item in &results.test_only_dependencies {
215            self.entry_for_path(&item.dep.path)
216                .test_only_dependencies
217                .push(item.clone());
218        }
219        for item in &results.dev_dependencies_in_production {
220            self.entry_for_path(&item.dep.path)
221                .dev_dependencies_in_production
222                .push(item.clone());
223        }
224
225        for item in &results.unlisted_dependencies {
226            let key = item.dep.imported_from.first().map_or_else(
227                || UNOWNED_GROUP_LABEL.to_string(),
228                |site| (self.key_for)(&site.path),
229            );
230            self.entry_for_key(key)
231                .unlisted_dependencies
232                .push(item.clone());
233        }
234        for item in &results.unlisted_binaries {
235            let key = item.binary.used_in.first().map_or_else(
236                || UNOWNED_GROUP_LABEL.to_string(),
237                |site| (self.key_for)(&site.path),
238            );
239            self.entry_for_key(key).unlisted_binaries.push(item.clone());
240        }
241        for item in &results.duplicate_exports {
242            let key = item.export.locations.first().map_or_else(
243                || UNOWNED_GROUP_LABEL.to_string(),
244                |loc| (self.key_for)(&loc.path),
245            );
246            self.entry_for_key(key).duplicate_exports.push(item.clone());
247        }
248    }
249
250    fn group_relationship_issues(&mut self, results: &AnalysisResults) {
251        self.group_structure_issues(results);
252        self.group_framework_boundary_issues(results);
253        self.group_component_contract_issues(results);
254    }
255
256    fn group_structure_issues(&mut self, results: &AnalysisResults) {
257        for item in &results.circular_dependencies {
258            let key = item
259                .cycle
260                .files
261                .first()
262                .map_or_else(|| UNOWNED_GROUP_LABEL.to_string(), |f| (self.key_for)(f));
263            self.entry_for_key(key)
264                .circular_dependencies
265                .push(item.clone());
266        }
267        for item in &results.re_export_cycles {
268            let key = item
269                .cycle
270                .files
271                .first()
272                .map_or_else(|| UNOWNED_GROUP_LABEL.to_string(), |f| (self.key_for)(f));
273            self.entry_for_key(key).re_export_cycles.push(item.clone());
274        }
275        // The first example import file owns a package cycle, the same file
276        // that workspace scope and per-file severity use.
277        for item in &results.package_cycles {
278            let key = item.cycle.edges.first().map_or_else(
279                || UNOWNED_GROUP_LABEL.to_string(),
280                |edge| (self.key_for)(&edge.path),
281            );
282            self.entry_for_key(key).package_cycles.push(item.clone());
283        }
284        for item in &results.boundary_violations {
285            self.entry_for_path(&item.violation.from_path)
286                .boundary_violations
287                .push(item.clone());
288        }
289        for item in &results.boundary_coverage_violations {
290            self.entry_for_path(&item.violation.path)
291                .boundary_coverage_violations
292                .push(item.clone());
293        }
294        for item in &results.boundary_call_violations {
295            self.entry_for_path(&item.violation.path)
296                .boundary_call_violations
297                .push(item.clone());
298        }
299        for item in &results.policy_violations {
300            self.entry_for_path(&item.violation.path)
301                .policy_violations
302                .push(item.clone());
303        }
304    }
305
306    fn group_framework_boundary_issues(&mut self, results: &AnalysisResults) {
307        for item in &results.invalid_client_exports {
308            self.entry_for_path(&item.export.path)
309                .invalid_client_exports
310                .push(item.clone());
311        }
312        for item in &results.mixed_client_server_barrels {
313            self.entry_for_path(&item.barrel.path)
314                .mixed_client_server_barrels
315                .push(item.clone());
316        }
317        for item in &results.misplaced_directives {
318            self.entry_for_path(&item.directive_site.path)
319                .misplaced_directives
320                .push(item.clone());
321        }
322        for item in &results.unprovided_injects {
323            self.entry_for_path(&item.inject.path)
324                .unprovided_injects
325                .push(item.clone());
326        }
327        for item in &results.unrendered_components {
328            self.entry_for_path(&item.component.path)
329                .unrendered_components
330                .push(item.clone());
331        }
332        for item in &results.route_collisions {
333            self.entry_for_path(&item.collision.path)
334                .route_collisions
335                .push(item.clone());
336        }
337        for item in &results.dynamic_segment_name_conflicts {
338            self.entry_for_path(&item.conflict.path)
339                .dynamic_segment_name_conflicts
340                .push(item.clone());
341        }
342    }
343
344    fn group_component_contract_issues(&mut self, results: &AnalysisResults) {
345        for item in &results.unused_component_props {
346            self.entry_for_path(&item.prop.path)
347                .unused_component_props
348                .push(item.clone());
349        }
350        for item in &results.constant_parameters {
351            self.entry_for_path(&item.parameter.path)
352                .constant_parameters
353                .push(item.clone());
354        }
355        for item in &results.absent_component_props {
356            self.entry_for_path(&item.prop.path)
357                .absent_component_props
358                .push(item.clone());
359        }
360        for item in &results.unused_component_emits {
361            self.entry_for_path(&item.emit.path)
362                .unused_component_emits
363                .push(item.clone());
364        }
365        for item in &results.unused_component_inputs {
366            self.entry_for_path(&item.input.path)
367                .unused_component_inputs
368                .push(item.clone());
369        }
370        for item in &results.unused_component_outputs {
371            self.entry_for_path(&item.output.path)
372                .unused_component_outputs
373                .push(item.clone());
374        }
375        for item in &results.unused_svelte_events {
376            self.entry_for_path(&item.event.path)
377                .unused_svelte_events
378                .push(item.clone());
379        }
380        for item in &results.duplicate_export_aliases {
381            self.entry_for_path(&item.alias.path)
382                .duplicate_export_aliases
383                .push(item.clone());
384        }
385        for item in &results.unused_effect_layers {
386            self.entry_for_path(&item.layer.path)
387                .unused_effect_layers
388                .push(item.clone());
389        }
390        for item in &results.unused_tagged_errors {
391            self.entry_for_path(&item.error.path)
392                .unused_tagged_errors
393                .push(item.clone());
394        }
395        for item in &results.unproduced_catch_tags {
396            self.entry_for_path(&item.catch_tag.path)
397                .unproduced_catch_tags
398                .push(item.clone());
399        }
400        for item in &results.unused_server_actions {
401            self.entry_for_path(&item.action.path)
402                .unused_server_actions
403                .push(item.clone());
404        }
405        for item in &results.unused_load_data_keys {
406            self.entry_for_path(&item.key.path)
407                .unused_load_data_keys
408                .push(item.clone());
409        }
410        for item in &results.stale_suppressions {
411            self.entry_for_path(&item.path)
412                .stale_suppressions
413                .push(item.clone());
414        }
415    }
416
417    fn group_workspace_config_issues(&mut self, results: &AnalysisResults) {
418        for item in &results.unused_catalog_entries {
419            self.entry_for_path(&item.entry.path)
420                .unused_catalog_entries
421                .push(item.clone());
422        }
423        for item in &results.empty_catalog_groups {
424            self.entry_for_path(&item.group.path)
425                .empty_catalog_groups
426                .push(item.clone());
427        }
428        for item in &results.unresolved_catalog_references {
429            self.entry_for_path(&item.reference.path)
430                .unresolved_catalog_references
431                .push(item.clone());
432        }
433        for item in &results.unused_dependency_overrides {
434            self.entry_for_path(&item.entry.path)
435                .unused_dependency_overrides
436                .push(item.clone());
437        }
438        for item in &results.misconfigured_dependency_overrides {
439            self.entry_for_path(&item.entry.path)
440                .misconfigured_dependency_overrides
441                .push(item.clone());
442        }
443    }
444
445    /// Group the opt-in component health signals. Advisory signals do not count toward
446    /// `total_issues`, but the flat report lists them, so the groups must too.
447    fn group_component_health_issues(&mut self, results: &AnalysisResults) {
448        // The first hop owns the drilled prop and anchors the finding, the
449        // same file that suppression and CI annotations use.
450        for item in &results.prop_drilling_chains {
451            let key = item.chain.hops.first().map_or_else(
452                || UNOWNED_GROUP_LABEL.to_string(),
453                |hop| (self.key_for)(&hop.file),
454            );
455            self.entry_for_key(key)
456                .prop_drilling_chains
457                .push(item.clone());
458        }
459        for item in &results.thin_wrappers {
460            self.entry_for_path(&item.wrapper.file)
461                .thin_wrappers
462                .push(item.clone());
463        }
464        for item in &results.duplicate_prop_shapes {
465            self.entry_for_path(&item.shape.file)
466                .duplicate_prop_shapes
467                .push(item.clone());
468        }
469    }
470}
471
472fn finalize_groups(
473    groups: FxHashMap<String, AnalysisResults>,
474    mut group_owners: FxHashMap<String, Vec<String>>,
475    include_owners: bool,
476) -> Vec<ResultGroup> {
477    let mut sorted: Vec<_> = groups
478        .into_iter()
479        .map(|(key, results)| {
480            let owners = if include_owners {
481                Some(group_owners.remove(&key).unwrap_or_default())
482            } else {
483                None
484            };
485            ResultGroup {
486                key,
487                owners,
488                results,
489            }
490        })
491        .collect();
492    sorted.sort_by(|a, b| {
493        let a_unowned = a.key == UNOWNED_GROUP_LABEL;
494        let b_unowned = b.key == UNOWNED_GROUP_LABEL;
495        match (a_unowned, b_unowned) {
496            (true, false) => std::cmp::Ordering::Greater,
497            (false, true) => std::cmp::Ordering::Less,
498            _ => b
499                .results
500                .total_issues()
501                .cmp(&a.results.total_issues())
502                .then_with(|| a.key.cmp(&b.key)),
503        }
504    });
505    sorted
506}
507
508/// Return the majority owner for a clone group using caller-provided path attribution.
509#[must_use]
510pub fn largest_clone_group_owner_with<F>(group: &CloneGroup, mut key_for_path: F) -> String
511where
512    F: FnMut(&Path) -> String,
513{
514    let mut counts: BTreeMap<String, u32> = BTreeMap::new();
515    for instance in &group.instances {
516        let key = key_for_path(&instance.file);
517        *counts.entry(key).or_insert(0) += 1;
518    }
519    if counts.is_empty() {
520        return UNOWNED_GROUP_LABEL.to_string();
521    }
522    let mut best_key: Option<String> = None;
523    let mut best_count: u32 = 0;
524    for (key, count) in counts {
525        if best_key.is_none() || count > best_count {
526            best_count = count;
527            best_key = Some(key);
528        }
529    }
530    best_key.unwrap_or_else(|| UNOWNED_GROUP_LABEL.to_string())
531}
532
533/// Build grouped duplication output using caller-provided path attribution.
534#[must_use]
535pub fn build_duplication_grouping_with<F>(
536    report: &DuplicationReport,
537    mode: &'static str,
538    mut key_for_path: F,
539) -> DuplicationGrouping
540where
541    F: FnMut(&Path) -> String,
542{
543    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
544    let buckets = build_attributed_clone_buckets(report, &mut key_for_path);
545    let mut groups: Vec<DuplicationGroup> = buckets
546        .into_iter()
547        .map(|(key, groups)| duplication_group(key, groups, report, &fingerprints))
548        .collect();
549    sort_duplication_groups(&mut groups);
550
551    DuplicationGrouping { mode, groups }
552}
553
554fn build_attributed_clone_buckets<F>(
555    report: &DuplicationReport,
556    key_for_path: &mut F,
557) -> BTreeMap<String, Vec<AttributedCloneGroup>>
558where
559    F: FnMut(&Path) -> String,
560{
561    let mut buckets: BTreeMap<String, Vec<AttributedCloneGroup>> = BTreeMap::new();
562    for group in &report.clone_groups {
563        let attributed = attributed_clone_group(group, key_for_path);
564        buckets
565            .entry(attributed.primary_owner.clone())
566            .or_default()
567            .push(attributed);
568    }
569    buckets
570}
571
572fn attributed_clone_group<F>(group: &CloneGroup, key_for_path: &mut F) -> AttributedCloneGroup
573where
574    F: FnMut(&Path) -> String,
575{
576    let primary_owner = largest_clone_group_owner_with(group, &mut *key_for_path);
577    let instances = group
578        .instances
579        .iter()
580        .map(|instance| AttributedInstance {
581            owner: key_for_path(&instance.file),
582            instance: instance.clone(),
583        })
584        .collect();
585    AttributedCloneGroup {
586        primary_owner,
587        token_count: group.token_count,
588        line_count: group.line_count,
589        similarity: group.similarity,
590        instances,
591    }
592}
593
594fn duplication_group(
595    key: String,
596    attributed_groups: Vec<AttributedCloneGroup>,
597    report: &DuplicationReport,
598    fingerprints: &CloneFingerprintSet,
599) -> DuplicationGroup {
600    let mut subset = duplication_subset_report(&attributed_groups, report);
601    subset.stats = fallow_engine::duplicates::recompute_stats(&subset);
602    let clone_families = clone_families_for_bucket(&attributed_groups, report, fingerprints);
603    subset.stats.clone_families = clone_families.len();
604    let clone_groups = attributed_groups
605        .into_iter()
606        .map(|group| {
607            let fingerprint = group.fingerprint(fingerprints);
608            AttributedCloneGroupFinding::with_fingerprint(group, fingerprint)
609        })
610        .collect();
611
612    DuplicationGroup {
613        key,
614        stats: subset.stats,
615        clone_groups,
616        clone_families,
617    }
618}
619
620fn duplication_subset_report(
621    attributed_groups: &[AttributedCloneGroup],
622    report: &DuplicationReport,
623) -> DuplicationReport {
624    DuplicationReport {
625        clone_groups: attributed_groups
626            .iter()
627            .map(|group| CloneGroup {
628                instances: group
629                    .instances
630                    .iter()
631                    .map(|instance| instance.instance.clone())
632                    .collect(),
633                token_count: group.token_count,
634                line_count: group.line_count,
635                similarity: group.similarity,
636            })
637            .collect(),
638        clone_families: Vec::new(),
639        mirrored_directories: Vec::new(),
640        range_marker_problems: Vec::new(),
641        stats: DuplicationStats {
642            total_files: report.stats.total_files,
643            files_with_clones: 0,
644            total_lines: report.stats.total_lines,
645            duplicated_lines: 0,
646            total_tokens: report.stats.total_tokens,
647            duplicated_tokens: 0,
648            clone_groups: 0,
649            clone_families: 0,
650            clone_instances: 0,
651            duplication_percentage: 0.0,
652            // Filtering and bounded-work counters are report-scoped and cannot
653            // be attributed reliably to one grouped bucket.
654            clone_groups_below_min_occurrences: 0,
655            clone_groups_ignored: 0,
656            near_candidates_skipped: 0,
657        },
658    }
659}
660
661fn clone_families_for_bucket(
662    attributed_groups: &[AttributedCloneGroup],
663    report: &DuplicationReport,
664    fingerprints: &CloneFingerprintSet,
665) -> Vec<CloneFamilyFinding> {
666    let bucket_files: FxHashSet<&Path> = attributed_groups
667        .iter()
668        .flat_map(|group| group.instances.iter().map(|i| i.instance.file.as_path()))
669        .collect();
670
671    report
672        .clone_families
673        .iter()
674        .filter(|family| {
675            family
676                .files
677                .iter()
678                .any(|path| bucket_files.contains(path.as_path()))
679        })
680        .map(|family| CloneFamilyFinding::with_fingerprints(family.clone(), fingerprints))
681        .collect()
682}
683
684fn sort_duplication_groups(groups: &mut [DuplicationGroup]) {
685    groups.sort_by(|a, b| {
686        let a_unowned = a.key == UNOWNED_GROUP_LABEL;
687        let b_unowned = b.key == UNOWNED_GROUP_LABEL;
688        match (a_unowned, b_unowned) {
689            (true, false) => std::cmp::Ordering::Greater,
690            (false, true) => std::cmp::Ordering::Less,
691            _ => b
692                .clone_groups
693                .len()
694                .cmp(&a.clone_groups.len())
695                .then_with(|| a.key.cmp(&b.key)),
696        }
697    });
698}
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703
704    /// Group by the full file path, so every finding anchor gets its own group.
705    fn group_by_path(results: &AnalysisResults) -> Vec<ResultGroup> {
706        group_analysis_results_with(
707            results,
708            |path: &Path| path.to_string_lossy().into_owned(),
709            |_: &Path| None,
710            false,
711        )
712    }
713
714    /// The length of each serialized issue list of `results`, by key.
715    fn list_lengths(results: &AnalysisResults) -> BTreeMap<String, usize> {
716        let value = serde_json::to_value(results).expect("serialize results");
717        value
718            .as_object()
719            .expect("results object")
720            .iter()
721            .filter_map(|(key, value)| value.as_array().map(|items| (key.clone(), items.len())))
722            .collect()
723    }
724
725    #[test]
726    fn every_issue_list_is_grouped() {
727        // The fixture names every field, so a new field must get a value there.
728        let source = crate::editor::tests::merge_test_source_with_all_fields();
729
730        let expected = list_lengths(&source);
731        for (key, len) in &expected {
732            assert!(
733                *len > 0,
734                "the fixture must fill `{key}` so this guard checks its grouping"
735            );
736        }
737
738        let groups = group_by_path(&source);
739        let mut grouped: BTreeMap<String, usize> = BTreeMap::new();
740        for group in &groups {
741            for (key, len) in list_lengths(&group.results) {
742                *grouped.entry(key).or_insert(0) += len;
743            }
744        }
745        for (key, len) in &expected {
746            assert_eq!(
747                grouped.get(key).copied().unwrap_or(0),
748                *len,
749                "--group-by drops `{key}` findings: add them to `GroupingBuilder`"
750            );
751        }
752
753        let grouped_total: usize = groups.iter().map(|g| g.results.total_issues()).sum();
754        assert_eq!(grouped_total, source.total_issues());
755    }
756
757    #[test]
758    fn prop_drilling_chain_without_hops_is_unowned() {
759        let mut source = crate::editor::tests::merge_test_source_with_all_fields();
760        let mut chain = source.prop_drilling_chains.remove(0);
761        chain.chain.hops.clear();
762        let mut results = AnalysisResults::default();
763        results.prop_drilling_chains.push(chain);
764
765        let groups = group_by_path(&results);
766        assert_eq!(groups.len(), 1);
767        assert_eq!(groups[0].key, UNOWNED_GROUP_LABEL);
768        assert_eq!(groups[0].results.prop_drilling_chains.len(), 1);
769    }
770
771    #[test]
772    fn health_signal_header_part_names_each_signal_type() {
773        let source = crate::editor::tests::merge_test_source_with_all_fields();
774        let mut results = AnalysisResults::default();
775        assert_eq!(health_signal_header_part(&results), "");
776
777        results
778            .prop_drilling_chains
779            .push(source.prop_drilling_chains[0].clone());
780        results.thin_wrappers.push(source.thin_wrappers[0].clone());
781        results.thin_wrappers.push(source.thin_wrappers[0].clone());
782        assert_eq!(
783            health_signal_header_part(&results),
784            "; 3 health signals: 1 prop drilling chain, 2 thin wrappers"
785        );
786
787        let mut single = AnalysisResults::default();
788        single
789            .duplicate_prop_shapes
790            .push(source.duplicate_prop_shapes[0].clone());
791        assert_eq!(
792            health_signal_header_part(&single),
793            "; 1 health signal: 1 duplicate prop shape"
794        );
795    }
796}