1#![allow(
4 clippy::implicit_hasher,
5 reason = "engine graph helpers use FxHashSet changed-file sets consistently with the rest of fallow"
6)]
7
8use std::path::{Path, PathBuf};
9
10use fallow_output::TestAdjacency;
11use fallow_types::discover::FileId;
12use rustc_hash::{FxHashMap, FxHashSet};
13
14use fallow_graph::graph::{
15 CoordinationGapPaths as GraphCoordinationGapPaths,
16 FocusFileFactsPaths as GraphFocusFileFactsPaths, ImpactClosurePaths as GraphImpactClosurePaths,
17 ModuleGraph, PartitionOrderPaths as GraphPartitionOrderPaths,
18 ReviewUnitPaths as GraphReviewUnitPaths,
19};
20use fallow_graph::graph::{
21 DirectImporterSummary as GraphDirectImporterSummary,
22 ImportedSymbolSummary as GraphImportedSymbolSummary,
23};
24use fallow_graph::graph::{
25 ExportTestReach as GraphExportTestReach, ExportTestReachResult as GraphExportTestReachResult,
26 TestMaskingState as GraphTestMaskingState,
27};
28
29#[derive(Debug)]
34pub struct RetainedModuleGraph {
35 inner: ModuleGraph,
36}
37
38impl RetainedModuleGraph {
39 #[must_use]
41 const fn new(inner: ModuleGraph) -> Self {
42 Self { inner }
43 }
44
45 pub(crate) const fn as_graph(&self) -> &ModuleGraph {
46 &self.inner
47 }
48
49 pub(crate) const fn static_test_coverage(&self) -> StaticTestCoverage<'_> {
51 StaticTestCoverage::new(&self.inner)
52 }
53
54 #[must_use]
56 pub fn module_count(&self) -> usize {
57 self.inner.module_count()
58 }
59
60 #[must_use]
62 pub fn edge_count(&self) -> usize {
63 self.inner.edge_count()
64 }
65
66 #[must_use]
68 pub(crate) fn public_export_keys(
69 &self,
70 public_entries: &FxHashSet<FileId>,
71 root: &Path,
72 ) -> FxHashSet<String> {
73 self.inner.public_export_keys(public_entries, root)
74 }
75
76 #[must_use]
78 pub fn direct_importer_count(&self, file_id: FileId) -> usize {
79 self.inner
80 .reverse_deps
81 .get(file_id.0 as usize)
82 .map_or(0, Vec::len)
83 }
84
85 #[must_use]
87 pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
88 self.inner
89 .direct_importer_summaries(target)
90 .into_iter()
91 .map(DirectImporterSummary::from)
92 .collect()
93 }
94}
95
96#[derive(Clone, Copy)]
106pub(crate) struct StaticTestCoverage<'a> {
107 graph: &'a ModuleGraph,
108 file_map: Option<&'a FxHashMap<FileId, FileId>>,
109}
110
111impl<'a> StaticTestCoverage<'a> {
112 pub(crate) const fn new(graph: &'a ModuleGraph) -> Self {
113 Self {
114 graph,
115 file_map: None,
116 }
117 }
118
119 pub(crate) const fn mapped(
122 graph: &'a ModuleGraph,
123 file_map: &'a FxHashMap<FileId, FileId>,
124 ) -> Self {
125 Self {
126 graph,
127 file_map: Some(file_map),
128 }
129 }
130
131 fn graph_file_id(self, file_id: FileId) -> Option<FileId> {
132 match self.file_map {
133 Some(file_map) => file_map.get(&file_id).copied(),
134 None => Some(file_id),
135 }
136 }
137
138 fn graph_export<'b>(
140 self,
141 file_id: FileId,
142 export: &'b fallow_graph::graph::ExportSymbol,
143 ) -> Option<(FileId, &'b fallow_graph::graph::ExportSymbol)>
144 where
145 'a: 'b,
146 {
147 if self.file_map.is_none() {
148 return Some((file_id, export));
149 }
150 let graph_file_id = self.graph_file_id(file_id)?;
151 let node = self.graph.modules.get(graph_file_id.0 as usize)?;
152 node.exports
153 .iter()
154 .find(|candidate| candidate.name == export.name)
155 .map(|candidate| (graph_file_id, candidate))
156 }
157
158 pub(crate) fn covers_file(self, file_id: FileId) -> bool {
159 self.graph_file_id(file_id)
160 .is_some_and(|graph_file_id| self.graph.is_test_reachable(graph_file_id))
161 }
162
163 pub(crate) fn covers_any_reference(
164 self,
165 file_id: FileId,
166 export: &fallow_graph::graph::ExportSymbol,
167 ) -> bool {
168 self.graph_export(file_id, export)
169 .is_some_and(|(_, export)| self.graph.is_any_test_reference_covered(export))
170 }
171
172 pub(crate) fn is_mocked_only(
175 self,
176 file_id: FileId,
177 export: &fallow_graph::graph::ExportSymbol,
178 ) -> bool {
179 if self.graph.test_masking_state() != GraphTestMaskingState::Active {
180 return false;
181 }
182 self.graph_export(file_id, export)
183 .is_some_and(|(graph_file_id, export)| {
184 self.graph
185 .export_test_reach(graph_file_id, export, &|_| false)
186 .reach
187 == GraphExportTestReach::MockedOnly
188 })
189 }
190}
191
192impl From<ModuleGraph> for RetainedModuleGraph {
193 fn from(inner: ModuleGraph) -> Self {
194 Self::new(inner)
195 }
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct NamedReExport {
201 pub path: PathBuf,
203 pub exported_name: String,
205 pub source_path: PathBuf,
207 pub imported_name: String,
209}
210
211#[must_use]
218pub fn named_re_exports(graph: &RetainedModuleGraph) -> Vec<NamedReExport> {
219 let graph = graph.as_graph();
220 graph
221 .modules
222 .iter()
223 .flat_map(|node| {
224 node.re_exports
225 .iter()
226 .filter(|edge| {
227 edge.imported_name != "*"
228 && edge.exported_name != "*"
229 && !(edge.span.start == 0 && edge.span.end == 0)
230 })
231 .filter_map(|edge| {
232 let source = graph.modules.get(edge.source_file.0 as usize)?;
233 Some(NamedReExport {
234 path: node.path.clone(),
235 exported_name: edge.exported_name.clone(),
236 source_path: source.path.clone(),
237 imported_name: edge.imported_name.clone(),
238 })
239 })
240 })
241 .collect()
242}
243
244#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct DirectImporterSummary {
247 pub source: FileId,
249 pub symbols: Vec<ImportedSymbolSummary>,
251}
252
253impl From<GraphDirectImporterSummary> for DirectImporterSummary {
254 fn from(summary: GraphDirectImporterSummary) -> Self {
255 Self {
256 source: summary.source,
257 symbols: summary.symbols.into_iter().map(Into::into).collect(),
258 }
259 }
260}
261
262#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct ImportedSymbolSummary {
265 pub imported: String,
267 pub local: String,
269 pub type_only: bool,
271}
272
273impl From<GraphImportedSymbolSummary> for ImportedSymbolSummary {
274 fn from(symbol: GraphImportedSymbolSummary) -> Self {
275 Self {
276 imported: symbol.imported,
277 local: symbol.local,
278 type_only: symbol.type_only,
279 }
280 }
281}
282
283#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct ModuleValueExport {
286 pub file_id: FileId,
288 pub name: String,
290 pub span_start: u32,
292 pub test_referenced: bool,
294}
295
296#[derive(Debug, Clone, Default, PartialEq, Eq)]
298pub struct ImpactClosurePaths {
299 pub in_diff: Vec<String>,
301 pub affected_not_shown: Vec<String>,
303 pub coordination_gap: Vec<CoordinationGapPaths>,
305}
306
307impl From<GraphImpactClosurePaths> for ImpactClosurePaths {
308 fn from(paths: GraphImpactClosurePaths) -> Self {
309 Self {
310 in_diff: paths.in_diff,
311 affected_not_shown: paths.affected_not_shown,
312 coordination_gap: paths
313 .coordination_gap
314 .into_iter()
315 .map(CoordinationGapPaths::from)
316 .collect(),
317 }
318 }
319}
320
321#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct CoordinationGapPaths {
324 pub changed_file: String,
326 pub consumer_file: String,
328 pub consumed_symbols: Vec<String>,
330}
331
332impl From<GraphCoordinationGapPaths> for CoordinationGapPaths {
333 fn from(paths: GraphCoordinationGapPaths) -> Self {
334 Self {
335 changed_file: paths.changed_file,
336 consumer_file: paths.consumer_file,
337 consumed_symbols: paths.consumed_symbols,
338 }
339 }
340}
341
342#[derive(Debug, Clone, Default, PartialEq, Eq)]
344pub struct PartitionOrderPaths {
345 pub units: Vec<ReviewUnitPaths>,
347 pub order: Vec<String>,
349 pub independent_slices: Vec<Vec<String>>,
352}
353
354impl From<GraphPartitionOrderPaths> for PartitionOrderPaths {
355 fn from(paths: GraphPartitionOrderPaths) -> Self {
356 Self {
357 units: paths.units.into_iter().map(ReviewUnitPaths::from).collect(),
358 order: paths.order,
359 independent_slices: paths.independent_slices,
360 }
361 }
362}
363
364#[derive(Debug, Clone, PartialEq, Eq)]
366pub struct ReviewUnitPaths {
367 pub module_dir: String,
369 pub files: Vec<String>,
371}
372
373impl From<GraphReviewUnitPaths> for ReviewUnitPaths {
374 fn from(paths: GraphReviewUnitPaths) -> Self {
375 Self {
376 module_dir: paths.module_dir,
377 files: paths.files,
378 }
379 }
380}
381
382#[derive(Debug, Clone, PartialEq, Eq)]
384pub struct FocusFileFactsPaths {
385 pub file: String,
387 pub fan_in: u32,
390 pub fan_out: u32,
392 pub dynamic_dispatch: bool,
396 pub re_export_indirection: bool,
399}
400
401impl From<GraphFocusFileFactsPaths> for FocusFileFactsPaths {
402 fn from(paths: GraphFocusFileFactsPaths) -> Self {
403 Self {
404 file: paths.file,
405 fan_in: paths.fan_in,
406 fan_out: paths.fan_out,
407 dynamic_dispatch: paths.dynamic_dispatch,
408 re_export_indirection: paths.re_export_indirection,
409 }
410 }
411}
412
413#[must_use]
416pub fn module_value_exports(graph: &RetainedModuleGraph) -> Vec<ModuleValueExport> {
417 module_value_exports_with_test_reach(graph, None)
418}
419
420#[must_use]
426pub fn module_value_exports_with_test_reach(
427 graph: &RetainedModuleGraph,
428 test_reach: Option<&crate::health::TestReachGraph>,
429) -> Vec<ModuleValueExport> {
430 let test_coverage = test_reach.map_or_else(
431 || graph.static_test_coverage(),
432 crate::health::TestReachGraph::static_test_coverage,
433 );
434 let graph = graph.as_graph();
435
436 graph
437 .modules
438 .iter()
439 .flat_map(|node| {
440 node.exports
441 .iter()
442 .filter(|export| !export.is_type_only)
443 .map(|export| ModuleValueExport {
444 file_id: node.file_id,
445 name: export.name.to_string(),
446 span_start: export.span.start,
447 test_referenced: test_coverage.covers_any_reference(node.file_id, export),
448 })
449 })
450 .collect()
451}
452
453#[must_use]
455pub fn impact_closure_for_changed_paths(
456 graph: &RetainedModuleGraph,
457 root: &Path,
458 changed_files: &FxHashSet<PathBuf>,
459) -> Option<ImpactClosurePaths> {
460 let graph = graph.as_graph();
461 let changed_ids = changed_file_ids(graph, changed_files);
462 if changed_ids.is_empty() {
463 return None;
464 }
465
466 let closure = graph.impact_closure(&changed_ids);
467 Some(graph.closure_with_paths(&closure, root).into())
468}
469
470#[must_use]
472pub fn partition_order_for_changed_paths(
473 graph: &RetainedModuleGraph,
474 root: &Path,
475 changed_files: &FxHashSet<PathBuf>,
476) -> Option<PartitionOrderPaths> {
477 let graph = graph.as_graph();
478 let changed_ids = changed_file_ids(graph, changed_files);
479 if changed_ids.is_empty() {
480 return None;
481 }
482
483 let partition = graph.partition_order(&changed_ids);
484 Some(graph.partition_order_with_paths(&partition, root).into())
485}
486
487#[must_use]
489pub fn focus_facts_for_changed_paths(
490 graph: &RetainedModuleGraph,
491 root: &Path,
492 changed_files: &FxHashSet<PathBuf>,
493) -> Option<Vec<FocusFileFactsPaths>> {
494 let graph = graph.as_graph();
495 let changed_ids = changed_file_ids(graph, changed_files);
496 if changed_ids.is_empty() {
497 return None;
498 }
499
500 let facts = graph.focus_file_facts(&changed_ids);
501 Some(
502 graph
503 .focus_facts_with_paths(&facts, root)
504 .into_iter()
505 .map(FocusFileFactsPaths::from)
506 .collect(),
507 )
508}
509
510#[must_use]
512pub fn export_lines_for_changed_paths(
513 graph: &RetainedModuleGraph,
514 root: &Path,
515 changed_files: &FxHashSet<PathBuf>,
516) -> Option<FxHashMap<String, Vec<(String, u32)>>> {
517 let graph = graph.as_graph();
518 let changed_norm = normalized_changed_paths(changed_files);
519 let mut map: FxHashMap<String, Vec<(String, u32)>> = FxHashMap::default();
520 for module in &graph.modules {
521 let abs = normalize_path(&module.path);
522 if !changed_norm.contains(&abs) || module.exports.is_empty() {
523 continue;
524 }
525 let Ok(content) = std::fs::read_to_string(&module.path) else {
526 continue;
527 };
528 let offsets = fallow_types::extract::compute_line_offsets(&content);
529 let exports: Vec<(String, u32)> = module
530 .exports
531 .iter()
532 .map(|export| {
533 let (line, _) =
534 fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start);
535 (export.name.to_string(), line)
536 })
537 .collect();
538 map.insert(relative_key_path(&module.path, root), exports);
539 }
540 Some(map)
541}
542
543#[derive(Debug, Clone, PartialEq, Eq)]
546pub struct ConsumerSearchGapPaths {
547 pub consumer_file: String,
549 pub check: crate::search_visibility::SearchCheck,
551}
552
553#[derive(Debug, Clone, PartialEq, Eq)]
555pub struct ExportSearchGapPaths {
556 pub file: String,
558 pub export_name: String,
560 pub line: u32,
562 pub declaration_lines: (u32, u32),
565 pub consumers: Vec<ConsumerSearchGapPaths>,
568}
569
570#[must_use]
573pub fn export_names_in_source(path: &Path, source: &str) -> FxHashSet<String> {
574 let module = fallow_extract::parse_source_to_module(FileId(0), path, source, 0, false);
575 module
576 .exports
577 .iter()
578 .map(|export| export.name.to_string())
579 .collect()
580}
581
582#[derive(Debug, Clone, PartialEq, Eq)]
588pub struct ChangedExport {
589 file_id: FileId,
590 export_index: usize,
591 pub file: String,
593 pub export_name: String,
595 pub line: u32,
597 pub declaration_lines: (u32, u32),
600 pub is_type_only: bool,
602 pub literal_value: bool,
605 pub is_re_export: bool,
607}
608
609#[must_use]
615pub fn changed_exports_for_changed_paths(
616 graph: &RetainedModuleGraph,
617 root: &Path,
618 changed_files: &FxHashSet<PathBuf>,
619) -> Option<Vec<ChangedExport>> {
620 let graph = graph.as_graph();
621 let mut changed_ids = changed_file_ids(graph, changed_files);
622 if changed_ids.is_empty() {
623 return None;
624 }
625 changed_ids.sort_unstable_by_key(|id| id.0);
626 let mut changed_exports = Vec::new();
627 for file_id in changed_ids {
628 let Some(module) = graph.modules.get(file_id.0 as usize) else {
629 continue;
630 };
631 if module.exports.is_empty() {
632 continue;
633 }
634 let Ok(source) = std::fs::read_to_string(&module.path) else {
635 continue;
636 };
637 changed_exports.extend(module_exports(graph, root, file_id, &source));
638 }
639 Some(changed_exports)
640}
641
642pub(crate) fn module_exports(
645 graph: &ModuleGraph,
646 root: &Path,
647 file_id: FileId,
648 source: &str,
649) -> Vec<ChangedExport> {
650 let Some(module) = graph.modules.get(file_id.0 as usize) else {
651 return Vec::new();
652 };
653 if module.exports.is_empty() {
654 return Vec::new();
655 }
656 let offsets = fallow_types::extract::compute_line_offsets(source);
657 let starts: Vec<u32> = module
658 .exports
659 .iter()
660 .map(|export| export.span.start)
661 .collect();
662 let declarations = crate::search_visibility::export_declarations(&module.path, source, &starts);
663 let file = relative_key_path(&module.path, root);
664 module
665 .exports
666 .iter()
667 .enumerate()
668 .map(|(export_index, export)| {
669 let line =
670 fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start).0;
671 let declaration = declarations.get(&export.span.start);
672 ChangedExport {
673 file_id,
674 export_index,
675 file: file.clone(),
676 export_name: export.name.to_string(),
677 line,
678 declaration_lines: declaration.map_or((line, line), |found| found.lines),
679 is_type_only: export.is_type_only,
680 literal_value: declaration.is_some_and(|found| found.literal_value),
681 is_re_export: declaration.is_some_and(|found| found.is_re_export),
682 }
683 })
684 .collect()
685}
686
687#[must_use]
694pub fn search_gaps_for_changed_paths(
695 graph: &RetainedModuleGraph,
696 root: &Path,
697 changed_files: &FxHashSet<PathBuf>,
698 changed_exports: &[ChangedExport],
699) -> Option<Vec<ExportSearchGapPaths>> {
700 use crate::search_visibility::{SearchTarget, SourceCache};
701 use fallow_graph::graph::ExportNamespace;
702 use fallow_types::trace::SearchVisibility;
703
704 let graph = graph.as_graph();
705 let changed_set: FxHashSet<FileId> =
706 changed_file_ids(graph, changed_files).into_iter().collect();
707 if changed_set.is_empty() {
708 return None;
709 }
710 let mut sources = SourceCache::new(graph);
711 let mut gaps = Vec::new();
712 for changed in changed_exports {
713 let Some(export) = graph
714 .modules
715 .get(changed.file_id.0 as usize)
716 .and_then(|module| module.exports.get(changed.export_index))
717 else {
718 continue;
719 };
720 let mut seen = FxHashSet::default();
721 let candidates: Vec<_> = export
722 .references
723 .iter()
724 .filter(|reference| {
725 !changed_set.contains(&reference.from_file)
726 && graph
727 .modules
728 .get(reference.from_file.0 as usize)
729 .is_some_and(fallow_graph::graph::ModuleNode::is_reachable)
730 && seen.insert(reference.from_file)
731 })
732 .collect();
733 if candidates.is_empty() {
734 continue;
735 }
736 let namespace = if export.is_type_only {
737 ExportNamespace::Type
738 } else {
739 ExportNamespace::Value
740 };
741 let target = SearchTarget::new(
742 graph,
743 &mut sources,
744 changed.file_id,
745 &changed.export_name,
746 namespace,
747 );
748 let mut consumers: Vec<ConsumerSearchGapPaths> = candidates
749 .into_iter()
750 .filter_map(|reference| {
751 let check = target.check(graph, &mut sources, reference)?;
752 if check.visibility == SearchVisibility::Found {
753 return None;
754 }
755 let consumer = graph.modules.get(reference.from_file.0 as usize)?;
756 Some(ConsumerSearchGapPaths {
757 consumer_file: relative_key_path(&consumer.path, root),
758 check,
759 })
760 })
761 .collect();
762 if consumers.is_empty() {
763 continue;
764 }
765 consumers.sort_by(|a, b| a.consumer_file.cmp(&b.consumer_file));
766 gaps.push(ExportSearchGapPaths {
767 file: changed.file.clone(),
768 export_name: changed.export_name.clone(),
769 line: changed.line,
770 declaration_lines: changed.declaration_lines,
771 consumers,
772 });
773 }
774 Some(gaps)
775}
776
777const E2E_RUNNER_PACKAGES: &[&str] = &["@playwright/test", "playwright", "cypress"];
780
781#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
783#[serde(rename_all = "kebab-case")]
784pub enum ExportTestReach {
785 Direct,
787 Transitive,
789 MockedOnly,
792 None,
794 NoneFile,
796}
797
798impl From<GraphExportTestReach> for ExportTestReach {
799 fn from(reach: GraphExportTestReach) -> Self {
800 match reach {
801 GraphExportTestReach::Direct => Self::Direct,
802 GraphExportTestReach::Transitive => Self::Transitive,
803 GraphExportTestReach::MockedOnly => Self::MockedOnly,
804 GraphExportTestReach::None => Self::None,
805 GraphExportTestReach::NoneFile => Self::NoneFile,
806 }
807 }
808}
809
810#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
812pub enum TestMaskingState {
813 Active,
815 NoMocks,
817 Capped,
819}
820
821impl From<GraphTestMaskingState> for TestMaskingState {
822 fn from(state: GraphTestMaskingState) -> Self {
823 match state {
824 GraphTestMaskingState::Active => Self::Active,
825 GraphTestMaskingState::NoMocks => Self::NoMocks,
826 GraphTestMaskingState::Capped => Self::Capped,
827 }
828 }
829}
830
831#[derive(Debug, Clone, PartialEq, Eq)]
833pub struct ExportTestReachPaths {
834 pub file: String,
836 pub export_name: String,
838 pub line: u32,
840 pub declaration_lines: (u32, u32),
842 pub literal_value: bool,
844 pub reach: ExportTestReach,
846 pub tests: Vec<String>,
849 pub mocked_targets: Vec<String>,
851}
852
853#[derive(Debug, Clone, PartialEq, Eq)]
855pub struct TestReachPaths {
856 pub has_tests: bool,
859 pub masking: TestMaskingState,
861 pub has_e2e_runner: bool,
863 pub exports: Vec<ExportTestReachPaths>,
865}
866
867#[must_use]
875pub fn test_reach_for_changed_paths(
876 graph: &RetainedModuleGraph,
877 root: &Path,
878 changed_exports: &[ChangedExport],
879 is_test_path: &dyn Fn(&str) -> bool,
880) -> Option<TestReachPaths> {
881 let graph = graph.as_graph();
882 let mut test_files: FxHashMap<FileId, bool> = FxHashMap::default();
883 let mut is_test_file = |file_id: FileId| -> bool {
884 *test_files.entry(file_id).or_insert_with(|| {
885 graph.test_entry_points.contains(&file_id)
886 || graph
887 .modules
888 .get(file_id.0 as usize)
889 .is_some_and(|module| is_test_path(&relative_key_path(&module.path, root)))
890 })
891 };
892 let has_tests = !graph.test_entry_points.is_empty();
893 let exports: Vec<ExportTestReachPaths> = changed_exports
894 .iter()
895 .filter_map(|changed| classify_export_test_reach(graph, root, changed, &mut is_test_file))
896 .collect();
897 if exports.is_empty() {
898 return None;
899 }
900 let has_e2e_runner = E2E_RUNNER_PACKAGES.iter().any(|name| {
901 graph.package_usage.contains_key(*name) || graph.type_only_package_usage.contains_key(*name)
902 });
903 Some(TestReachPaths {
904 has_tests,
905 masking: graph.test_masking_state().into(),
906 has_e2e_runner,
907 exports,
908 })
909}
910
911pub(crate) fn classify_export_test_reach(
916 graph: &ModuleGraph,
917 root: &Path,
918 changed: &ChangedExport,
919 is_test_file: &mut dyn FnMut(FileId) -> bool,
920) -> Option<ExportTestReachPaths> {
921 if changed.is_type_only || changed.is_re_export {
922 return None;
923 }
924 let module = graph.modules.get(changed.file_id.0 as usize)?;
925 let export = module.exports.get(changed.export_index)?;
926 if !is_reach_subject(&module.path) || is_test_file(changed.file_id) {
927 return None;
928 }
929 let result = if graph.test_entry_points.is_empty() {
930 GraphExportTestReachResult {
931 reach: GraphExportTestReach::NoneFile,
932 tests: Vec::new(),
933 mocked_targets: Vec::new(),
934 }
935 } else {
936 let test_flags: FxHashMap<FileId, bool> = export
937 .references
938 .iter()
939 .map(|reference| (reference.from_file, is_test_file(reference.from_file)))
940 .collect();
941 graph.export_test_reach(changed.file_id, export, &|file_id| {
942 test_flags.get(&file_id).copied().unwrap_or(false)
943 })
944 };
945 let paths_of = |files: &[FileId]| -> Vec<String> {
946 let mut paths: Vec<String> = files
947 .iter()
948 .filter_map(|file_id| graph.modules.get(file_id.0 as usize))
949 .map(|node| relative_key_path(&node.path, root))
950 .collect();
951 paths.sort_unstable();
952 paths
953 };
954 Some(ExportTestReachPaths {
955 file: changed.file.clone(),
956 export_name: changed.export_name.clone(),
957 line: changed.line,
958 declaration_lines: changed.declaration_lines,
959 literal_value: changed.literal_value,
960 reach: result.reach.into(),
961 tests: paths_of(&result.tests),
962 mocked_targets: paths_of(&result.mocked_targets),
963 })
964}
965
966fn is_reach_subject(path: &Path) -> bool {
969 if fallow_graph::graph::is_declaration_file_path(path) {
970 return false;
971 }
972 !path
973 .extension()
974 .and_then(|extension| extension.to_str())
975 .is_some_and(|extension| matches!(extension, "css" | "scss" | "less" | "sass"))
976}
977
978#[must_use]
980pub fn internal_consumers_for_changed_paths(
981 graph: &RetainedModuleGraph,
982 root: &Path,
983 changed_files: &FxHashSet<PathBuf>,
984) -> Option<FxHashMap<String, u64>> {
985 let graph = graph.as_graph();
986 let changed_norm = normalized_changed_paths(changed_files);
987 let id_to_norm: FxHashMap<FileId, String> = graph
988 .modules
989 .iter()
990 .map(|module| (module.file_id, normalize_path(&module.path)))
991 .collect();
992
993 let mut map: FxHashMap<String, u64> = FxHashMap::default();
994 for module in &graph.modules {
995 let abs = normalize_path(&module.path);
996 if !changed_norm.contains(&abs) {
997 continue;
998 }
999 let count = graph
1000 .importers_of(module.file_id)
1001 .iter()
1002 .filter(|imp| {
1003 id_to_norm
1004 .get(imp)
1005 .is_none_or(|p| !changed_norm.contains(p))
1006 })
1007 .count() as u64;
1008 map.insert(relative_key_path(&module.path, root), count);
1009 }
1010 Some(map)
1011}
1012
1013#[must_use]
1020pub fn test_adjacency_for_changed_paths(
1021 graph: &RetainedModuleGraph,
1022 root: &Path,
1023 changed_files: &FxHashSet<PathBuf>,
1024 is_test_path: &dyn Fn(&str) -> bool,
1025) -> Option<FxHashMap<String, TestAdjacency>> {
1026 let graph = graph.as_graph();
1027 if !graph
1030 .modules
1031 .iter()
1032 .any(|module| is_test_path(&relative_key_path(&module.path, root)))
1033 {
1034 return None;
1035 }
1036 let changed_norm = normalized_changed_paths(changed_files);
1037 let mut map: FxHashMap<String, TestAdjacency> = FxHashMap::default();
1038 for module in &graph.modules {
1039 if !changed_norm.contains(&normalize_path(&module.path)) {
1040 continue;
1041 }
1042 let rel = relative_key_path(&module.path, root);
1043 if is_test_path(&rel) {
1044 continue;
1045 }
1046 let mut adjacency = TestAdjacency::None;
1047 for importer in graph.importers_of(module.file_id) {
1048 let Some(node) = graph.modules.get(importer.0 as usize) else {
1049 continue;
1050 };
1051 if !is_test_path(&relative_key_path(&node.path, root)) {
1052 continue;
1053 }
1054 if changed_norm.contains(&normalize_path(&node.path)) {
1055 adjacency = TestAdjacency::Changed;
1056 break;
1057 }
1058 adjacency = TestAdjacency::Untouched;
1059 }
1060 map.insert(rel, adjacency);
1061 }
1062 if map.is_empty() {
1063 return None;
1064 }
1065 Some(map)
1066}
1067
1068#[derive(Debug, Clone, Default, PartialEq, Eq)]
1070pub struct PackageImporters {
1071 pub importers: Vec<FileId>,
1076 pub out_of_diff: Vec<FileId>,
1078}
1079
1080#[must_use]
1088pub fn package_importers_for_changed_paths(
1089 graph: &RetainedModuleGraph,
1090 changed_files: &FxHashSet<PathBuf>,
1091) -> Option<FxHashMap<String, PackageImporters>> {
1092 let graph = graph.as_graph();
1093 if graph.package_usage.is_empty() && graph.type_only_package_usage.is_empty() {
1094 return None;
1095 }
1096 let changed_norm = normalized_changed_paths(changed_files);
1097 let id_to_norm: FxHashMap<FileId, String> = graph
1098 .modules
1099 .iter()
1100 .map(|module| (module.file_id, normalize_path(&module.path)))
1101 .collect();
1102 let mut usage: FxHashMap<&str, Vec<FileId>> = FxHashMap::default();
1103 for (package, files) in graph
1104 .package_usage
1105 .iter()
1106 .chain(graph.type_only_package_usage.iter())
1107 {
1108 usage
1109 .entry(package.as_str())
1110 .or_default()
1111 .extend(files.iter().copied());
1112 }
1113 let map = usage
1114 .into_iter()
1115 .map(|(package, files)| {
1116 let mut importers: Vec<FileId> = files;
1117 importers.sort_unstable_by_key(|id| id.0);
1118 importers.dedup();
1119 let out_of_diff: Vec<FileId> = importers
1120 .iter()
1121 .copied()
1122 .filter(|id| id_to_norm.get(id).is_none_or(|p| !changed_norm.contains(p)))
1123 .collect();
1124 (
1125 package.to_string(),
1126 PackageImporters {
1127 importers,
1128 out_of_diff,
1129 },
1130 )
1131 })
1132 .collect();
1133 Some(map)
1134}
1135
1136fn changed_file_ids(graph: &ModuleGraph, changed_files: &FxHashSet<PathBuf>) -> Vec<FileId> {
1137 let path_to_id: FxHashMap<String, FileId> = graph
1138 .modules
1139 .iter()
1140 .map(|module| (normalize_path(&module.path), module.file_id))
1141 .collect();
1142
1143 changed_files
1144 .iter()
1145 .filter_map(|path| path_to_id.get(&normalize_path(path)).copied())
1146 .collect()
1147}
1148
1149fn normalized_changed_paths(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<String> {
1150 changed_files
1151 .iter()
1152 .map(|path| normalize_path(path))
1153 .collect()
1154}
1155
1156fn normalize_path(path: &Path) -> String {
1157 path.to_string_lossy().replace('\\', "/")
1158}
1159
1160pub fn relative_key_path(path: &Path, root: &Path) -> String {
1168 let simple_path = dunce::simplified(path);
1169 let simple_root = dunce::simplified(root);
1170 simple_path
1171 .strip_prefix(simple_root)
1172 .unwrap_or(simple_path)
1173 .to_string_lossy()
1174 .replace('\\', "/")
1175}
1176
1177#[cfg(test)]
1178mod tests {
1179 use super::{RetainedModuleGraph, module_value_exports};
1180 use fallow_graph::graph::ModuleGraph;
1181 use fallow_graph::resolve::{
1182 ResolveResult, ResolvedImport, ResolvedModule, ResolvedReplacedModuleTarget,
1183 };
1184 use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
1185 use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
1186 use std::path::PathBuf;
1187
1188 fn import(target: FileId, imported_name: ImportedName) -> ResolvedImport {
1189 import_with_mechanism(target, imported_name, false)
1190 }
1191
1192 fn import_with_mechanism(
1193 target: FileId,
1194 imported_name: ImportedName,
1195 commonjs: bool,
1196 ) -> ResolvedImport {
1197 ResolvedImport {
1198 info: ImportInfo {
1199 source: "./target".to_string(),
1200 imported_name,
1201 local_name: "target".to_string(),
1202 is_type_only: false,
1203 is_type_only_star: false,
1204 from_style: false,
1205 span: oxc_span::Span::new(0, 10),
1206 source_span: oxc_span::Span::default(),
1207 },
1208 target: if commonjs {
1209 ResolveResult::CommonJsInternalModule(target)
1210 } else {
1211 ResolveResult::InternalModule(target)
1212 },
1213 }
1214 }
1215
1216 fn value_export(name: &str, span_start: u32) -> ExportInfo {
1217 ExportInfo {
1218 name: ExportName::Named(name.to_string()),
1219 local_name: Some(name.to_string()),
1220 is_type_only: false,
1221 visibility: VisibilityTag::None,
1222 expected_unused_reason: None,
1223 span: oxc_span::Span::new(span_start, span_start + 10),
1224 members: Vec::new(),
1225 is_side_effect_used: false,
1226 super_class: None,
1227 deprecated: false,
1228 deprecated_reason: None,
1229 }
1230 }
1231
1232 fn mixed_root_graph(unmasked_root_imports_export: bool) -> RetainedModuleGraph {
1233 let files: Vec<_> = (0..3)
1234 .map(|id| DiscoveredFile {
1235 id: FileId(id),
1236 path: PathBuf::from(format!("/project/file{id}.ts")),
1237 size_bytes: 1,
1238 })
1239 .collect();
1240 let modules = vec![
1241 ResolvedModule {
1242 file_id: FileId(0),
1243 path: files[0].path.clone(),
1244 resolved_imports: vec![import(
1245 FileId(2),
1246 ImportedName::Named("target".to_string()),
1247 )],
1248 ..ResolvedModule::default()
1249 },
1250 ResolvedModule {
1251 file_id: FileId(1),
1252 path: files[1].path.clone(),
1253 resolved_imports: vec![import(
1254 FileId(2),
1255 if unmasked_root_imports_export {
1256 ImportedName::Named("target".to_string())
1257 } else {
1258 ImportedName::SideEffect
1259 },
1260 )],
1261 ..ResolvedModule::default()
1262 },
1263 ResolvedModule {
1264 file_id: FileId(2),
1265 path: files[2].path.clone(),
1266 exports: vec![value_export("target", 0)].into(),
1267 ..ResolvedModule::default()
1268 },
1269 ];
1270 let test_entry_points = vec![
1271 EntryPoint {
1272 path: files[0].path.clone(),
1273 source: EntryPointSource::TestFile,
1274 },
1275 EntryPoint {
1276 path: files[1].path.clone(),
1277 source: EntryPointSource::TestFile,
1278 },
1279 ];
1280 let graph = ModuleGraph::build_with_reachability_roots_and_replacements(
1281 &modules,
1282 &[ResolvedReplacedModuleTarget {
1283 source_file: FileId(0),
1284 target_file: FileId(2),
1285 }],
1286 &test_entry_points,
1287 &[],
1288 &test_entry_points,
1289 &files,
1290 );
1291 RetainedModuleGraph::from(graph)
1292 }
1293
1294 #[test]
1295 fn export_coverage_requires_one_root_to_reach_consumer_and_target() {
1296 let graph = mixed_root_graph(false);
1297
1298 let exports = module_value_exports(&graph);
1299
1300 assert_eq!(exports.len(), 1);
1301 assert!(!exports[0].test_referenced);
1302 }
1303
1304 #[test]
1305 fn export_coverage_accepts_an_unmasked_correlated_reference() {
1306 let graph = mixed_root_graph(true);
1307
1308 let exports = module_value_exports(&graph);
1309
1310 assert_eq!(exports.len(), 1);
1311 assert!(exports[0].test_referenced);
1312 }
1313
1314 #[test]
1315 fn commonjs_reference_does_not_credit_a_mocked_esm_export() {
1316 let files: Vec<_> = (0..2)
1317 .map(|id| DiscoveredFile {
1318 id: FileId(id),
1319 path: PathBuf::from(format!("/project/file{id}.ts")),
1320 size_bytes: 1,
1321 })
1322 .collect();
1323 let modules = vec![
1324 ResolvedModule {
1325 file_id: FileId(0),
1326 path: files[0].path.clone(),
1327 resolved_imports: vec![
1328 import_with_mechanism(
1329 FileId(1),
1330 ImportedName::Named("esmOnly".to_string()),
1331 false,
1332 ),
1333 import_with_mechanism(
1334 FileId(1),
1335 ImportedName::Named("required".to_string()),
1336 true,
1337 ),
1338 ],
1339 ..ResolvedModule::default()
1340 },
1341 ResolvedModule {
1342 file_id: FileId(1),
1343 path: files[1].path.clone(),
1344 exports: vec![value_export("esmOnly", 0), value_export("required", 20)].into(),
1345 ..ResolvedModule::default()
1346 },
1347 ];
1348 let test_entry_points = vec![EntryPoint {
1349 path: files[0].path.clone(),
1350 source: EntryPointSource::TestFile,
1351 }];
1352 let graph =
1353 RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1354 &modules,
1355 &[ResolvedReplacedModuleTarget {
1356 source_file: FileId(0),
1357 target_file: FileId(1),
1358 }],
1359 &test_entry_points,
1360 &[],
1361 &test_entry_points,
1362 &files,
1363 ));
1364
1365 let exports = module_value_exports(&graph);
1366 let coverage: rustc_hash::FxHashMap<_, _> = exports
1367 .into_iter()
1368 .map(|export| (export.name, export.test_referenced))
1369 .collect();
1370
1371 assert_eq!(coverage.get("esmOnly"), Some(&false));
1372 assert_eq!(coverage.get("required"), Some(&true));
1373 }
1374
1375 #[test]
1376 fn type_only_test_import_does_not_credit_a_value_export() {
1377 let files: Vec<_> = (0..3)
1378 .map(|id| DiscoveredFile {
1379 id: FileId(id),
1380 path: PathBuf::from(format!("/project/file{id}.ts")),
1381 size_bytes: 1,
1382 })
1383 .collect();
1384 let mut type_only = import(FileId(1), ImportedName::Named("typed".to_string()));
1385 type_only.info.is_type_only = true;
1386 let modules = vec![
1387 ResolvedModule {
1388 file_id: FileId(0),
1389 path: files[0].path.clone(),
1390 resolved_imports: vec![
1391 type_only,
1392 import(FileId(2), ImportedName::Named("called".to_string())),
1393 ],
1394 ..ResolvedModule::default()
1395 },
1396 ResolvedModule {
1397 file_id: FileId(1),
1398 path: files[1].path.clone(),
1399 exports: vec![value_export("typed", 0)].into(),
1400 ..ResolvedModule::default()
1401 },
1402 ResolvedModule {
1403 file_id: FileId(2),
1404 path: files[2].path.clone(),
1405 exports: vec![value_export("called", 0)].into(),
1406 ..ResolvedModule::default()
1407 },
1408 ];
1409 let test_entry_points = vec![EntryPoint {
1410 path: files[0].path.clone(),
1411 source: EntryPointSource::TestFile,
1412 }];
1413 let graph =
1414 RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1415 &modules,
1416 &[],
1417 &test_entry_points,
1418 &[],
1419 &test_entry_points,
1420 &files,
1421 ));
1422
1423 let coverage: rustc_hash::FxHashMap<_, _> = module_value_exports(&graph)
1424 .into_iter()
1425 .map(|export| (export.name, export.test_referenced))
1426 .collect();
1427
1428 assert_eq!(coverage.get("typed"), Some(&false));
1429 assert_eq!(coverage.get("called"), Some(&true));
1430 }
1431}