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, NamespaceEscapeFinding, PackageCycleFinding,
201 PolicyViolationFinding, PrivateTypeLeakFinding, PropDrillingChainFinding,
202 ReExportCycleFinding, 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, NamespaceEscape, NamespaceEscapeReason, PackageCycle,
226 PackageCycleEdge, PolicyRuleKind, PolicyViolation, PolicyViolationSeverity,
227 PrivateTypeLeak, PropDrillHop, PropDrillingChain, ReExportCycle, ReExportCycleKind,
228 ReactComponentIntel, ReactHookSummary, ReactPropDrill, ReactPropIntel, ReferenceLocation,
229 RenderFanInComponent, RenderFanInMetric, RouteCollision, SecurityAttackSurfaceEntry,
230 SecurityCandidate, SecurityCandidateBoundary, SecurityCandidateSink,
231 SecurityDeadCodeContext, SecurityDeadCodeKind, SecurityDefensiveBoundary,
232 SecurityDefensiveControl, SecurityFinding, SecurityFindingKind, SecurityNetworkContext,
233 SecurityReachability, SecurityRuntimeContext, SecurityRuntimeState, SecuritySeverity,
234 SecurityTaintFlow, SecurityUnresolvedCalleeDiagnostic, SecurityZoneCrossing,
235 StaleSuppression, SuppressionOrigin, TaintConfidence, TaintEndpoint, TaintPath,
236 TestOnlyDependency, ThinWrapper, TraceHop, TraceHopRole, TypeOnlyDependency,
237 UnlistedDependency, UnprovidedInject, UnrenderedComponent, UnresolvedCatalogReference,
238 UnresolvedImport, UnusedCatalogEntry, UnusedComponentEmit, UnusedComponentInput,
239 UnusedComponentOutput, UnusedComponentProp, UnusedDependency, UnusedDependencyOverride,
240 UnusedExport, UnusedFile, UnusedLoadDataKey, UnusedMember, UnusedServerAction,
241 UnusedSvelteEvent,
242 };
243 pub use fallow_types::results::{
244 ConstantParameter, ConstantParameterCallSite, ConstantParameterFinding,
245 ConstantParameterReason, ConstantParameterValue, ConstantParameterValueKind,
246 };
247 pub use fallow_types::results::{DuplicateExportAlias, DuplicateExportAliasLocation};
248 pub use fallow_types::results::{
249 EffectCatchSite, EffectLayerKind, UnproducedCatchTag, UnusedEffectLayer, UnusedTaggedError,
250 };
251}
252
253pub mod editor_security {
255 #[must_use]
257 pub fn security_catalogue_title(kind: &str) -> Option<&'static str> {
258 fallow_engine::dead_code::security_catalogue_title(kind)
259 }
260}
261
262pub mod editor_suppress {
264 pub use fallow_types::suppress::{IssueKind, is_suppressed};
265}
266
267pub type EditorAnalysisResults = fallow_types::results::AnalysisResults;
269
270#[derive(Debug)]
275pub struct EditorDeadCodeAnalysisOutput {
276 pub results: EditorAnalysisResults,
278 pub modules: Option<Vec<ModuleInfo>>,
281 pub files: Option<Vec<DiscoveredFile>>,
283}
284
285impl EditorDeadCodeAnalysisOutput {
286 fn from_engine(output: fallow_engine::dead_code::DeadCodeAnalysisOutput) -> Self {
287 Self {
288 results: output.results,
289 modules: output.modules,
290 files: output.files,
291 }
292 }
293}
294
295#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct EditorInlineComplexityFinding {
302 pub path: PathBuf,
304 pub name: String,
306 pub line: u32,
308 pub col: u32,
310 pub cyclomatic: u16,
312 pub cognitive: u16,
314 pub exceeded: EditorInlineComplexityExceeded,
316}
317
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320pub enum EditorInlineComplexityExceeded {
321 Cyclomatic,
323 Cognitive,
325 CyclomaticAndCognitive,
327}
328
329#[must_use]
335pub fn collect_inline_complexity(
336 config: &fallow_config::ResolvedConfig,
337 output: &EditorDeadCodeAnalysisOutput,
338) -> Vec<EditorInlineComplexityFinding> {
339 let (Some(modules), Some(files)) = (output.modules.as_ref(), output.files.as_ref()) else {
340 return Vec::new();
341 };
342 fallow_engine::health::inline_complexity(config, modules, files)
343 .into_iter()
344 .map(|finding| EditorInlineComplexityFinding {
345 exceeded: match (finding.exceeds_cyclomatic, finding.exceeds_cognitive) {
346 (true, true) => EditorInlineComplexityExceeded::CyclomaticAndCognitive,
347 (true, false) => EditorInlineComplexityExceeded::Cyclomatic,
348 (false, _) => EditorInlineComplexityExceeded::Cognitive,
349 },
350 path: finding.path,
351 name: finding.name,
352 line: finding.line,
353 col: finding.col,
354 cyclomatic: finding.cyclomatic,
355 cognitive: finding.cognitive,
356 })
357 .collect()
358}
359
360#[expect(
362 clippy::implicit_hasher,
363 reason = "editor analysis changed-file sets use the workspace FxHashSet convention"
364)]
365pub fn filter_inline_complexity_by_changed_files(
366 findings: &mut Vec<EditorInlineComplexityFinding>,
367 changed_files: &FxHashSet<PathBuf>,
368) {
369 findings.retain(|finding| changed_files.contains(&finding.path));
370}
371
372pub fn filter_inline_complexity_by_change_scope(
374 findings: &mut Vec<EditorInlineComplexityFinding>,
375 scope: &ChangeScope,
376) {
377 findings.retain(|finding| scope.contains(&finding.path));
378}
379
380pub type EditorSessionParseCounts = fallow_engine::session::SessionParseCounts;
383
384#[derive(Debug)]
386pub struct EditorAnalysisSession {
387 inner: fallow_engine::session::AnalysisSession,
388 runs_duplication: bool,
390}
391
392impl EditorAnalysisSession {
393 pub fn open(run: &crate::run::ResolvedRun) -> Result<Self, crate::ProgrammaticError> {
401 use crate::run::AnalysisSlot;
402 use fallow_config::PlannedAnalysis;
403 let AnalysisSlot::Runs(dead_code) = run.analysis(PlannedAnalysis::DeadCode) else {
404 return Err(crate::ProgrammaticError::new(
405 "an editor session needs a run that plans the dead-code analysis",
406 2,
407 ));
408 };
409 Ok(Self {
410 inner: dead_code.open_session(),
411 runs_duplication: matches!(
412 run.analysis(PlannedAnalysis::Duplication),
413 AnalysisSlot::Runs(_)
414 ),
415 })
416 }
417
418 #[cfg(any(test, feature = "testing"))]
424 pub fn load(root: &Path, config_path: Option<&Path>) -> fallow_engine::EngineResult<Self> {
425 fallow_engine::session::AnalysisSession::load(root, config_path).map(Self::from_engine)
426 }
427
428 #[cfg(any(test, feature = "testing"))]
434 pub fn load_with_config(
435 root: &Path,
436 config_path: Option<&Path>,
437 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
438 ) -> fallow_engine::EngineResult<Self> {
439 fallow_engine::session::AnalysisSession::load_with_config(root, config_path, configure)
440 .map(Self::from_engine)
441 }
442
443 #[cfg(any(test, feature = "testing"))]
450 pub fn load_with_config_options(
451 root: &Path,
452 config_path: Option<&Path>,
453 load_options: fallow_config::ConfigLoadOptions,
454 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
455 ) -> fallow_engine::EngineResult<Self> {
456 fallow_engine::session::AnalysisSession::load_with_config_options(
457 root,
458 config_path,
459 load_options,
460 configure,
461 )
462 .map(Self::from_engine)
463 }
464
465 #[cfg(any(test, feature = "testing"))]
475 pub fn load_with_production(
476 root: &Path,
477 config_path: Option<&Path>,
478 load_options: fallow_config::ConfigLoadOptions,
479 production_override: Option<bool>,
480 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
481 ) -> fallow_engine::EngineResult<Self> {
482 let mut project = fallow_engine::project_config::config_for_project_with_production(
483 root,
484 config_path,
485 load_options,
486 fallow_engine::project_config::ProductionFlags {
487 global: production_override,
488 ..fallow_engine::project_config::ProductionFlags::default()
489 },
490 )?;
491 configure(&mut project.config);
492 Ok(Self::from_engine(
493 fallow_engine::session::AnalysisSession::from_config(
494 project.without_workspace_metadata(),
495 ),
496 ))
497 }
498
499 #[cfg(any(test, feature = "testing"))]
501 #[must_use]
502 pub fn load_default(root: &Path) -> Self {
503 Self::from_engine(fallow_engine::session::AnalysisSession::load_default(root))
504 }
505
506 #[cfg(any(test, feature = "testing"))]
509 #[must_use]
510 pub fn load_default_with_config(
511 root: &Path,
512 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
513 ) -> Self {
514 Self::from_engine(
515 fallow_engine::session::AnalysisSession::load_default_with_config(root, configure),
516 )
517 }
518
519 #[must_use]
528 pub fn with_cancellation(
529 self,
530 cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
531 ) -> Self {
532 Self {
533 inner: self.inner.with_cancellation(cancellation),
534 runs_duplication: self.runs_duplication,
535 }
536 }
537
538 pub fn set_cancellation(
540 &mut self,
541 cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
542 ) {
543 self.inner.set_cancellation(cancellation);
544 }
545
546 pub fn refresh_discovery(&mut self) -> bool {
551 self.inner.refresh_discovery()
552 }
553
554 #[must_use]
558 pub fn config_inputs(&self) -> &fallow_config::ConfigInputs {
559 self.inner.config_inputs()
560 }
561
562 #[must_use]
565 pub fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
566 self.inner.config_inputs_before_resolve()
567 }
568
569 #[must_use]
572 pub fn retained_bytes_estimate(&self) -> u64 {
573 self.inner.retained_bytes_estimate()
574 }
575
576 pub fn flush_parse_cache(&self) {
579 self.inner.flush_parse_cache();
580 }
581
582 pub fn prewarm(&self, retain_complexity_artifacts: bool) -> fallow_engine::EngineResult<()> {
589 self.inner
590 .prewarm_parsed_modules(retain_complexity_artifacts)
591 }
592
593 #[must_use]
595 pub fn parse_counts(&self) -> EditorSessionParseCounts {
596 self.inner.parse_counts()
597 }
598
599 #[must_use]
601 pub fn config(&self) -> &fallow_config::ResolvedConfig {
602 self.inner.config()
603 }
604
605 pub fn change_scope(
613 &self,
614 request: ChangeScopeRequest<'_>,
615 ) -> Result<ChangeScope, PackageBaselineError> {
616 ChangeScope::resolve(request, self.inner.config(), self.inner.workspaces())
617 }
618
619 #[must_use]
624 pub fn unmatched_config_patterns(&self) -> Vec<fallow_config::WorkspaceDiagnostic> {
625 fallow_engine::dead_code::config_pattern_diagnostics(self.inner.config(), true)
626 }
627
628 #[must_use]
630 pub fn config_path(&self) -> Option<&Path> {
631 self.inner.config_path()
632 }
633
634 pub fn refine_type_aware_dead_code(
642 &self,
643 options: &crate::TypeAwareOptions,
644 filters: &crate::DeadCodeFilters,
645 output: &mut EditorDeadCodeAnalysisOutput,
646 ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
647 let meta = crate::type_aware::refine_programmatic_dead_code(
648 options,
649 filters,
650 &self.inner,
651 &mut output.results,
652 )?;
653 fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
657 Ok(meta)
658 }
659
660 pub fn refine_type_aware_dead_code_in_session(
662 &self,
663 semantic_session: &mut crate::TypeAwareSession,
664 changes: Option<&crate::TypeAwareFileChanges>,
665 options: &crate::TypeAwareOptions,
666 filters: &crate::DeadCodeFilters,
667 output: &mut EditorDeadCodeAnalysisOutput,
668 ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
669 let meta = crate::type_aware::refine_programmatic_dead_code_in_session(
670 semantic_session,
671 changes,
672 options,
673 filters,
674 &self.inner,
675 &mut output.results,
676 )?;
677 fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
678 Ok(meta)
679 }
680
681 pub fn analyze_project_with(
687 &self,
688 duplicates_config: &fallow_config::DuplicatesConfig,
689 retain_complexity_artifacts: bool,
690 ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
691 self.inner
692 .analyze_project_with(duplicates_config, retain_complexity_artifacts)
693 .map(EditorProjectAnalysisOutput::from_engine)
694 .map(|output| self.with_resolved_rule_severities(output))
695 }
696
697 pub fn analyze_project_with_changed_files(
708 &self,
709 duplicates_config: &fallow_config::DuplicatesConfig,
710 retain_complexity_artifacts: bool,
711 changed_files: Option<&FxHashSet<PathBuf>>,
712 ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
713 let artifacts = if self.runs_duplication {
714 self.inner.analyze_project_with_artifacts(
715 duplicates_config,
716 fallow_engine::project_analysis::ProjectAnalysisArtifactOptions {
717 retain_complexity_artifacts,
718 changed_files: changed_files.cloned(),
719 ..fallow_engine::project_analysis::ProjectAnalysisArtifactOptions::default()
720 },
721 )?
722 } else {
723 fallow_engine::project_analysis::ProjectAnalysisArtifacts {
724 dead_code: self
725 .inner
726 .analyze_dead_code_with_artifacts(retain_complexity_artifacts, false)?,
727 duplication: fallow_types::duplicates::DuplicationReport::default(),
728 ignored_clone_groups: Vec::new(),
729 changed_files: changed_files.cloned(),
730 source_fingerprints: None,
731 }
732 };
733 Ok(
734 self.with_resolved_rule_severities(EditorProjectAnalysisOutput::from_engine(
735 artifacts.into_output(),
736 )),
737 )
738 }
739
740 pub fn apply_change_scope(
748 &self,
749 output: &mut EditorProjectAnalysisOutput,
750 scope: &ChangeScope,
751 ) {
752 fallow_engine::dead_code::apply_scope(
753 &mut output.dead_code.results,
754 &fallow_engine::dead_code::DeadCodeScope {
755 workspace_roots: None,
756 changes: Some(scope),
757 diff: None,
758 files: None,
759 },
760 self.inner.config(),
761 );
762 fallow_engine::duplicates::apply_scope(
763 &mut output.duplication,
764 &fallow_engine::duplicates::DuplicationScope {
765 changes: Some(scope),
766 diff: None,
767 workspace_roots: None,
768 },
769 &self.inner.config().root,
770 );
771 }
772
773 fn with_resolved_rule_severities(
780 &self,
781 mut output: EditorProjectAnalysisOutput,
782 ) -> EditorProjectAnalysisOutput {
783 fallow_engine::dead_code::apply_rule_severities(
784 &mut output.dead_code.results,
785 self.inner.config(),
786 );
787 output
788 }
789
790 #[cfg(any(test, feature = "testing"))]
794 fn from_engine(inner: fallow_engine::session::AnalysisSession) -> Self {
795 Self {
796 runs_duplication: inner.config().duplicates.runs_by_default(),
797 inner,
798 }
799 }
800}
801
802#[derive(Debug)]
804pub struct EditorProjectAnalysisOutput {
805 pub dead_code: EditorDeadCodeAnalysisOutput,
807 pub duplication: EditorDuplicationReport,
809}
810
811impl EditorProjectAnalysisOutput {
812 fn from_engine(output: fallow_engine::project_analysis::ProjectAnalysisOutput) -> Self {
813 Self {
814 dead_code: EditorDeadCodeAnalysisOutput::from_engine(output.dead_code),
815 duplication: output.duplication,
816 }
817 }
818}
819
820#[derive(Debug, Default)]
822pub struct EditorAnalysisOutput {
823 pub results: EditorAnalysisResults,
825 pub duplication: EditorDuplicationReport,
827}
828
829impl EditorAnalysisOutput {
830 #[must_use]
832 pub const fn new(results: EditorAnalysisResults, duplication: EditorDuplicationReport) -> Self {
833 Self {
834 results,
835 duplication,
836 }
837 }
838
839 pub fn merge_project_output(&mut self, output: EditorProjectAnalysisOutput) {
841 self.merge_results(output.dead_code.results);
842 self.merge_duplication(output.duplication);
843 }
844
845 pub fn merge_results(&mut self, source: EditorAnalysisResults) {
847 self.results.merge_into(source);
848 }
849
850 pub fn merge_duplication(&mut self, source: EditorDuplicationReport) {
853 self.duplication.clone_groups.extend(source.clone_groups);
854 self.duplication
855 .clone_families
856 .extend(source.clone_families);
857 self.duplication
858 .mirrored_directories
859 .extend(source.mirrored_directories);
860 self.duplication.stats.clone_groups += source.stats.clone_groups;
861 self.duplication.stats.clone_families += source.stats.clone_families;
862 self.duplication.stats.clone_instances += source.stats.clone_instances;
863 self.duplication.stats.total_files += source.stats.total_files;
864 self.duplication.stats.files_with_clones += source.stats.files_with_clones;
865 self.duplication.stats.total_lines += source.stats.total_lines;
866 self.duplication.stats.duplicated_lines += source.stats.duplicated_lines;
867 self.duplication.stats.total_tokens += source.stats.total_tokens;
868 self.duplication.stats.duplicated_tokens += source.stats.duplicated_tokens;
869 self.duplication.stats.clone_groups_below_min_occurrences +=
870 source.stats.clone_groups_below_min_occurrences;
871 self.duplication.stats.clone_groups_ignored += source.stats.clone_groups_ignored;
872 self.duplication.stats.near_candidates_skipped += source.stats.near_candidates_skipped;
873 self.duplication.stats.duplication_percentage = if self.duplication.stats.total_lines > 0 {
874 (self.duplication.stats.duplicated_lines as f64
875 / self.duplication.stats.total_lines as f64)
876 * 100.0
877 } else {
878 0.0
879 };
880 }
881
882 pub fn filter_by_changed_files(&mut self, changed_files: &FxHashSet<PathBuf>, root: &Path) {
888 fallow_engine::changed_files::filter_results_by_changed_files(
889 &mut self.results,
890 changed_files,
891 );
892 fallow_engine::changed_files::filter_duplication_by_changed_files(
893 &mut self.duplication,
894 changed_files,
895 root,
896 );
897 }
898}
899
900#[cfg(test)]
901#[path = "editor_tests.rs"]
902pub(crate) mod tests;