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,
203 TestOnlyExportFinding, ThinWrapperFinding, TypeOnlyDependencyFinding,
204 UnlistedDependencyFinding, UnprovidedInjectFinding, UnrenderedComponentFinding,
205 UnresolvedCatalogReferenceFinding, UnresolvedImportFinding, UnusedCatalogEntryFinding,
206 UnusedClassMemberFinding, UnusedComponentEmitFinding, UnusedComponentInputFinding,
207 UnusedComponentOutputFinding, UnusedComponentPropFinding, UnusedDependencyFinding,
208 UnusedDependencyOverrideFinding, UnusedDevDependencyFinding, UnusedEnumMemberFinding,
209 UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding,
210 UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding,
211 UnusedProtectedClassMemberFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
212 UnusedSvelteEventFinding, UnusedTypeFinding,
213 };
214 pub use fallow_types::output_dead_code::{
215 UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
216 };
217 pub use fallow_types::results::{
218 AbsentComponentProp, ActiveSuppression, AnalysisResults, BoundaryCallViolation,
219 BoundaryCoverageViolation, BoundaryViolation, CircularDependency, CircularDependencyEdge,
220 ComponentPropCallSite, DependencyLocation, DependencyOverrideMisconfigReason,
221 DependencyOverrideSource, DeprecatedConsumerKind, DeprecatedExportConsumer,
222 DeprecatedExportInUse, DevDependencyInProduction, DuplicateExport, DuplicateLocation,
223 DuplicatePropShape, DuplicatePropShapeMember, DynamicSegmentNameConflict,
224 EmptyCatalogGroup, EntryPointSummary, ExportUsage, FeatureFlag, FlagConfidence, FlagKind,
225 ImportSite, InvalidClientExport, MisconfiguredDependencyOverride, MisplacedDirective,
226 MixedClientServerBarrel, NamespaceEscape, NamespaceEscapeReason, PackageCycle,
227 PackageCycleEdge, PolicyRuleKind, PolicyViolation, PolicyViolationSeverity,
228 PrivateTypeLeak, PropDrillHop, PropDrillingChain, ReExportCycle, ReExportCycleKind,
229 ReactComponentIntel, ReactHookSummary, ReactPropDrill, ReactPropIntel, ReferenceLocation,
230 RenderFanInComponent, RenderFanInMetric, RouteCollision, SecurityAttackSurfaceEntry,
231 SecurityCandidate, SecurityCandidateBoundary, SecurityCandidateSink,
232 SecurityDeadCodeContext, SecurityDeadCodeKind, SecurityDefensiveBoundary,
233 SecurityDefensiveControl, SecurityFinding, SecurityFindingKind, SecurityNetworkContext,
234 SecurityReachability, SecurityRuntimeContext, SecurityRuntimeState, SecuritySeverity,
235 SecurityTaintFlow, SecurityUnresolvedCalleeDiagnostic, SecurityZoneCrossing,
236 StaleSuppression, SuppressionOrigin, TaintConfidence, TaintEndpoint, TaintPath,
237 TestOnlyDependency, TestOnlyExport, ThinWrapper, TraceHop, TraceHopRole,
238 TypeOnlyDependency, UnlistedDependency, UnprovidedInject, UnrenderedComponent,
239 UnresolvedCatalogReference, UnresolvedImport, UnusedCatalogEntry, UnusedComponentEmit,
240 UnusedComponentInput, UnusedComponentOutput, UnusedComponentProp, UnusedDependency,
241 UnusedDependencyOverride, UnusedExport, UnusedFile, UnusedLoadDataKey, UnusedMember,
242 UnusedServerAction, UnusedSvelteEvent,
243 };
244 pub use fallow_types::results::{
245 ConstantParameter, ConstantParameterCallSite, ConstantParameterFinding,
246 ConstantParameterReason, ConstantParameterValue, ConstantParameterValueKind,
247 };
248 pub use fallow_types::results::{DuplicateExportAlias, DuplicateExportAliasLocation};
249 pub use fallow_types::results::{
250 EffectCatchSite, EffectLayerKind, UnproducedCatchTag, UnusedEffectLayer, UnusedTaggedError,
251 };
252}
253
254pub mod editor_security {
256 #[must_use]
258 pub fn security_catalogue_title(kind: &str) -> Option<&'static str> {
259 fallow_engine::dead_code::security_catalogue_title(kind)
260 }
261}
262
263pub mod editor_suppress {
265 pub use fallow_types::suppress::{IssueKind, is_suppressed};
266}
267
268pub type EditorAnalysisResults = fallow_types::results::AnalysisResults;
270
271#[derive(Debug)]
276pub struct EditorDeadCodeAnalysisOutput {
277 pub results: EditorAnalysisResults,
279 pub modules: Option<Vec<ModuleInfo>>,
282 pub files: Option<Vec<DiscoveredFile>>,
284}
285
286impl EditorDeadCodeAnalysisOutput {
287 fn from_engine(output: fallow_engine::dead_code::DeadCodeAnalysisOutput) -> Self {
288 Self {
289 results: output.results,
290 modules: output.modules,
291 files: output.files,
292 }
293 }
294}
295
296#[derive(Debug, Clone, PartialEq, Eq)]
302pub struct EditorInlineComplexityFinding {
303 pub path: PathBuf,
305 pub name: String,
307 pub line: u32,
309 pub col: u32,
311 pub cyclomatic: u16,
313 pub cognitive: u16,
315 pub exceeded: EditorInlineComplexityExceeded,
317}
318
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum EditorInlineComplexityExceeded {
322 Cyclomatic,
324 Cognitive,
326 CyclomaticAndCognitive,
328}
329
330#[must_use]
336pub fn collect_inline_complexity(
337 config: &fallow_config::ResolvedConfig,
338 output: &EditorDeadCodeAnalysisOutput,
339) -> Vec<EditorInlineComplexityFinding> {
340 let (Some(modules), Some(files)) = (output.modules.as_ref(), output.files.as_ref()) else {
341 return Vec::new();
342 };
343 fallow_engine::health::inline_complexity(config, modules, files)
344 .into_iter()
345 .map(|finding| EditorInlineComplexityFinding {
346 exceeded: match (finding.exceeds_cyclomatic, finding.exceeds_cognitive) {
347 (true, true) => EditorInlineComplexityExceeded::CyclomaticAndCognitive,
348 (true, false) => EditorInlineComplexityExceeded::Cyclomatic,
349 (false, _) => EditorInlineComplexityExceeded::Cognitive,
350 },
351 path: finding.path,
352 name: finding.name,
353 line: finding.line,
354 col: finding.col,
355 cyclomatic: finding.cyclomatic,
356 cognitive: finding.cognitive,
357 })
358 .collect()
359}
360
361#[expect(
363 clippy::implicit_hasher,
364 reason = "editor analysis changed-file sets use the workspace FxHashSet convention"
365)]
366pub fn filter_inline_complexity_by_changed_files(
367 findings: &mut Vec<EditorInlineComplexityFinding>,
368 changed_files: &FxHashSet<PathBuf>,
369) {
370 findings.retain(|finding| changed_files.contains(&finding.path));
371}
372
373pub fn filter_inline_complexity_by_change_scope(
375 findings: &mut Vec<EditorInlineComplexityFinding>,
376 scope: &ChangeScope,
377) {
378 findings.retain(|finding| scope.contains(&finding.path));
379}
380
381pub type EditorSessionParseCounts = fallow_engine::session::SessionParseCounts;
384
385#[derive(Debug)]
387pub struct EditorAnalysisSession {
388 inner: fallow_engine::session::AnalysisSession,
389 runs_duplication: bool,
391}
392
393impl EditorAnalysisSession {
394 pub fn open(run: &crate::run::ResolvedRun) -> Result<Self, crate::ProgrammaticError> {
402 use crate::run::AnalysisSlot;
403 use fallow_config::PlannedAnalysis;
404 let AnalysisSlot::Runs(dead_code) = run.analysis(PlannedAnalysis::DeadCode) else {
405 return Err(crate::ProgrammaticError::new(
406 "an editor session needs a run that plans the dead-code analysis",
407 2,
408 ));
409 };
410 Ok(Self {
411 inner: dead_code.open_session(),
412 runs_duplication: matches!(
413 run.analysis(PlannedAnalysis::Duplication),
414 AnalysisSlot::Runs(_)
415 ),
416 })
417 }
418
419 #[cfg(any(test, feature = "testing"))]
425 pub fn load(root: &Path, config_path: Option<&Path>) -> fallow_engine::EngineResult<Self> {
426 fallow_engine::session::AnalysisSession::load(root, config_path).map(Self::from_engine)
427 }
428
429 #[cfg(any(test, feature = "testing"))]
435 pub fn load_with_config(
436 root: &Path,
437 config_path: Option<&Path>,
438 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
439 ) -> fallow_engine::EngineResult<Self> {
440 fallow_engine::session::AnalysisSession::load_with_config(root, config_path, configure)
441 .map(Self::from_engine)
442 }
443
444 #[cfg(any(test, feature = "testing"))]
451 pub fn load_with_config_options(
452 root: &Path,
453 config_path: Option<&Path>,
454 load_options: fallow_config::ConfigLoadOptions,
455 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
456 ) -> fallow_engine::EngineResult<Self> {
457 fallow_engine::session::AnalysisSession::load_with_config_options(
458 root,
459 config_path,
460 load_options,
461 configure,
462 )
463 .map(Self::from_engine)
464 }
465
466 #[cfg(any(test, feature = "testing"))]
476 pub fn load_with_production(
477 root: &Path,
478 config_path: Option<&Path>,
479 load_options: fallow_config::ConfigLoadOptions,
480 production_override: Option<bool>,
481 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
482 ) -> fallow_engine::EngineResult<Self> {
483 let mut project = fallow_engine::project_config::config_for_project_with_production(
484 root,
485 config_path,
486 load_options,
487 fallow_engine::project_config::ProductionFlags {
488 global: production_override,
489 ..fallow_engine::project_config::ProductionFlags::default()
490 },
491 )?;
492 configure(&mut project.config);
493 Ok(Self::from_engine(
494 fallow_engine::session::AnalysisSession::from_config(
495 project.without_workspace_metadata(),
496 ),
497 ))
498 }
499
500 #[cfg(any(test, feature = "testing"))]
502 #[must_use]
503 pub fn load_default(root: &Path) -> Self {
504 Self::from_engine(fallow_engine::session::AnalysisSession::load_default(root))
505 }
506
507 #[cfg(any(test, feature = "testing"))]
510 #[must_use]
511 pub fn load_default_with_config(
512 root: &Path,
513 configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
514 ) -> Self {
515 Self::from_engine(
516 fallow_engine::session::AnalysisSession::load_default_with_config(root, configure),
517 )
518 }
519
520 #[must_use]
529 pub fn with_cancellation(
530 self,
531 cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
532 ) -> Self {
533 Self {
534 inner: self.inner.with_cancellation(cancellation),
535 runs_duplication: self.runs_duplication,
536 }
537 }
538
539 pub fn set_cancellation(
541 &mut self,
542 cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
543 ) {
544 self.inner.set_cancellation(cancellation);
545 }
546
547 pub fn refresh_discovery(&mut self) -> bool {
552 self.inner.refresh_discovery()
553 }
554
555 #[must_use]
559 pub fn config_inputs(&self) -> &fallow_config::ConfigInputs {
560 self.inner.config_inputs()
561 }
562
563 #[must_use]
566 pub fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
567 self.inner.config_inputs_before_resolve()
568 }
569
570 #[must_use]
573 pub fn retained_bytes_estimate(&self) -> u64 {
574 self.inner.retained_bytes_estimate()
575 }
576
577 pub fn flush_parse_cache(&self) {
580 self.inner.flush_parse_cache();
581 }
582
583 pub fn prewarm(&self, retain_complexity_artifacts: bool) -> fallow_engine::EngineResult<()> {
590 self.inner
591 .prewarm_parsed_modules(retain_complexity_artifacts)
592 }
593
594 #[must_use]
596 pub fn parse_counts(&self) -> EditorSessionParseCounts {
597 self.inner.parse_counts()
598 }
599
600 #[must_use]
602 pub fn config(&self) -> &fallow_config::ResolvedConfig {
603 self.inner.config()
604 }
605
606 pub fn change_scope(
614 &self,
615 request: ChangeScopeRequest<'_>,
616 ) -> Result<ChangeScope, PackageBaselineError> {
617 ChangeScope::resolve(request, self.inner.config(), self.inner.workspaces())
618 }
619
620 #[must_use]
625 pub fn unmatched_config_patterns(&self) -> Vec<fallow_config::WorkspaceDiagnostic> {
626 fallow_engine::dead_code::config_pattern_diagnostics(self.inner.config(), true)
627 }
628
629 #[must_use]
631 pub fn config_path(&self) -> Option<&Path> {
632 self.inner.config_path()
633 }
634
635 pub fn refine_type_aware_dead_code(
643 &self,
644 options: &crate::TypeAwareOptions,
645 filters: &crate::DeadCodeFilters,
646 output: &mut EditorDeadCodeAnalysisOutput,
647 ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
648 let meta = crate::type_aware::refine_programmatic_dead_code(
649 options,
650 filters,
651 &self.inner,
652 &mut output.results,
653 )?;
654 fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
658 Ok(meta)
659 }
660
661 pub fn refine_type_aware_dead_code_in_session(
663 &self,
664 semantic_session: &mut crate::TypeAwareSession,
665 changes: Option<&crate::TypeAwareFileChanges>,
666 options: &crate::TypeAwareOptions,
667 filters: &crate::DeadCodeFilters,
668 output: &mut EditorDeadCodeAnalysisOutput,
669 ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
670 let meta = crate::type_aware::refine_programmatic_dead_code_in_session(
671 semantic_session,
672 changes,
673 options,
674 filters,
675 &self.inner,
676 &mut output.results,
677 )?;
678 fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
679 Ok(meta)
680 }
681
682 pub fn analyze_project_with(
688 &self,
689 duplicates_config: &fallow_config::DuplicatesConfig,
690 retain_complexity_artifacts: bool,
691 ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
692 self.inner
693 .analyze_project_with(duplicates_config, retain_complexity_artifacts)
694 .map(EditorProjectAnalysisOutput::from_engine)
695 .map(|output| self.with_resolved_rule_severities(output))
696 }
697
698 pub fn analyze_project_with_changed_files(
709 &self,
710 duplicates_config: &fallow_config::DuplicatesConfig,
711 retain_complexity_artifacts: bool,
712 changed_files: Option<&FxHashSet<PathBuf>>,
713 ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
714 let artifacts = if self.runs_duplication {
715 self.inner.analyze_project_with_artifacts(
716 duplicates_config,
717 fallow_engine::project_analysis::ProjectAnalysisArtifactOptions {
718 retain_complexity_artifacts,
719 changed_files: changed_files.cloned(),
720 ..fallow_engine::project_analysis::ProjectAnalysisArtifactOptions::default()
721 },
722 )?
723 } else {
724 fallow_engine::project_analysis::ProjectAnalysisArtifacts {
725 dead_code: self
726 .inner
727 .analyze_dead_code_with_artifacts(retain_complexity_artifacts, false)?,
728 duplication: fallow_types::duplicates::DuplicationReport::default(),
729 ignored_clone_groups: Vec::new(),
730 changed_files: changed_files.cloned(),
731 source_fingerprints: None,
732 }
733 };
734 Ok(
735 self.with_resolved_rule_severities(EditorProjectAnalysisOutput::from_engine(
736 artifacts.into_output(),
737 )),
738 )
739 }
740
741 pub fn apply_change_scope(
749 &self,
750 output: &mut EditorProjectAnalysisOutput,
751 scope: &ChangeScope,
752 ) {
753 fallow_engine::dead_code::apply_scope(
754 &mut output.dead_code.results,
755 &fallow_engine::dead_code::DeadCodeScope {
756 workspace_roots: None,
757 changes: Some(scope),
758 diff: None,
759 files: None,
760 },
761 self.inner.config(),
762 );
763 fallow_engine::duplicates::apply_scope(
764 &mut output.duplication,
765 &fallow_engine::duplicates::DuplicationScope {
766 changes: Some(scope),
767 diff: None,
768 workspace_roots: None,
769 },
770 &self.inner.config().root,
771 );
772 }
773
774 fn with_resolved_rule_severities(
781 &self,
782 mut output: EditorProjectAnalysisOutput,
783 ) -> EditorProjectAnalysisOutput {
784 fallow_engine::dead_code::apply_rule_severities(
785 &mut output.dead_code.results,
786 self.inner.config(),
787 );
788 output
789 }
790
791 #[cfg(any(test, feature = "testing"))]
795 fn from_engine(inner: fallow_engine::session::AnalysisSession) -> Self {
796 Self {
797 runs_duplication: inner.config().duplicates.runs_by_default(),
798 inner,
799 }
800 }
801}
802
803#[derive(Debug)]
805pub struct EditorProjectAnalysisOutput {
806 pub dead_code: EditorDeadCodeAnalysisOutput,
808 pub duplication: EditorDuplicationReport,
810}
811
812impl EditorProjectAnalysisOutput {
813 fn from_engine(output: fallow_engine::project_analysis::ProjectAnalysisOutput) -> Self {
814 Self {
815 dead_code: EditorDeadCodeAnalysisOutput::from_engine(output.dead_code),
816 duplication: output.duplication,
817 }
818 }
819}
820
821#[derive(Debug, Default)]
823pub struct EditorAnalysisOutput {
824 pub results: EditorAnalysisResults,
826 pub duplication: EditorDuplicationReport,
828}
829
830impl EditorAnalysisOutput {
831 #[must_use]
833 pub const fn new(results: EditorAnalysisResults, duplication: EditorDuplicationReport) -> Self {
834 Self {
835 results,
836 duplication,
837 }
838 }
839
840 pub fn merge_project_output(&mut self, output: EditorProjectAnalysisOutput) {
842 self.merge_results(output.dead_code.results);
843 self.merge_duplication(output.duplication);
844 }
845
846 pub fn merge_results(&mut self, source: EditorAnalysisResults) {
848 self.results.merge_into(source);
849 }
850
851 pub fn merge_duplication(&mut self, source: EditorDuplicationReport) {
854 self.duplication.clone_groups.extend(source.clone_groups);
855 self.duplication
856 .clone_families
857 .extend(source.clone_families);
858 self.duplication
859 .mirrored_directories
860 .extend(source.mirrored_directories);
861 self.duplication.stats.clone_groups += source.stats.clone_groups;
862 self.duplication.stats.clone_families += source.stats.clone_families;
863 self.duplication.stats.clone_instances += source.stats.clone_instances;
864 self.duplication.stats.total_files += source.stats.total_files;
865 self.duplication.stats.files_with_clones += source.stats.files_with_clones;
866 self.duplication.stats.total_lines += source.stats.total_lines;
867 self.duplication.stats.duplicated_lines += source.stats.duplicated_lines;
868 self.duplication.stats.total_tokens += source.stats.total_tokens;
869 self.duplication.stats.duplicated_tokens += source.stats.duplicated_tokens;
870 self.duplication.stats.clone_groups_below_min_occurrences +=
871 source.stats.clone_groups_below_min_occurrences;
872 self.duplication.stats.clone_groups_ignored += source.stats.clone_groups_ignored;
873 self.duplication.stats.near_candidates_skipped += source.stats.near_candidates_skipped;
874 self.duplication.stats.duplication_percentage = if self.duplication.stats.total_lines > 0 {
875 (self.duplication.stats.duplicated_lines as f64
876 / self.duplication.stats.total_lines as f64)
877 * 100.0
878 } else {
879 0.0
880 };
881 }
882
883 pub fn filter_by_changed_files(&mut self, changed_files: &FxHashSet<PathBuf>, root: &Path) {
889 fallow_engine::changed_files::filter_results_by_changed_files(
890 &mut self.results,
891 changed_files,
892 );
893 fallow_engine::changed_files::filter_duplication_by_changed_files(
894 &mut self.duplication,
895 changed_files,
896 root,
897 );
898 }
899}
900
901#[cfg(test)]
902#[path = "editor_tests.rs"]
903pub(crate) mod tests;