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.unresolved_imports {
182            self.entry_for_path(&item.import.path)
183                .unresolved_imports
184                .push(item.clone());
185        }
186    }
187
188    fn group_dependency_issues(&mut self, results: &AnalysisResults) {
189        for item in &results.unused_dependencies {
190            self.entry_for_path(&item.dep.path)
191                .unused_dependencies
192                .push(item.clone());
193        }
194        for item in &results.unused_dev_dependencies {
195            self.entry_for_path(&item.dep.path)
196                .unused_dev_dependencies
197                .push(item.clone());
198        }
199        for item in &results.unused_optional_dependencies {
200            self.entry_for_path(&item.dep.path)
201                .unused_optional_dependencies
202                .push(item.clone());
203        }
204        for item in &results.type_only_dependencies {
205            self.entry_for_path(&item.dep.path)
206                .type_only_dependencies
207                .push(item.clone());
208        }
209        for item in &results.test_only_dependencies {
210            self.entry_for_path(&item.dep.path)
211                .test_only_dependencies
212                .push(item.clone());
213        }
214        for item in &results.dev_dependencies_in_production {
215            self.entry_for_path(&item.dep.path)
216                .dev_dependencies_in_production
217                .push(item.clone());
218        }
219
220        for item in &results.unlisted_dependencies {
221            let key = item.dep.imported_from.first().map_or_else(
222                || UNOWNED_GROUP_LABEL.to_string(),
223                |site| (self.key_for)(&site.path),
224            );
225            self.entry_for_key(key)
226                .unlisted_dependencies
227                .push(item.clone());
228        }
229        for item in &results.unlisted_binaries {
230            let key = item.binary.used_in.first().map_or_else(
231                || UNOWNED_GROUP_LABEL.to_string(),
232                |site| (self.key_for)(&site.path),
233            );
234            self.entry_for_key(key).unlisted_binaries.push(item.clone());
235        }
236        for item in &results.duplicate_exports {
237            let key = item.export.locations.first().map_or_else(
238                || UNOWNED_GROUP_LABEL.to_string(),
239                |loc| (self.key_for)(&loc.path),
240            );
241            self.entry_for_key(key).duplicate_exports.push(item.clone());
242        }
243    }
244
245    fn group_relationship_issues(&mut self, results: &AnalysisResults) {
246        self.group_structure_issues(results);
247        self.group_framework_boundary_issues(results);
248        self.group_component_contract_issues(results);
249    }
250
251    fn group_structure_issues(&mut self, results: &AnalysisResults) {
252        for item in &results.circular_dependencies {
253            let key = item
254                .cycle
255                .files
256                .first()
257                .map_or_else(|| UNOWNED_GROUP_LABEL.to_string(), |f| (self.key_for)(f));
258            self.entry_for_key(key)
259                .circular_dependencies
260                .push(item.clone());
261        }
262        for item in &results.re_export_cycles {
263            let key = item
264                .cycle
265                .files
266                .first()
267                .map_or_else(|| UNOWNED_GROUP_LABEL.to_string(), |f| (self.key_for)(f));
268            self.entry_for_key(key).re_export_cycles.push(item.clone());
269        }
270        // The first example import file owns a package cycle, the same file
271        // that workspace scope and per-file severity use.
272        for item in &results.package_cycles {
273            let key = item.cycle.edges.first().map_or_else(
274                || UNOWNED_GROUP_LABEL.to_string(),
275                |edge| (self.key_for)(&edge.path),
276            );
277            self.entry_for_key(key).package_cycles.push(item.clone());
278        }
279        for item in &results.boundary_violations {
280            self.entry_for_path(&item.violation.from_path)
281                .boundary_violations
282                .push(item.clone());
283        }
284        for item in &results.boundary_coverage_violations {
285            self.entry_for_path(&item.violation.path)
286                .boundary_coverage_violations
287                .push(item.clone());
288        }
289        for item in &results.boundary_call_violations {
290            self.entry_for_path(&item.violation.path)
291                .boundary_call_violations
292                .push(item.clone());
293        }
294        for item in &results.policy_violations {
295            self.entry_for_path(&item.violation.path)
296                .policy_violations
297                .push(item.clone());
298        }
299    }
300
301    fn group_framework_boundary_issues(&mut self, results: &AnalysisResults) {
302        for item in &results.invalid_client_exports {
303            self.entry_for_path(&item.export.path)
304                .invalid_client_exports
305                .push(item.clone());
306        }
307        for item in &results.mixed_client_server_barrels {
308            self.entry_for_path(&item.barrel.path)
309                .mixed_client_server_barrels
310                .push(item.clone());
311        }
312        for item in &results.misplaced_directives {
313            self.entry_for_path(&item.directive_site.path)
314                .misplaced_directives
315                .push(item.clone());
316        }
317        for item in &results.unprovided_injects {
318            self.entry_for_path(&item.inject.path)
319                .unprovided_injects
320                .push(item.clone());
321        }
322        for item in &results.unrendered_components {
323            self.entry_for_path(&item.component.path)
324                .unrendered_components
325                .push(item.clone());
326        }
327        for item in &results.route_collisions {
328            self.entry_for_path(&item.collision.path)
329                .route_collisions
330                .push(item.clone());
331        }
332        for item in &results.dynamic_segment_name_conflicts {
333            self.entry_for_path(&item.conflict.path)
334                .dynamic_segment_name_conflicts
335                .push(item.clone());
336        }
337    }
338
339    fn group_component_contract_issues(&mut self, results: &AnalysisResults) {
340        for item in &results.unused_component_props {
341            self.entry_for_path(&item.prop.path)
342                .unused_component_props
343                .push(item.clone());
344        }
345        for item in &results.constant_parameters {
346            self.entry_for_path(&item.parameter.path)
347                .constant_parameters
348                .push(item.clone());
349        }
350        for item in &results.absent_component_props {
351            self.entry_for_path(&item.prop.path)
352                .absent_component_props
353                .push(item.clone());
354        }
355        for item in &results.unused_component_emits {
356            self.entry_for_path(&item.emit.path)
357                .unused_component_emits
358                .push(item.clone());
359        }
360        for item in &results.unused_component_inputs {
361            self.entry_for_path(&item.input.path)
362                .unused_component_inputs
363                .push(item.clone());
364        }
365        for item in &results.unused_component_outputs {
366            self.entry_for_path(&item.output.path)
367                .unused_component_outputs
368                .push(item.clone());
369        }
370        for item in &results.unused_svelte_events {
371            self.entry_for_path(&item.event.path)
372                .unused_svelte_events
373                .push(item.clone());
374        }
375        for item in &results.duplicate_export_aliases {
376            self.entry_for_path(&item.alias.path)
377                .duplicate_export_aliases
378                .push(item.clone());
379        }
380        for item in &results.unused_effect_layers {
381            self.entry_for_path(&item.layer.path)
382                .unused_effect_layers
383                .push(item.clone());
384        }
385        for item in &results.unused_tagged_errors {
386            self.entry_for_path(&item.error.path)
387                .unused_tagged_errors
388                .push(item.clone());
389        }
390        for item in &results.unproduced_catch_tags {
391            self.entry_for_path(&item.catch_tag.path)
392                .unproduced_catch_tags
393                .push(item.clone());
394        }
395        for item in &results.unused_server_actions {
396            self.entry_for_path(&item.action.path)
397                .unused_server_actions
398                .push(item.clone());
399        }
400        for item in &results.unused_load_data_keys {
401            self.entry_for_path(&item.key.path)
402                .unused_load_data_keys
403                .push(item.clone());
404        }
405        for item in &results.stale_suppressions {
406            self.entry_for_path(&item.path)
407                .stale_suppressions
408                .push(item.clone());
409        }
410    }
411
412    fn group_workspace_config_issues(&mut self, results: &AnalysisResults) {
413        for item in &results.unused_catalog_entries {
414            self.entry_for_path(&item.entry.path)
415                .unused_catalog_entries
416                .push(item.clone());
417        }
418        for item in &results.empty_catalog_groups {
419            self.entry_for_path(&item.group.path)
420                .empty_catalog_groups
421                .push(item.clone());
422        }
423        for item in &results.unresolved_catalog_references {
424            self.entry_for_path(&item.reference.path)
425                .unresolved_catalog_references
426                .push(item.clone());
427        }
428        for item in &results.unused_dependency_overrides {
429            self.entry_for_path(&item.entry.path)
430                .unused_dependency_overrides
431                .push(item.clone());
432        }
433        for item in &results.misconfigured_dependency_overrides {
434            self.entry_for_path(&item.entry.path)
435                .misconfigured_dependency_overrides
436                .push(item.clone());
437        }
438    }
439
440    /// Group the opt-in component health signals. Advisory signals do not count toward
441    /// `total_issues`, but the flat report lists them, so the groups must too.
442    fn group_component_health_issues(&mut self, results: &AnalysisResults) {
443        // The first hop owns the drilled prop and anchors the finding, the
444        // same file that suppression and CI annotations use.
445        for item in &results.prop_drilling_chains {
446            let key = item.chain.hops.first().map_or_else(
447                || UNOWNED_GROUP_LABEL.to_string(),
448                |hop| (self.key_for)(&hop.file),
449            );
450            self.entry_for_key(key)
451                .prop_drilling_chains
452                .push(item.clone());
453        }
454        for item in &results.thin_wrappers {
455            self.entry_for_path(&item.wrapper.file)
456                .thin_wrappers
457                .push(item.clone());
458        }
459        for item in &results.duplicate_prop_shapes {
460            self.entry_for_path(&item.shape.file)
461                .duplicate_prop_shapes
462                .push(item.clone());
463        }
464    }
465}
466
467fn finalize_groups(
468    groups: FxHashMap<String, AnalysisResults>,
469    mut group_owners: FxHashMap<String, Vec<String>>,
470    include_owners: bool,
471) -> Vec<ResultGroup> {
472    let mut sorted: Vec<_> = groups
473        .into_iter()
474        .map(|(key, results)| {
475            let owners = if include_owners {
476                Some(group_owners.remove(&key).unwrap_or_default())
477            } else {
478                None
479            };
480            ResultGroup {
481                key,
482                owners,
483                results,
484            }
485        })
486        .collect();
487    sorted.sort_by(|a, b| {
488        let a_unowned = a.key == UNOWNED_GROUP_LABEL;
489        let b_unowned = b.key == UNOWNED_GROUP_LABEL;
490        match (a_unowned, b_unowned) {
491            (true, false) => std::cmp::Ordering::Greater,
492            (false, true) => std::cmp::Ordering::Less,
493            _ => b
494                .results
495                .total_issues()
496                .cmp(&a.results.total_issues())
497                .then_with(|| a.key.cmp(&b.key)),
498        }
499    });
500    sorted
501}
502
503/// Return the majority owner for a clone group using caller-provided path attribution.
504#[must_use]
505pub fn largest_clone_group_owner_with<F>(group: &CloneGroup, mut key_for_path: F) -> String
506where
507    F: FnMut(&Path) -> String,
508{
509    let mut counts: BTreeMap<String, u32> = BTreeMap::new();
510    for instance in &group.instances {
511        let key = key_for_path(&instance.file);
512        *counts.entry(key).or_insert(0) += 1;
513    }
514    if counts.is_empty() {
515        return UNOWNED_GROUP_LABEL.to_string();
516    }
517    let mut best_key: Option<String> = None;
518    let mut best_count: u32 = 0;
519    for (key, count) in counts {
520        if best_key.is_none() || count > best_count {
521            best_count = count;
522            best_key = Some(key);
523        }
524    }
525    best_key.unwrap_or_else(|| UNOWNED_GROUP_LABEL.to_string())
526}
527
528/// Build grouped duplication output using caller-provided path attribution.
529#[must_use]
530pub fn build_duplication_grouping_with<F>(
531    report: &DuplicationReport,
532    mode: &'static str,
533    mut key_for_path: F,
534) -> DuplicationGrouping
535where
536    F: FnMut(&Path) -> String,
537{
538    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
539    let buckets = build_attributed_clone_buckets(report, &mut key_for_path);
540    let mut groups: Vec<DuplicationGroup> = buckets
541        .into_iter()
542        .map(|(key, groups)| duplication_group(key, groups, report, &fingerprints))
543        .collect();
544    sort_duplication_groups(&mut groups);
545
546    DuplicationGrouping { mode, groups }
547}
548
549fn build_attributed_clone_buckets<F>(
550    report: &DuplicationReport,
551    key_for_path: &mut F,
552) -> BTreeMap<String, Vec<AttributedCloneGroup>>
553where
554    F: FnMut(&Path) -> String,
555{
556    let mut buckets: BTreeMap<String, Vec<AttributedCloneGroup>> = BTreeMap::new();
557    for group in &report.clone_groups {
558        let attributed = attributed_clone_group(group, key_for_path);
559        buckets
560            .entry(attributed.primary_owner.clone())
561            .or_default()
562            .push(attributed);
563    }
564    buckets
565}
566
567fn attributed_clone_group<F>(group: &CloneGroup, key_for_path: &mut F) -> AttributedCloneGroup
568where
569    F: FnMut(&Path) -> String,
570{
571    let primary_owner = largest_clone_group_owner_with(group, &mut *key_for_path);
572    let instances = group
573        .instances
574        .iter()
575        .map(|instance| AttributedInstance {
576            owner: key_for_path(&instance.file),
577            instance: instance.clone(),
578        })
579        .collect();
580    AttributedCloneGroup {
581        primary_owner,
582        token_count: group.token_count,
583        line_count: group.line_count,
584        similarity: group.similarity,
585        instances,
586    }
587}
588
589fn duplication_group(
590    key: String,
591    attributed_groups: Vec<AttributedCloneGroup>,
592    report: &DuplicationReport,
593    fingerprints: &CloneFingerprintSet,
594) -> DuplicationGroup {
595    let mut subset = duplication_subset_report(&attributed_groups, report);
596    subset.stats = fallow_engine::duplicates::recompute_stats(&subset);
597    let clone_families = clone_families_for_bucket(&attributed_groups, report, fingerprints);
598    subset.stats.clone_families = clone_families.len();
599    let clone_groups = attributed_groups
600        .into_iter()
601        .map(|group| {
602            let fingerprint = group.fingerprint(fingerprints);
603            AttributedCloneGroupFinding::with_fingerprint(group, fingerprint)
604        })
605        .collect();
606
607    DuplicationGroup {
608        key,
609        stats: subset.stats,
610        clone_groups,
611        clone_families,
612    }
613}
614
615fn duplication_subset_report(
616    attributed_groups: &[AttributedCloneGroup],
617    report: &DuplicationReport,
618) -> DuplicationReport {
619    DuplicationReport {
620        clone_groups: attributed_groups
621            .iter()
622            .map(|group| CloneGroup {
623                instances: group
624                    .instances
625                    .iter()
626                    .map(|instance| instance.instance.clone())
627                    .collect(),
628                token_count: group.token_count,
629                line_count: group.line_count,
630                similarity: group.similarity,
631            })
632            .collect(),
633        clone_families: Vec::new(),
634        mirrored_directories: Vec::new(),
635        stats: DuplicationStats {
636            total_files: report.stats.total_files,
637            files_with_clones: 0,
638            total_lines: report.stats.total_lines,
639            duplicated_lines: 0,
640            total_tokens: report.stats.total_tokens,
641            duplicated_tokens: 0,
642            clone_groups: 0,
643            clone_families: 0,
644            clone_instances: 0,
645            duplication_percentage: 0.0,
646            // Filtering and bounded-work counters are report-scoped and cannot
647            // be attributed reliably to one grouped bucket.
648            clone_groups_below_min_occurrences: 0,
649            clone_groups_ignored: 0,
650            near_candidates_skipped: 0,
651        },
652    }
653}
654
655fn clone_families_for_bucket(
656    attributed_groups: &[AttributedCloneGroup],
657    report: &DuplicationReport,
658    fingerprints: &CloneFingerprintSet,
659) -> Vec<CloneFamilyFinding> {
660    let bucket_files: FxHashSet<&Path> = attributed_groups
661        .iter()
662        .flat_map(|group| group.instances.iter().map(|i| i.instance.file.as_path()))
663        .collect();
664
665    report
666        .clone_families
667        .iter()
668        .filter(|family| {
669            family
670                .files
671                .iter()
672                .any(|path| bucket_files.contains(path.as_path()))
673        })
674        .map(|family| CloneFamilyFinding::with_fingerprints(family.clone(), fingerprints))
675        .collect()
676}
677
678fn sort_duplication_groups(groups: &mut [DuplicationGroup]) {
679    groups.sort_by(|a, b| {
680        let a_unowned = a.key == UNOWNED_GROUP_LABEL;
681        let b_unowned = b.key == UNOWNED_GROUP_LABEL;
682        match (a_unowned, b_unowned) {
683            (true, false) => std::cmp::Ordering::Greater,
684            (false, true) => std::cmp::Ordering::Less,
685            _ => b
686                .clone_groups
687                .len()
688                .cmp(&a.clone_groups.len())
689                .then_with(|| a.key.cmp(&b.key)),
690        }
691    });
692}
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697
698    /// Group by the full file path, so every finding anchor gets its own group.
699    fn group_by_path(results: &AnalysisResults) -> Vec<ResultGroup> {
700        group_analysis_results_with(
701            results,
702            |path: &Path| path.to_string_lossy().into_owned(),
703            |_: &Path| None,
704            false,
705        )
706    }
707
708    /// The length of each serialized issue list of `results`, by key.
709    fn list_lengths(results: &AnalysisResults) -> BTreeMap<String, usize> {
710        let value = serde_json::to_value(results).expect("serialize results");
711        value
712            .as_object()
713            .expect("results object")
714            .iter()
715            .filter_map(|(key, value)| value.as_array().map(|items| (key.clone(), items.len())))
716            .collect()
717    }
718
719    #[test]
720    fn every_issue_list_is_grouped() {
721        // The fixture names every field, so a new field must get a value there.
722        let source = crate::editor::tests::merge_test_source_with_all_fields();
723
724        let expected = list_lengths(&source);
725        for (key, len) in &expected {
726            assert!(
727                *len > 0,
728                "the fixture must fill `{key}` so this guard checks its grouping"
729            );
730        }
731
732        let groups = group_by_path(&source);
733        let mut grouped: BTreeMap<String, usize> = BTreeMap::new();
734        for group in &groups {
735            for (key, len) in list_lengths(&group.results) {
736                *grouped.entry(key).or_insert(0) += len;
737            }
738        }
739        for (key, len) in &expected {
740            assert_eq!(
741                grouped.get(key).copied().unwrap_or(0),
742                *len,
743                "--group-by drops `{key}` findings: add them to `GroupingBuilder`"
744            );
745        }
746
747        let grouped_total: usize = groups.iter().map(|g| g.results.total_issues()).sum();
748        assert_eq!(grouped_total, source.total_issues());
749    }
750
751    #[test]
752    fn prop_drilling_chain_without_hops_is_unowned() {
753        let mut source = crate::editor::tests::merge_test_source_with_all_fields();
754        let mut chain = source.prop_drilling_chains.remove(0);
755        chain.chain.hops.clear();
756        let mut results = AnalysisResults::default();
757        results.prop_drilling_chains.push(chain);
758
759        let groups = group_by_path(&results);
760        assert_eq!(groups.len(), 1);
761        assert_eq!(groups[0].key, UNOWNED_GROUP_LABEL);
762        assert_eq!(groups[0].results.prop_drilling_chains.len(), 1);
763    }
764
765    #[test]
766    fn health_signal_header_part_names_each_signal_type() {
767        let source = crate::editor::tests::merge_test_source_with_all_fields();
768        let mut results = AnalysisResults::default();
769        assert_eq!(health_signal_header_part(&results), "");
770
771        results
772            .prop_drilling_chains
773            .push(source.prop_drilling_chains[0].clone());
774        results.thin_wrappers.push(source.thin_wrappers[0].clone());
775        results.thin_wrappers.push(source.thin_wrappers[0].clone());
776        assert_eq!(
777            health_signal_header_part(&results),
778            "; 3 health signals: 1 prop drilling chain, 2 thin wrappers"
779        );
780
781        let mut single = AnalysisResults::default();
782        single
783            .duplicate_prop_shapes
784            .push(source.duplicate_prop_shapes[0].clone());
785        assert_eq!(
786            health_signal_header_part(&single),
787            "; 1 health signal: 1 duplicate prop shape"
788        );
789    }
790}