1use std::path::{Path, PathBuf};
4
5use rustc_hash::FxHashSet;
6
7use fallow_types::{discover::DiscoveredFile, extract::ModuleInfo};
8
9use crate::{ChangeScope, ChangeScopeRequest, PackageBaselineError};
10
11pub type EditorCloneFamily = fallow_types::duplicates::CloneFamily;
13pub type EditorCloneGroup = fallow_types::duplicates::CloneGroup;
15pub type EditorCloneInstance = fallow_types::duplicates::CloneInstance;
17pub type EditorDuplicationReport = fallow_types::duplicates::DuplicationReport;
19pub type EditorDuplicationStats = fallow_types::duplicates::DuplicationStats;
21pub type EditorMirroredDirectory = fallow_types::duplicates::MirroredDirectory;
23pub type EditorRefactoringKind = fallow_types::duplicates::RefactoringKind;
25pub type EditorRefactoringSuggestion = fallow_types::duplicates::RefactoringSuggestion;
27
28#[derive(Debug, Clone)]
30pub struct EditorCloneFingerprintSet {
31 inner: fallow_engine::duplicates::CloneFingerprintSet,
32}
33
34impl EditorCloneFingerprintSet {
35 #[must_use]
37 pub fn from_groups(groups: &[EditorCloneGroup]) -> Self {
38 Self {
39 inner: fallow_engine::duplicates::CloneFingerprintSet::from_groups(groups),
40 }
41 }
42
43 #[must_use]
45 pub fn fingerprint_for_group(&self, group: &EditorCloneGroup) -> String {
46 self.inner.fingerprint_for_group(group)
47 }
48
49 #[must_use]
51 pub fn fingerprint_for_parts(
52 &self,
53 instances: &[EditorCloneInstance],
54 token_count: usize,
55 line_count: usize,
56 ) -> String {
57 self.inner
58 .fingerprint_for_parts(instances, token_count, line_count)
59 }
60
61 #[must_use]
63 pub fn find_group<'a>(
64 &self,
65 groups: &'a [EditorCloneGroup],
66 fingerprint: &str,
67 ) -> Option<&'a EditorCloneGroup> {
68 self.inner.find_group(groups, fingerprint)
69 }
70}
71
72pub mod editor_duplicates {
75 pub use crate::editor::{
76 EditorCloneFamily as CloneFamily, EditorCloneFingerprintSet as CloneFingerprintSet,
77 EditorCloneGroup as CloneGroup, EditorCloneInstance as CloneInstance,
78 EditorDuplicationReport as DuplicationReport, EditorDuplicationStats as DuplicationStats,
79 EditorMirroredDirectory as MirroredDirectory, EditorRefactoringKind as RefactoringKind,
80 EditorRefactoringSuggestion as RefactoringSuggestion,
81 };
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum ChangedFilesError {
87 InvalidRef(String),
89 GitMissing(String),
91 NotARepository,
93 GitFailed(String),
95}
96
97impl ChangedFilesError {
98 #[must_use]
100 pub fn describe(&self) -> String {
101 match self {
102 Self::InvalidRef(err) => format!("invalid git ref: {err}"),
103 Self::GitMissing(err) => format!("failed to run git: {err}"),
104 Self::NotARepository => "not a git repository".to_owned(),
105 Self::GitFailed(stderr) => {
106 let lower = stderr.to_ascii_lowercase();
107 if lower.contains("not a valid object name")
108 || lower.contains("unknown revision")
109 || lower.contains("ambiguous argument")
110 {
111 format!(
112 "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
113 )
114 } else {
115 stderr.clone()
116 }
117 }
118 }
119 }
120}
121
122impl From<fallow_engine::changed_files::ChangedFilesError> for ChangedFilesError {
123 fn from(error: fallow_engine::changed_files::ChangedFilesError) -> Self {
124 match error {
125 fallow_engine::changed_files::ChangedFilesError::InvalidRef(err) => {
126 Self::InvalidRef(err)
127 }
128 fallow_engine::changed_files::ChangedFilesError::GitMissing(err) => {
129 Self::GitMissing(err)
130 }
131 fallow_engine::changed_files::ChangedFilesError::NotARepository => Self::NotARepository,
132 fallow_engine::changed_files::ChangedFilesError::GitFailed(stderr) => {
133 Self::GitFailed(stderr)
134 }
135 }
136 }
137}
138
139pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
146 fallow_engine::changed_files::resolve_git_toplevel(cwd).map_err(ChangedFilesError::from)
147}
148
149pub fn try_get_changed_files_with_toplevel(
156 cwd: &Path,
157 toplevel: &Path,
158 git_ref: &str,
159) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
160 fallow_engine::changed_files::try_get_changed_files_with_toplevel(cwd, toplevel, git_ref)
161 .map_err(ChangedFilesError::from)
162}
163
164pub mod editor_extract {
167 pub use fallow_types::extract::{
168 AngularComponentSelector, AngularInputMember, AngularOutputMember,
169 AngularTemplateMemberAccessFact, AngularThisSpreadFact, CalleeUse, ClassHeritageInfo,
170 ComplexityContribution, ComplexityContributionKind, ComplexityMetric, ComponentEmit,
171 ComponentFunction, ComponentFunctionKind, ComponentProp, CssAnalytics, CssDeclarationBlock,
172 CssRuleMetric, DiFramework, DiKeySite, DiRole, DispatchedEvent,
173 DynamicCustomElementRenderFact, DynamicImportInfo, DynamicImportPattern, ExportInfo,
174 ExportName, FactoryCallMemberAccessFact, FactoryFnMemberAccessFact, FactoryReturnExport,
175 FlagUse, FlagUseKind, FluentChainMemberAccessFact, FluentChainNewMemberAccessFact,
176 ForwardAttr, FunctionComplexity, HookUse, HookUseKind, ImportInfo, ImportedName,
177 InstanceExportBindingFact, LoadReturnKey, LocalTypeDeclaration, MemberAccess, MemberInfo,
178 MemberKind, MisplacedDirectiveSite, ModuleInfo, NamespaceObjectAlias, PUBLIC_ENV_EXACT,
179 PUBLIC_ENV_METADATA_TOKENS, PUBLIC_ENV_PREFIXES, ParseResult, PlaywrightFixtureAliasFact,
180 PlaywrightFixtureDefinitionFact, PlaywrightFixtureTypeFact, PlaywrightFixtureUseFact,
181 PublicSignatureTypeReference, ReExportInfo, RegisteredCustomElement, RenderEdge,
182 RequireCallInfo, SECRET_ENV_TOKENS, SanitizedSinkArg, SanitizerScope, SecurityControlKind,
183 SecurityControlSite, SecurityUrlShape, SemanticFact, SemanticFactView, SinkArgKind,
184 SinkLiteralValue, SinkObjectProperty, SinkShape, SinkSite,
185 SkippedSecurityCalleeExpressionKind, SkippedSecurityCalleeReason,
186 SkippedSecurityCalleeSite, TaintedBinding, VisibilityTag,
187 };
188}
189
190pub mod editor_results {
193 pub use fallow_types::output_dead_code::DuplicateExportAliasFinding;
194 pub use fallow_types::output_dead_code::{
195 AbsentComponentPropFinding, BoundaryCallViolationFinding, BoundaryCoverageViolationFinding,
196 BoundaryViolationFinding, CircularDependencyFinding, DeprecatedExportInUseFinding,
197 DevDependencyInProductionFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
198 DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding, InvalidClientExportFinding,
199 MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
200 MixedClientServerBarrelFinding, PackageCycleFinding, PolicyViolationFinding,
201 PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding,
202 RouteCollisionFinding, TestOnlyDependencyFinding, ThinWrapperFinding,
203 TypeOnlyDependencyFinding, UnlistedDependencyFinding, UnprovidedInjectFinding,
204 UnrenderedComponentFinding, UnresolvedCatalogReferenceFinding, UnresolvedImportFinding,
205 UnusedCatalogEntryFinding, UnusedClassMemberFinding, UnusedComponentEmitFinding,
206 UnusedComponentInputFinding, UnusedComponentOutputFinding, UnusedComponentPropFinding,
207 UnusedDependencyFinding, UnusedDependencyOverrideFinding, UnusedDevDependencyFinding,
208 UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding,
209 UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding,
210 UnusedProtectedClassMemberFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
211 UnusedSvelteEventFinding, UnusedTypeFinding,
212 };
213 pub use fallow_types::output_dead_code::{
214 UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
215 };
216 pub use fallow_types::results::{
217 AbsentComponentProp, ActiveSuppression, AnalysisResults, BoundaryCallViolation,
218 BoundaryCoverageViolation, BoundaryViolation, CircularDependency, CircularDependencyEdge,
219 ComponentPropCallSite, DependencyLocation, DependencyOverrideMisconfigReason,
220 DependencyOverrideSource, DeprecatedConsumerKind, DeprecatedExportConsumer,
221 DeprecatedExportInUse, DevDependencyInProduction, DuplicateExport, DuplicateLocation,
222 DuplicatePropShape, DuplicatePropShapeMember, DynamicSegmentNameConflict,
223 EmptyCatalogGroup, EntryPointSummary, ExportUsage, FeatureFlag, FlagConfidence, FlagKind,
224 ImportSite, InvalidClientExport, MisconfiguredDependencyOverride, MisplacedDirective,
225 MixedClientServerBarrel, PackageCycle, PackageCycleEdge, PolicyRuleKind, PolicyViolation,
226 PolicyViolationSeverity, PrivateTypeLeak, PropDrillHop, PropDrillingChain, ReExportCycle,
227 ReExportCycleKind, ReactComponentIntel, ReactHookSummary, ReactPropDrill, ReactPropIntel,
228 ReferenceLocation, RenderFanInComponent, RenderFanInMetric, RouteCollision,
229 SecurityAttackSurfaceEntry, SecurityCandidate, SecurityCandidateBoundary,
230 SecurityCandidateSink, SecurityDeadCodeContext, SecurityDeadCodeKind,
231 SecurityDefensiveBoundary, SecurityDefensiveControl, SecurityFinding, SecurityFindingKind,
232 SecurityNetworkContext, SecurityReachability, SecurityRuntimeContext, SecurityRuntimeState,
233 SecuritySeverity, SecurityTaintFlow, SecurityUnresolvedCalleeDiagnostic,
234 SecurityZoneCrossing, StaleSuppression, SuppressionOrigin, TaintConfidence, TaintEndpoint,
235 TaintPath, TestOnlyDependency, ThinWrapper, TraceHop, TraceHopRole, TypeOnlyDependency,
236 UnlistedDependency, UnprovidedInject, UnrenderedComponent, UnresolvedCatalogReference,
237 UnresolvedImport, UnusedCatalogEntry, UnusedComponentEmit, UnusedComponentInput,
238 UnusedComponentOutput, UnusedComponentProp, UnusedDependency, UnusedDependencyOverride,
239 UnusedExport, UnusedFile, UnusedLoadDataKey, UnusedMember, UnusedServerAction,
240 UnusedSvelteEvent,
241 };
242 pub use fallow_types::results::{
243 ConstantParameter, ConstantParameterCallSite, ConstantParameterFinding,
244 ConstantParameterReason, ConstantParameterValue, ConstantParameterValueKind,
245 };
246 pub use fallow_types::results::{DuplicateExportAlias, DuplicateExportAliasLocation};
247 pub use fallow_types::results::{
248 EffectCatchSite, EffectLayerKind, UnproducedCatchTag, UnusedEffectLayer, UnusedTaggedError,
249 };
250}
251
252pub mod editor_security {
254 #[must_use]
256 pub fn security_catalogue_title(kind: &str) -> Option<&'static str> {
257 fallow_engine::dead_code::security_catalogue_title(kind)
258 }
259}
260
261pub mod editor_suppress {
263 pub use fallow_types::suppress::{IssueKind, is_suppressed};
264}
265
266pub type EditorAnalysisResults = fallow_types::results::AnalysisResults;
268
269#[derive(Debug)]
274pub struct EditorDeadCodeAnalysisOutput {
275 pub results: EditorAnalysisResults,
277 pub modules: Option<Vec<ModuleInfo>>,
280 pub files: Option<Vec<DiscoveredFile>>,
282}
283
284impl EditorDeadCodeAnalysisOutput {
285 fn from_engine(output: fallow_engine::dead_code::DeadCodeAnalysisOutput) -> Self {
286 Self {
287 results: output.results,
288 modules: output.modules,
289 files: output.files,
290 }
291 }
292}
293
294#[derive(Debug, Clone, PartialEq, Eq)]
300pub struct EditorInlineComplexityFinding {
301 pub path: PathBuf,
303 pub name: String,
305 pub line: u32,
307 pub col: u32,
309 pub cyclomatic: u16,
311 pub cognitive: u16,
313 pub exceeded: EditorInlineComplexityExceeded,
315}
316
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319pub enum EditorInlineComplexityExceeded {
320 Cyclomatic,
322 Cognitive,
324 CyclomaticAndCognitive,
326}
327
328#[must_use]
334pub fn collect_inline_complexity(
335 config: &fallow_config::ResolvedConfig,
336 output: &EditorDeadCodeAnalysisOutput,
337) -> Vec<EditorInlineComplexityFinding> {
338 let (Some(modules), Some(files)) = (output.modules.as_ref(), output.files.as_ref()) else {
339 return Vec::new();
340 };
341 fallow_engine::health::inline_complexity(config, modules, files)
342 .into_iter()
343 .map(|finding| EditorInlineComplexityFinding {
344 exceeded: match (finding.exceeds_cyclomatic, finding.exceeds_cognitive) {
345 (true, true) => EditorInlineComplexityExceeded::CyclomaticAndCognitive,
346 (true, false) => EditorInlineComplexityExceeded::Cyclomatic,
347 (false, _) => EditorInlineComplexityExceeded::Cognitive,
348 },
349 path: finding.path,
350 name: finding.name,
351 line: finding.line,
352 col: finding.col,
353 cyclomatic: finding.cyclomatic,
354 cognitive: finding.cognitive,
355 })
356 .collect()
357}
358
359#[expect(
361 clippy::implicit_hasher,
362 reason = "editor analysis changed-file sets use the workspace FxHashSet convention"
363)]
364pub fn filter_inline_complexity_by_changed_files(
365 findings: &mut Vec<EditorInlineComplexityFinding>,
366 changed_files: &FxHashSet<PathBuf>,
367) {
368 findings.retain(|finding| changed_files.contains(&finding.path));
369}
370
371pub fn filter_inline_complexity_by_change_scope(
373 findings: &mut Vec<EditorInlineComplexityFinding>,
374 scope: &ChangeScope,
375) {
376 findings.retain(|finding| scope.contains(&finding.path));
377}
378
379pub type EditorSessionParseCounts = fallow_engine::session::SessionParseCounts;
382
383#[derive(Debug)]
385pub struct EditorAnalysisSession {
386 inner: fallow_engine::session::AnalysisSession,
387 runs_duplication: bool,
389}
390
391impl EditorAnalysisSession {
392 pub fn open(run: &crate::run::ResolvedRun) -> Result<Self, crate::ProgrammaticError> {
400 use crate::run::AnalysisSlot;
401 use fallow_config::PlannedAnalysis;
402 let AnalysisSlot::Runs(dead_code) = run.analysis(PlannedAnalysis::DeadCode) else {
403 return Err(crate::ProgrammaticError::new(
404 "an editor session needs a run that plans the dead-code analysis",
405 2,
406 ));
407 };
408 Ok(Self {
409 inner: dead_code.open_session(),
410 runs_duplication: matches!(
411 run.analysis(PlannedAnalysis::Duplication),
412 AnalysisSlot::Runs(_)
413 ),
414 })
415 }
416
417 pub fn load(root: &Path, config_path: Option<&Path>) -> fallow_engine::EngineResult<Self> {
423 fallow_engine::session::AnalysisSession::load(root, config_path).map(Self::from_engine)
424 }
425
426 pub fn load_with_config(
432 root: &Path,
433 config_path: Option<&Path>,
434 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
435 ) -> fallow_engine::EngineResult<Self> {
436 fallow_engine::session::AnalysisSession::load_with_config(root, config_path, configure)
437 .map(Self::from_engine)
438 }
439
440 pub fn load_with_config_options(
447 root: &Path,
448 config_path: Option<&Path>,
449 load_options: fallow_config::ConfigLoadOptions,
450 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
451 ) -> fallow_engine::EngineResult<Self> {
452 fallow_engine::session::AnalysisSession::load_with_config_options(
453 root,
454 config_path,
455 load_options,
456 configure,
457 )
458 .map(Self::from_engine)
459 }
460
461 pub fn load_with_production(
471 root: &Path,
472 config_path: Option<&Path>,
473 load_options: fallow_config::ConfigLoadOptions,
474 production_override: Option<bool>,
475 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
476 ) -> fallow_engine::EngineResult<Self> {
477 let mut project = fallow_engine::project_config::config_for_project_with_production(
478 root,
479 config_path,
480 load_options,
481 fallow_engine::project_config::ProductionFlags {
482 global: production_override,
483 ..fallow_engine::project_config::ProductionFlags::default()
484 },
485 )?;
486 configure(&mut project.config);
487 Ok(Self::from_engine(
488 fallow_engine::session::AnalysisSession::from_config(
489 project.without_workspace_metadata(),
490 ),
491 ))
492 }
493
494 #[must_use]
496 pub fn load_default(root: &Path) -> Self {
497 Self::from_engine(fallow_engine::session::AnalysisSession::load_default(root))
498 }
499
500 #[must_use]
503 pub fn load_default_with_config(
504 root: &Path,
505 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
506 ) -> Self {
507 Self::from_engine(
508 fallow_engine::session::AnalysisSession::load_default_with_config(root, configure),
509 )
510 }
511
512 #[must_use]
521 pub fn with_cancellation(
522 self,
523 cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
524 ) -> Self {
525 Self::from_engine(self.inner.with_cancellation(cancellation))
526 }
527
528 pub fn set_cancellation(
530 &mut self,
531 cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
532 ) {
533 self.inner.set_cancellation(cancellation);
534 }
535
536 pub fn refresh_discovery(&mut self) -> bool {
541 self.inner.refresh_discovery()
542 }
543
544 #[must_use]
548 pub fn config_inputs(&self) -> &fallow_config::ConfigInputs {
549 self.inner.config_inputs()
550 }
551
552 #[must_use]
555 pub fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
556 self.inner.config_inputs_before_resolve()
557 }
558
559 #[must_use]
562 pub fn retained_bytes_estimate(&self) -> u64 {
563 self.inner.retained_bytes_estimate()
564 }
565
566 pub fn flush_parse_cache(&self) {
569 self.inner.flush_parse_cache();
570 }
571
572 pub fn prewarm(&self, retain_complexity_artifacts: bool) -> fallow_engine::EngineResult<()> {
579 self.inner
580 .prewarm_parsed_modules(retain_complexity_artifacts)
581 }
582
583 #[must_use]
585 pub fn parse_counts(&self) -> EditorSessionParseCounts {
586 self.inner.parse_counts()
587 }
588
589 #[must_use]
591 pub fn config(&self) -> &fallow_config::ResolvedConfig {
592 self.inner.config()
593 }
594
595 pub fn change_scope(
603 &self,
604 request: ChangeScopeRequest<'_>,
605 ) -> Result<ChangeScope, PackageBaselineError> {
606 ChangeScope::resolve(request, self.inner.config(), self.inner.workspaces())
607 }
608
609 #[must_use]
614 pub fn unmatched_config_patterns(&self) -> Vec<fallow_config::WorkspaceDiagnostic> {
615 fallow_engine::dead_code::config_pattern_diagnostics(self.inner.config(), true)
616 }
617
618 #[must_use]
620 pub fn config_path(&self) -> Option<&Path> {
621 self.inner.config_path()
622 }
623
624 pub fn refine_type_aware_dead_code(
632 &self,
633 options: &crate::TypeAwareOptions,
634 filters: &crate::DeadCodeFilters,
635 output: &mut EditorDeadCodeAnalysisOutput,
636 ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
637 let meta = crate::type_aware::refine_programmatic_dead_code(
638 options,
639 filters,
640 &self.inner,
641 &mut output.results,
642 )?;
643 fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
647 Ok(meta)
648 }
649
650 pub fn refine_type_aware_dead_code_in_session(
652 &self,
653 semantic_session: &mut crate::TypeAwareSession,
654 changes: Option<&crate::TypeAwareFileChanges>,
655 options: &crate::TypeAwareOptions,
656 filters: &crate::DeadCodeFilters,
657 output: &mut EditorDeadCodeAnalysisOutput,
658 ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
659 let meta = crate::type_aware::refine_programmatic_dead_code_in_session(
660 semantic_session,
661 changes,
662 options,
663 filters,
664 &self.inner,
665 &mut output.results,
666 )?;
667 fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
668 Ok(meta)
669 }
670
671 pub fn analyze_project_with(
677 &self,
678 duplicates_config: &fallow_config::DuplicatesConfig,
679 retain_complexity_artifacts: bool,
680 ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
681 self.inner
682 .analyze_project_with(duplicates_config, retain_complexity_artifacts)
683 .map(EditorProjectAnalysisOutput::from_engine)
684 .map(|output| self.with_resolved_rule_severities(output))
685 }
686
687 pub fn analyze_project_with_changed_files(
698 &self,
699 duplicates_config: &fallow_config::DuplicatesConfig,
700 retain_complexity_artifacts: bool,
701 changed_files: Option<&FxHashSet<PathBuf>>,
702 ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
703 let artifacts = if self.runs_duplication {
704 self.inner.analyze_project_with_artifacts(
705 duplicates_config,
706 fallow_engine::project_analysis::ProjectAnalysisArtifactOptions {
707 retain_complexity_artifacts,
708 changed_files: changed_files.cloned(),
709 ..fallow_engine::project_analysis::ProjectAnalysisArtifactOptions::default()
710 },
711 )?
712 } else {
713 fallow_engine::project_analysis::ProjectAnalysisArtifacts {
714 dead_code: self
715 .inner
716 .analyze_dead_code_with_artifacts(retain_complexity_artifacts, false)?,
717 duplication: fallow_types::duplicates::DuplicationReport::default(),
718 changed_files: changed_files.cloned(),
719 source_fingerprints: None,
720 }
721 };
722 Ok(
723 self.with_resolved_rule_severities(EditorProjectAnalysisOutput::from_engine(
724 artifacts.into_output(),
725 )),
726 )
727 }
728
729 pub fn apply_change_scope(
737 &self,
738 output: &mut EditorProjectAnalysisOutput,
739 scope: &ChangeScope,
740 ) {
741 fallow_engine::dead_code::apply_scope(
742 &mut output.dead_code.results,
743 &fallow_engine::dead_code::DeadCodeScope {
744 workspace_roots: None,
745 changes: Some(scope),
746 diff: None,
747 files: None,
748 },
749 self.inner.config(),
750 );
751 fallow_engine::duplicates::apply_scope(
752 &mut output.duplication,
753 &fallow_engine::duplicates::DuplicationScope {
754 changes: Some(scope),
755 diff: None,
756 workspace_roots: None,
757 },
758 &self.inner.config().root,
759 );
760 }
761
762 fn with_resolved_rule_severities(
769 &self,
770 mut output: EditorProjectAnalysisOutput,
771 ) -> EditorProjectAnalysisOutput {
772 fallow_engine::dead_code::apply_rule_severities(
773 &mut output.dead_code.results,
774 self.inner.config(),
775 );
776 output
777 }
778
779 fn from_engine(inner: fallow_engine::session::AnalysisSession) -> Self {
783 Self {
784 runs_duplication: inner.config().duplicates.runs_by_default(),
785 inner,
786 }
787 }
788}
789
790#[derive(Debug)]
792pub struct EditorProjectAnalysisOutput {
793 pub dead_code: EditorDeadCodeAnalysisOutput,
795 pub duplication: EditorDuplicationReport,
797}
798
799impl EditorProjectAnalysisOutput {
800 fn from_engine(output: fallow_engine::project_analysis::ProjectAnalysisOutput) -> Self {
801 Self {
802 dead_code: EditorDeadCodeAnalysisOutput::from_engine(output.dead_code),
803 duplication: output.duplication,
804 }
805 }
806}
807
808#[derive(Debug, Default)]
810pub struct EditorAnalysisOutput {
811 pub results: EditorAnalysisResults,
813 pub duplication: EditorDuplicationReport,
815}
816
817impl EditorAnalysisOutput {
818 #[must_use]
820 pub const fn new(results: EditorAnalysisResults, duplication: EditorDuplicationReport) -> Self {
821 Self {
822 results,
823 duplication,
824 }
825 }
826
827 pub fn merge_project_output(&mut self, output: EditorProjectAnalysisOutput) {
829 self.merge_results(output.dead_code.results);
830 self.merge_duplication(output.duplication);
831 }
832
833 pub fn merge_results(&mut self, source: EditorAnalysisResults) {
835 self.results.merge_into(source);
836 }
837
838 pub fn merge_duplication(&mut self, source: EditorDuplicationReport) {
841 self.duplication.clone_groups.extend(source.clone_groups);
842 self.duplication
843 .clone_families
844 .extend(source.clone_families);
845 self.duplication
846 .mirrored_directories
847 .extend(source.mirrored_directories);
848 self.duplication.stats.clone_groups += source.stats.clone_groups;
849 self.duplication.stats.clone_families += source.stats.clone_families;
850 self.duplication.stats.clone_instances += source.stats.clone_instances;
851 self.duplication.stats.total_files += source.stats.total_files;
852 self.duplication.stats.files_with_clones += source.stats.files_with_clones;
853 self.duplication.stats.total_lines += source.stats.total_lines;
854 self.duplication.stats.duplicated_lines += source.stats.duplicated_lines;
855 self.duplication.stats.total_tokens += source.stats.total_tokens;
856 self.duplication.stats.duplicated_tokens += source.stats.duplicated_tokens;
857 self.duplication.stats.clone_groups_below_min_occurrences +=
858 source.stats.clone_groups_below_min_occurrences;
859 self.duplication.stats.clone_groups_ignored += source.stats.clone_groups_ignored;
860 self.duplication.stats.near_candidates_skipped += source.stats.near_candidates_skipped;
861 self.duplication.stats.duplication_percentage = if self.duplication.stats.total_lines > 0 {
862 (self.duplication.stats.duplicated_lines as f64
863 / self.duplication.stats.total_lines as f64)
864 * 100.0
865 } else {
866 0.0
867 };
868 }
869
870 pub fn filter_by_changed_files(&mut self, changed_files: &FxHashSet<PathBuf>, root: &Path) {
876 fallow_engine::changed_files::filter_results_by_changed_files(
877 &mut self.results,
878 changed_files,
879 );
880 fallow_engine::changed_files::filter_duplication_by_changed_files(
881 &mut self.duplication,
882 changed_files,
883 root,
884 );
885 }
886}
887
888#[cfg(test)]
889#[path = "editor_tests.rs"]
890pub(crate) mod tests;