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 DirectImporterSummary {
201 pub source: FileId,
203 pub symbols: Vec<ImportedSymbolSummary>,
205}
206
207impl From<GraphDirectImporterSummary> for DirectImporterSummary {
208 fn from(summary: GraphDirectImporterSummary) -> Self {
209 Self {
210 source: summary.source,
211 symbols: summary.symbols.into_iter().map(Into::into).collect(),
212 }
213 }
214}
215
216#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct ImportedSymbolSummary {
219 pub imported: String,
221 pub local: String,
223 pub type_only: bool,
225}
226
227impl From<GraphImportedSymbolSummary> for ImportedSymbolSummary {
228 fn from(symbol: GraphImportedSymbolSummary) -> Self {
229 Self {
230 imported: symbol.imported,
231 local: symbol.local,
232 type_only: symbol.type_only,
233 }
234 }
235}
236
237#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct ModuleValueExport {
240 pub file_id: FileId,
242 pub name: String,
244 pub span_start: u32,
246 pub test_referenced: bool,
248}
249
250#[derive(Debug, Clone, Default, PartialEq, Eq)]
252pub struct ImpactClosurePaths {
253 pub in_diff: Vec<String>,
255 pub affected_not_shown: Vec<String>,
257 pub coordination_gap: Vec<CoordinationGapPaths>,
259}
260
261impl From<GraphImpactClosurePaths> for ImpactClosurePaths {
262 fn from(paths: GraphImpactClosurePaths) -> Self {
263 Self {
264 in_diff: paths.in_diff,
265 affected_not_shown: paths.affected_not_shown,
266 coordination_gap: paths
267 .coordination_gap
268 .into_iter()
269 .map(CoordinationGapPaths::from)
270 .collect(),
271 }
272 }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct CoordinationGapPaths {
278 pub changed_file: String,
280 pub consumer_file: String,
282 pub consumed_symbols: Vec<String>,
284}
285
286impl From<GraphCoordinationGapPaths> for CoordinationGapPaths {
287 fn from(paths: GraphCoordinationGapPaths) -> Self {
288 Self {
289 changed_file: paths.changed_file,
290 consumer_file: paths.consumer_file,
291 consumed_symbols: paths.consumed_symbols,
292 }
293 }
294}
295
296#[derive(Debug, Clone, Default, PartialEq, Eq)]
298pub struct PartitionOrderPaths {
299 pub units: Vec<ReviewUnitPaths>,
301 pub order: Vec<String>,
303 pub independent_slices: Vec<Vec<String>>,
306}
307
308impl From<GraphPartitionOrderPaths> for PartitionOrderPaths {
309 fn from(paths: GraphPartitionOrderPaths) -> Self {
310 Self {
311 units: paths.units.into_iter().map(ReviewUnitPaths::from).collect(),
312 order: paths.order,
313 independent_slices: paths.independent_slices,
314 }
315 }
316}
317
318#[derive(Debug, Clone, PartialEq, Eq)]
320pub struct ReviewUnitPaths {
321 pub module_dir: String,
323 pub files: Vec<String>,
325}
326
327impl From<GraphReviewUnitPaths> for ReviewUnitPaths {
328 fn from(paths: GraphReviewUnitPaths) -> Self {
329 Self {
330 module_dir: paths.module_dir,
331 files: paths.files,
332 }
333 }
334}
335
336#[derive(Debug, Clone, PartialEq, Eq)]
338pub struct FocusFileFactsPaths {
339 pub file: String,
341 pub fan_in: u32,
344 pub fan_out: u32,
346 pub dynamic_dispatch: bool,
350 pub re_export_indirection: bool,
353}
354
355impl From<GraphFocusFileFactsPaths> for FocusFileFactsPaths {
356 fn from(paths: GraphFocusFileFactsPaths) -> Self {
357 Self {
358 file: paths.file,
359 fan_in: paths.fan_in,
360 fan_out: paths.fan_out,
361 dynamic_dispatch: paths.dynamic_dispatch,
362 re_export_indirection: paths.re_export_indirection,
363 }
364 }
365}
366
367#[must_use]
370pub fn module_value_exports(graph: &RetainedModuleGraph) -> Vec<ModuleValueExport> {
371 module_value_exports_with_test_reach(graph, None)
372}
373
374#[must_use]
380pub fn module_value_exports_with_test_reach(
381 graph: &RetainedModuleGraph,
382 test_reach: Option<&crate::health::TestReachGraph>,
383) -> Vec<ModuleValueExport> {
384 let test_coverage = test_reach.map_or_else(
385 || graph.static_test_coverage(),
386 crate::health::TestReachGraph::static_test_coverage,
387 );
388 let graph = graph.as_graph();
389
390 graph
391 .modules
392 .iter()
393 .flat_map(|node| {
394 node.exports
395 .iter()
396 .filter(|export| !export.is_type_only)
397 .map(|export| ModuleValueExport {
398 file_id: node.file_id,
399 name: export.name.to_string(),
400 span_start: export.span.start,
401 test_referenced: test_coverage.covers_any_reference(node.file_id, export),
402 })
403 })
404 .collect()
405}
406
407#[must_use]
409pub fn impact_closure_for_changed_paths(
410 graph: &RetainedModuleGraph,
411 root: &Path,
412 changed_files: &FxHashSet<PathBuf>,
413) -> Option<ImpactClosurePaths> {
414 let graph = graph.as_graph();
415 let changed_ids = changed_file_ids(graph, changed_files);
416 if changed_ids.is_empty() {
417 return None;
418 }
419
420 let closure = graph.impact_closure(&changed_ids);
421 Some(graph.closure_with_paths(&closure, root).into())
422}
423
424#[must_use]
426pub fn partition_order_for_changed_paths(
427 graph: &RetainedModuleGraph,
428 root: &Path,
429 changed_files: &FxHashSet<PathBuf>,
430) -> Option<PartitionOrderPaths> {
431 let graph = graph.as_graph();
432 let changed_ids = changed_file_ids(graph, changed_files);
433 if changed_ids.is_empty() {
434 return None;
435 }
436
437 let partition = graph.partition_order(&changed_ids);
438 Some(graph.partition_order_with_paths(&partition, root).into())
439}
440
441#[must_use]
443pub fn focus_facts_for_changed_paths(
444 graph: &RetainedModuleGraph,
445 root: &Path,
446 changed_files: &FxHashSet<PathBuf>,
447) -> Option<Vec<FocusFileFactsPaths>> {
448 let graph = graph.as_graph();
449 let changed_ids = changed_file_ids(graph, changed_files);
450 if changed_ids.is_empty() {
451 return None;
452 }
453
454 let facts = graph.focus_file_facts(&changed_ids);
455 Some(
456 graph
457 .focus_facts_with_paths(&facts, root)
458 .into_iter()
459 .map(FocusFileFactsPaths::from)
460 .collect(),
461 )
462}
463
464#[must_use]
466pub fn export_lines_for_changed_paths(
467 graph: &RetainedModuleGraph,
468 root: &Path,
469 changed_files: &FxHashSet<PathBuf>,
470) -> Option<FxHashMap<String, Vec<(String, u32)>>> {
471 let graph = graph.as_graph();
472 let changed_norm = normalized_changed_paths(changed_files);
473 let mut map: FxHashMap<String, Vec<(String, u32)>> = FxHashMap::default();
474 for module in &graph.modules {
475 let abs = normalize_path(&module.path);
476 if !changed_norm.contains(&abs) || module.exports.is_empty() {
477 continue;
478 }
479 let Ok(content) = std::fs::read_to_string(&module.path) else {
480 continue;
481 };
482 let offsets = fallow_types::extract::compute_line_offsets(&content);
483 let exports: Vec<(String, u32)> = module
484 .exports
485 .iter()
486 .map(|export| {
487 let (line, _) =
488 fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start);
489 (export.name.to_string(), line)
490 })
491 .collect();
492 map.insert(relative_key_path(&module.path, root), exports);
493 }
494 Some(map)
495}
496
497#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct ConsumerSearchGapPaths {
501 pub consumer_file: String,
503 pub check: crate::search_visibility::SearchCheck,
505}
506
507#[derive(Debug, Clone, PartialEq, Eq)]
509pub struct ExportSearchGapPaths {
510 pub file: String,
512 pub export_name: String,
514 pub line: u32,
516 pub declaration_lines: (u32, u32),
519 pub consumers: Vec<ConsumerSearchGapPaths>,
522}
523
524#[must_use]
527pub fn export_names_in_source(path: &Path, source: &str) -> FxHashSet<String> {
528 let module = fallow_extract::parse_source_to_module(FileId(0), path, source, 0, false);
529 module
530 .exports
531 .iter()
532 .map(|export| export.name.to_string())
533 .collect()
534}
535
536#[derive(Debug, Clone, PartialEq, Eq)]
542pub struct ChangedExport {
543 file_id: FileId,
544 export_index: usize,
545 pub file: String,
547 pub export_name: String,
549 pub line: u32,
551 pub declaration_lines: (u32, u32),
554 pub is_type_only: bool,
556 pub literal_value: bool,
559 pub is_re_export: bool,
561}
562
563#[must_use]
569pub fn changed_exports_for_changed_paths(
570 graph: &RetainedModuleGraph,
571 root: &Path,
572 changed_files: &FxHashSet<PathBuf>,
573) -> Option<Vec<ChangedExport>> {
574 let graph = graph.as_graph();
575 let mut changed_ids = changed_file_ids(graph, changed_files);
576 if changed_ids.is_empty() {
577 return None;
578 }
579 changed_ids.sort_unstable_by_key(|id| id.0);
580 let mut changed_exports = Vec::new();
581 for file_id in changed_ids {
582 let Some(module) = graph.modules.get(file_id.0 as usize) else {
583 continue;
584 };
585 if module.exports.is_empty() {
586 continue;
587 }
588 let Ok(source) = std::fs::read_to_string(&module.path) else {
589 continue;
590 };
591 changed_exports.extend(module_exports(graph, root, file_id, &source));
592 }
593 Some(changed_exports)
594}
595
596pub(crate) fn module_exports(
599 graph: &ModuleGraph,
600 root: &Path,
601 file_id: FileId,
602 source: &str,
603) -> Vec<ChangedExport> {
604 let Some(module) = graph.modules.get(file_id.0 as usize) else {
605 return Vec::new();
606 };
607 if module.exports.is_empty() {
608 return Vec::new();
609 }
610 let offsets = fallow_types::extract::compute_line_offsets(source);
611 let starts: Vec<u32> = module
612 .exports
613 .iter()
614 .map(|export| export.span.start)
615 .collect();
616 let declarations = crate::search_visibility::export_declarations(&module.path, source, &starts);
617 let file = relative_key_path(&module.path, root);
618 module
619 .exports
620 .iter()
621 .enumerate()
622 .map(|(export_index, export)| {
623 let line =
624 fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start).0;
625 let declaration = declarations.get(&export.span.start);
626 ChangedExport {
627 file_id,
628 export_index,
629 file: file.clone(),
630 export_name: export.name.to_string(),
631 line,
632 declaration_lines: declaration.map_or((line, line), |found| found.lines),
633 is_type_only: export.is_type_only,
634 literal_value: declaration.is_some_and(|found| found.literal_value),
635 is_re_export: declaration.is_some_and(|found| found.is_re_export),
636 }
637 })
638 .collect()
639}
640
641#[must_use]
648pub fn search_gaps_for_changed_paths(
649 graph: &RetainedModuleGraph,
650 root: &Path,
651 changed_files: &FxHashSet<PathBuf>,
652 changed_exports: &[ChangedExport],
653) -> Option<Vec<ExportSearchGapPaths>> {
654 use crate::search_visibility::{SearchTarget, SourceCache};
655 use fallow_graph::graph::ExportNamespace;
656 use fallow_types::trace::SearchVisibility;
657
658 let graph = graph.as_graph();
659 let changed_set: FxHashSet<FileId> =
660 changed_file_ids(graph, changed_files).into_iter().collect();
661 if changed_set.is_empty() {
662 return None;
663 }
664 let mut sources = SourceCache::new(graph);
665 let mut gaps = Vec::new();
666 for changed in changed_exports {
667 let Some(export) = graph
668 .modules
669 .get(changed.file_id.0 as usize)
670 .and_then(|module| module.exports.get(changed.export_index))
671 else {
672 continue;
673 };
674 let mut seen = FxHashSet::default();
675 let candidates: Vec<_> = export
676 .references
677 .iter()
678 .filter(|reference| {
679 !changed_set.contains(&reference.from_file)
680 && graph
681 .modules
682 .get(reference.from_file.0 as usize)
683 .is_some_and(fallow_graph::graph::ModuleNode::is_reachable)
684 && seen.insert(reference.from_file)
685 })
686 .collect();
687 if candidates.is_empty() {
688 continue;
689 }
690 let namespace = if export.is_type_only {
691 ExportNamespace::Type
692 } else {
693 ExportNamespace::Value
694 };
695 let target = SearchTarget::new(
696 graph,
697 &mut sources,
698 changed.file_id,
699 &changed.export_name,
700 namespace,
701 );
702 let mut consumers: Vec<ConsumerSearchGapPaths> = candidates
703 .into_iter()
704 .filter_map(|reference| {
705 let check = target.check(graph, &mut sources, reference)?;
706 if check.visibility == SearchVisibility::Found {
707 return None;
708 }
709 let consumer = graph.modules.get(reference.from_file.0 as usize)?;
710 Some(ConsumerSearchGapPaths {
711 consumer_file: relative_key_path(&consumer.path, root),
712 check,
713 })
714 })
715 .collect();
716 if consumers.is_empty() {
717 continue;
718 }
719 consumers.sort_by(|a, b| a.consumer_file.cmp(&b.consumer_file));
720 gaps.push(ExportSearchGapPaths {
721 file: changed.file.clone(),
722 export_name: changed.export_name.clone(),
723 line: changed.line,
724 declaration_lines: changed.declaration_lines,
725 consumers,
726 });
727 }
728 Some(gaps)
729}
730
731const E2E_RUNNER_PACKAGES: &[&str] = &["@playwright/test", "playwright", "cypress"];
734
735#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
737#[serde(rename_all = "kebab-case")]
738pub enum ExportTestReach {
739 Direct,
741 Transitive,
743 MockedOnly,
746 None,
748 NoneFile,
750}
751
752impl From<GraphExportTestReach> for ExportTestReach {
753 fn from(reach: GraphExportTestReach) -> Self {
754 match reach {
755 GraphExportTestReach::Direct => Self::Direct,
756 GraphExportTestReach::Transitive => Self::Transitive,
757 GraphExportTestReach::MockedOnly => Self::MockedOnly,
758 GraphExportTestReach::None => Self::None,
759 GraphExportTestReach::NoneFile => Self::NoneFile,
760 }
761 }
762}
763
764#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
766pub enum TestMaskingState {
767 Active,
769 NoMocks,
771 Capped,
773}
774
775impl From<GraphTestMaskingState> for TestMaskingState {
776 fn from(state: GraphTestMaskingState) -> Self {
777 match state {
778 GraphTestMaskingState::Active => Self::Active,
779 GraphTestMaskingState::NoMocks => Self::NoMocks,
780 GraphTestMaskingState::Capped => Self::Capped,
781 }
782 }
783}
784
785#[derive(Debug, Clone, PartialEq, Eq)]
787pub struct ExportTestReachPaths {
788 pub file: String,
790 pub export_name: String,
792 pub line: u32,
794 pub declaration_lines: (u32, u32),
796 pub literal_value: bool,
798 pub reach: ExportTestReach,
800 pub tests: Vec<String>,
803 pub mocked_targets: Vec<String>,
805}
806
807#[derive(Debug, Clone, PartialEq, Eq)]
809pub struct TestReachPaths {
810 pub has_tests: bool,
813 pub masking: TestMaskingState,
815 pub has_e2e_runner: bool,
817 pub exports: Vec<ExportTestReachPaths>,
819}
820
821#[must_use]
829pub fn test_reach_for_changed_paths(
830 graph: &RetainedModuleGraph,
831 root: &Path,
832 changed_exports: &[ChangedExport],
833 is_test_path: &dyn Fn(&str) -> bool,
834) -> Option<TestReachPaths> {
835 let graph = graph.as_graph();
836 let mut test_files: FxHashMap<FileId, bool> = FxHashMap::default();
837 let mut is_test_file = |file_id: FileId| -> bool {
838 *test_files.entry(file_id).or_insert_with(|| {
839 graph.test_entry_points.contains(&file_id)
840 || graph
841 .modules
842 .get(file_id.0 as usize)
843 .is_some_and(|module| is_test_path(&relative_key_path(&module.path, root)))
844 })
845 };
846 let has_tests = !graph.test_entry_points.is_empty();
847 let exports: Vec<ExportTestReachPaths> = changed_exports
848 .iter()
849 .filter_map(|changed| classify_export_test_reach(graph, root, changed, &mut is_test_file))
850 .collect();
851 if exports.is_empty() {
852 return None;
853 }
854 let has_e2e_runner = E2E_RUNNER_PACKAGES.iter().any(|name| {
855 graph.package_usage.contains_key(*name) || graph.type_only_package_usage.contains_key(*name)
856 });
857 Some(TestReachPaths {
858 has_tests,
859 masking: graph.test_masking_state().into(),
860 has_e2e_runner,
861 exports,
862 })
863}
864
865pub(crate) fn classify_export_test_reach(
870 graph: &ModuleGraph,
871 root: &Path,
872 changed: &ChangedExport,
873 is_test_file: &mut dyn FnMut(FileId) -> bool,
874) -> Option<ExportTestReachPaths> {
875 if changed.is_type_only || changed.is_re_export {
876 return None;
877 }
878 let module = graph.modules.get(changed.file_id.0 as usize)?;
879 let export = module.exports.get(changed.export_index)?;
880 if !is_reach_subject(&module.path) || is_test_file(changed.file_id) {
881 return None;
882 }
883 let result = if graph.test_entry_points.is_empty() {
884 GraphExportTestReachResult {
885 reach: GraphExportTestReach::NoneFile,
886 tests: Vec::new(),
887 mocked_targets: Vec::new(),
888 }
889 } else {
890 let test_flags: FxHashMap<FileId, bool> = export
891 .references
892 .iter()
893 .map(|reference| (reference.from_file, is_test_file(reference.from_file)))
894 .collect();
895 graph.export_test_reach(changed.file_id, export, &|file_id| {
896 test_flags.get(&file_id).copied().unwrap_or(false)
897 })
898 };
899 let paths_of = |files: &[FileId]| -> Vec<String> {
900 let mut paths: Vec<String> = files
901 .iter()
902 .filter_map(|file_id| graph.modules.get(file_id.0 as usize))
903 .map(|node| relative_key_path(&node.path, root))
904 .collect();
905 paths.sort_unstable();
906 paths
907 };
908 Some(ExportTestReachPaths {
909 file: changed.file.clone(),
910 export_name: changed.export_name.clone(),
911 line: changed.line,
912 declaration_lines: changed.declaration_lines,
913 literal_value: changed.literal_value,
914 reach: result.reach.into(),
915 tests: paths_of(&result.tests),
916 mocked_targets: paths_of(&result.mocked_targets),
917 })
918}
919
920fn is_reach_subject(path: &Path) -> bool {
923 if fallow_graph::graph::is_declaration_file_path(path) {
924 return false;
925 }
926 !path
927 .extension()
928 .and_then(|extension| extension.to_str())
929 .is_some_and(|extension| matches!(extension, "css" | "scss" | "less" | "sass"))
930}
931
932#[must_use]
934pub fn internal_consumers_for_changed_paths(
935 graph: &RetainedModuleGraph,
936 root: &Path,
937 changed_files: &FxHashSet<PathBuf>,
938) -> Option<FxHashMap<String, u64>> {
939 let graph = graph.as_graph();
940 let changed_norm = normalized_changed_paths(changed_files);
941 let id_to_norm: FxHashMap<FileId, String> = graph
942 .modules
943 .iter()
944 .map(|module| (module.file_id, normalize_path(&module.path)))
945 .collect();
946
947 let mut map: FxHashMap<String, u64> = FxHashMap::default();
948 for module in &graph.modules {
949 let abs = normalize_path(&module.path);
950 if !changed_norm.contains(&abs) {
951 continue;
952 }
953 let count = graph
954 .importers_of(module.file_id)
955 .iter()
956 .filter(|imp| {
957 id_to_norm
958 .get(imp)
959 .is_none_or(|p| !changed_norm.contains(p))
960 })
961 .count() as u64;
962 map.insert(relative_key_path(&module.path, root), count);
963 }
964 Some(map)
965}
966
967#[must_use]
974pub fn test_adjacency_for_changed_paths(
975 graph: &RetainedModuleGraph,
976 root: &Path,
977 changed_files: &FxHashSet<PathBuf>,
978 is_test_path: &dyn Fn(&str) -> bool,
979) -> Option<FxHashMap<String, TestAdjacency>> {
980 let graph = graph.as_graph();
981 if !graph
984 .modules
985 .iter()
986 .any(|module| is_test_path(&relative_key_path(&module.path, root)))
987 {
988 return None;
989 }
990 let changed_norm = normalized_changed_paths(changed_files);
991 let mut map: FxHashMap<String, TestAdjacency> = FxHashMap::default();
992 for module in &graph.modules {
993 if !changed_norm.contains(&normalize_path(&module.path)) {
994 continue;
995 }
996 let rel = relative_key_path(&module.path, root);
997 if is_test_path(&rel) {
998 continue;
999 }
1000 let mut adjacency = TestAdjacency::None;
1001 for importer in graph.importers_of(module.file_id) {
1002 let Some(node) = graph.modules.get(importer.0 as usize) else {
1003 continue;
1004 };
1005 if !is_test_path(&relative_key_path(&node.path, root)) {
1006 continue;
1007 }
1008 if changed_norm.contains(&normalize_path(&node.path)) {
1009 adjacency = TestAdjacency::Changed;
1010 break;
1011 }
1012 adjacency = TestAdjacency::Untouched;
1013 }
1014 map.insert(rel, adjacency);
1015 }
1016 if map.is_empty() {
1017 return None;
1018 }
1019 Some(map)
1020}
1021
1022#[derive(Debug, Clone, Default, PartialEq, Eq)]
1024pub struct PackageImporters {
1025 pub importers: Vec<FileId>,
1030 pub out_of_diff: Vec<FileId>,
1032}
1033
1034#[must_use]
1042pub fn package_importers_for_changed_paths(
1043 graph: &RetainedModuleGraph,
1044 changed_files: &FxHashSet<PathBuf>,
1045) -> Option<FxHashMap<String, PackageImporters>> {
1046 let graph = graph.as_graph();
1047 if graph.package_usage.is_empty() && graph.type_only_package_usage.is_empty() {
1048 return None;
1049 }
1050 let changed_norm = normalized_changed_paths(changed_files);
1051 let id_to_norm: FxHashMap<FileId, String> = graph
1052 .modules
1053 .iter()
1054 .map(|module| (module.file_id, normalize_path(&module.path)))
1055 .collect();
1056 let mut usage: FxHashMap<&str, Vec<FileId>> = FxHashMap::default();
1057 for (package, files) in graph
1058 .package_usage
1059 .iter()
1060 .chain(graph.type_only_package_usage.iter())
1061 {
1062 usage
1063 .entry(package.as_str())
1064 .or_default()
1065 .extend(files.iter().copied());
1066 }
1067 let map = usage
1068 .into_iter()
1069 .map(|(package, files)| {
1070 let mut importers: Vec<FileId> = files;
1071 importers.sort_unstable_by_key(|id| id.0);
1072 importers.dedup();
1073 let out_of_diff: Vec<FileId> = importers
1074 .iter()
1075 .copied()
1076 .filter(|id| id_to_norm.get(id).is_none_or(|p| !changed_norm.contains(p)))
1077 .collect();
1078 (
1079 package.to_string(),
1080 PackageImporters {
1081 importers,
1082 out_of_diff,
1083 },
1084 )
1085 })
1086 .collect();
1087 Some(map)
1088}
1089
1090fn changed_file_ids(graph: &ModuleGraph, changed_files: &FxHashSet<PathBuf>) -> Vec<FileId> {
1091 let path_to_id: FxHashMap<String, FileId> = graph
1092 .modules
1093 .iter()
1094 .map(|module| (normalize_path(&module.path), module.file_id))
1095 .collect();
1096
1097 changed_files
1098 .iter()
1099 .filter_map(|path| path_to_id.get(&normalize_path(path)).copied())
1100 .collect()
1101}
1102
1103fn normalized_changed_paths(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<String> {
1104 changed_files
1105 .iter()
1106 .map(|path| normalize_path(path))
1107 .collect()
1108}
1109
1110fn normalize_path(path: &Path) -> String {
1111 path.to_string_lossy().replace('\\', "/")
1112}
1113
1114pub fn relative_key_path(path: &Path, root: &Path) -> String {
1122 let simple_path = dunce::simplified(path);
1123 let simple_root = dunce::simplified(root);
1124 simple_path
1125 .strip_prefix(simple_root)
1126 .unwrap_or(simple_path)
1127 .to_string_lossy()
1128 .replace('\\', "/")
1129}
1130
1131#[cfg(test)]
1132mod tests {
1133 use super::{RetainedModuleGraph, module_value_exports};
1134 use fallow_graph::graph::ModuleGraph;
1135 use fallow_graph::resolve::{
1136 ResolveResult, ResolvedImport, ResolvedModule, ResolvedReplacedModuleTarget,
1137 };
1138 use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
1139 use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
1140 use std::path::PathBuf;
1141
1142 fn import(target: FileId, imported_name: ImportedName) -> ResolvedImport {
1143 import_with_mechanism(target, imported_name, false)
1144 }
1145
1146 fn import_with_mechanism(
1147 target: FileId,
1148 imported_name: ImportedName,
1149 commonjs: bool,
1150 ) -> ResolvedImport {
1151 ResolvedImport {
1152 info: ImportInfo {
1153 source: "./target".to_string(),
1154 imported_name,
1155 local_name: "target".to_string(),
1156 is_type_only: false,
1157 is_type_only_star: false,
1158 from_style: false,
1159 span: oxc_span::Span::new(0, 10),
1160 source_span: oxc_span::Span::default(),
1161 },
1162 target: if commonjs {
1163 ResolveResult::CommonJsInternalModule(target)
1164 } else {
1165 ResolveResult::InternalModule(target)
1166 },
1167 }
1168 }
1169
1170 fn value_export(name: &str, span_start: u32) -> ExportInfo {
1171 ExportInfo {
1172 name: ExportName::Named(name.to_string()),
1173 local_name: Some(name.to_string()),
1174 is_type_only: false,
1175 visibility: VisibilityTag::None,
1176 expected_unused_reason: None,
1177 span: oxc_span::Span::new(span_start, span_start + 10),
1178 members: Vec::new(),
1179 is_side_effect_used: false,
1180 super_class: None,
1181 deprecated: false,
1182 deprecated_reason: None,
1183 }
1184 }
1185
1186 fn mixed_root_graph(unmasked_root_imports_export: bool) -> RetainedModuleGraph {
1187 let files: Vec<_> = (0..3)
1188 .map(|id| DiscoveredFile {
1189 id: FileId(id),
1190 path: PathBuf::from(format!("/project/file{id}.ts")),
1191 size_bytes: 1,
1192 })
1193 .collect();
1194 let modules = vec![
1195 ResolvedModule {
1196 file_id: FileId(0),
1197 path: files[0].path.clone(),
1198 resolved_imports: vec![import(
1199 FileId(2),
1200 ImportedName::Named("target".to_string()),
1201 )],
1202 ..ResolvedModule::default()
1203 },
1204 ResolvedModule {
1205 file_id: FileId(1),
1206 path: files[1].path.clone(),
1207 resolved_imports: vec![import(
1208 FileId(2),
1209 if unmasked_root_imports_export {
1210 ImportedName::Named("target".to_string())
1211 } else {
1212 ImportedName::SideEffect
1213 },
1214 )],
1215 ..ResolvedModule::default()
1216 },
1217 ResolvedModule {
1218 file_id: FileId(2),
1219 path: files[2].path.clone(),
1220 exports: vec![value_export("target", 0)].into(),
1221 ..ResolvedModule::default()
1222 },
1223 ];
1224 let test_entry_points = vec![
1225 EntryPoint {
1226 path: files[0].path.clone(),
1227 source: EntryPointSource::TestFile,
1228 },
1229 EntryPoint {
1230 path: files[1].path.clone(),
1231 source: EntryPointSource::TestFile,
1232 },
1233 ];
1234 let graph = ModuleGraph::build_with_reachability_roots_and_replacements(
1235 &modules,
1236 &[ResolvedReplacedModuleTarget {
1237 source_file: FileId(0),
1238 target_file: FileId(2),
1239 }],
1240 &test_entry_points,
1241 &[],
1242 &test_entry_points,
1243 &files,
1244 );
1245 RetainedModuleGraph::from(graph)
1246 }
1247
1248 #[test]
1249 fn export_coverage_requires_one_root_to_reach_consumer_and_target() {
1250 let graph = mixed_root_graph(false);
1251
1252 let exports = module_value_exports(&graph);
1253
1254 assert_eq!(exports.len(), 1);
1255 assert!(!exports[0].test_referenced);
1256 }
1257
1258 #[test]
1259 fn export_coverage_accepts_an_unmasked_correlated_reference() {
1260 let graph = mixed_root_graph(true);
1261
1262 let exports = module_value_exports(&graph);
1263
1264 assert_eq!(exports.len(), 1);
1265 assert!(exports[0].test_referenced);
1266 }
1267
1268 #[test]
1269 fn commonjs_reference_does_not_credit_a_mocked_esm_export() {
1270 let files: Vec<_> = (0..2)
1271 .map(|id| DiscoveredFile {
1272 id: FileId(id),
1273 path: PathBuf::from(format!("/project/file{id}.ts")),
1274 size_bytes: 1,
1275 })
1276 .collect();
1277 let modules = vec![
1278 ResolvedModule {
1279 file_id: FileId(0),
1280 path: files[0].path.clone(),
1281 resolved_imports: vec![
1282 import_with_mechanism(
1283 FileId(1),
1284 ImportedName::Named("esmOnly".to_string()),
1285 false,
1286 ),
1287 import_with_mechanism(
1288 FileId(1),
1289 ImportedName::Named("required".to_string()),
1290 true,
1291 ),
1292 ],
1293 ..ResolvedModule::default()
1294 },
1295 ResolvedModule {
1296 file_id: FileId(1),
1297 path: files[1].path.clone(),
1298 exports: vec![value_export("esmOnly", 0), value_export("required", 20)].into(),
1299 ..ResolvedModule::default()
1300 },
1301 ];
1302 let test_entry_points = vec![EntryPoint {
1303 path: files[0].path.clone(),
1304 source: EntryPointSource::TestFile,
1305 }];
1306 let graph =
1307 RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1308 &modules,
1309 &[ResolvedReplacedModuleTarget {
1310 source_file: FileId(0),
1311 target_file: FileId(1),
1312 }],
1313 &test_entry_points,
1314 &[],
1315 &test_entry_points,
1316 &files,
1317 ));
1318
1319 let exports = module_value_exports(&graph);
1320 let coverage: rustc_hash::FxHashMap<_, _> = exports
1321 .into_iter()
1322 .map(|export| (export.name, export.test_referenced))
1323 .collect();
1324
1325 assert_eq!(coverage.get("esmOnly"), Some(&false));
1326 assert_eq!(coverage.get("required"), Some(&true));
1327 }
1328
1329 #[test]
1330 fn type_only_test_import_does_not_credit_a_value_export() {
1331 let files: Vec<_> = (0..3)
1332 .map(|id| DiscoveredFile {
1333 id: FileId(id),
1334 path: PathBuf::from(format!("/project/file{id}.ts")),
1335 size_bytes: 1,
1336 })
1337 .collect();
1338 let mut type_only = import(FileId(1), ImportedName::Named("typed".to_string()));
1339 type_only.info.is_type_only = true;
1340 let modules = vec![
1341 ResolvedModule {
1342 file_id: FileId(0),
1343 path: files[0].path.clone(),
1344 resolved_imports: vec![
1345 type_only,
1346 import(FileId(2), ImportedName::Named("called".to_string())),
1347 ],
1348 ..ResolvedModule::default()
1349 },
1350 ResolvedModule {
1351 file_id: FileId(1),
1352 path: files[1].path.clone(),
1353 exports: vec![value_export("typed", 0)].into(),
1354 ..ResolvedModule::default()
1355 },
1356 ResolvedModule {
1357 file_id: FileId(2),
1358 path: files[2].path.clone(),
1359 exports: vec![value_export("called", 0)].into(),
1360 ..ResolvedModule::default()
1361 },
1362 ];
1363 let test_entry_points = vec![EntryPoint {
1364 path: files[0].path.clone(),
1365 source: EntryPointSource::TestFile,
1366 }];
1367 let graph =
1368 RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1369 &modules,
1370 &[],
1371 &test_entry_points,
1372 &[],
1373 &test_entry_points,
1374 &files,
1375 ));
1376
1377 let coverage: rustc_hash::FxHashMap<_, _> = module_value_exports(&graph)
1378 .into_iter()
1379 .map(|export| (export.name, export.test_referenced))
1380 .collect();
1381
1382 assert_eq!(coverage.get("typed"), Some(&false));
1383 assert_eq!(coverage.get("called"), Some(&true));
1384 }
1385}