Documentation
¶
Index ¶
- Constants
- Variables
- func AggregateComplexityByModule(functions []FunctionComplexity) map[string]ModuleComplexityMetrics
- func AggregateDeadCodeByModule(files []FileDeadCode) map[string]ModuleDeadCodeMetrics
- func BoolPtr(b bool) *bool
- func BoolValue(b *bool, defaultVal bool) bool
- func DefaultAnalysisExcludePatterns() []string
- func DefaultAnalysisIncludePatterns() []string
- func DefaultMockDataDomains() []string
- func DefaultMockDataKeywords() []string
- func DefaultMockDataTestPatterns() []string
- func DefaultPythonModuleIncludePatterns() []string
- func DefaultPythonSourceIncludePatterns() []string
- func Float64Ptr(v float64) *float64
- func GetGradeFromScore(score int) string
- func NewAnalysisError(message string, cause error) error
- func NewCancelledError(message string, cause error) error
- func NewConfigError(message string, cause error) error
- func NewDomainError(code, message string, cause error) error
- func NewFileNotFoundError(path string, cause error) error
- func NewInternalError(message string, cause error) error
- func NewInvalidInputError(message string, cause error) error
- func NewNotImplementedError(feature string) error
- func NewOutputError(message string, cause error) error
- func NewParseError(file string, cause error) error
- func NewTimeoutError(message string, cause error) error
- func NewUnsupportedFormatError(format string) error
- func NewValidationError(message string) error
- func ScoreCommunityResult(result *CommunityAnalysisResult)
- func ServiceLocatorMethodNames() []string
- func ShouldUseLSH(lshEnabled string, fragmentCount int, autoThreshold int) bool
- func ShouldUseLSHWithPairEstimate(lshEnabled string, fragmentCount int, autoThreshold int, pairThreshold int) bool
- func ValidateFunctionSLOCThresholds(warn, critical int) error
- type AnalysisCoverage
- type AnalysisDiagnostic
- type AnalysisFailure
- type AnalysisFailureCode
- type AnalysisFailureReporter
- type AnalysisKind
- type AnalysisScopeKind
- type AnalyzeConfigurationLoader
- type AnalyzeExecutionConfig
- type AnalyzeOutputFormatter
- type AnalyzeResponse
- type AnalyzeSummary
- type ArchitectureAnalysisResult
- type ArchitectureRecommendation
- type ArchitectureRules
- type ArchitectureViolation
- type BridgeModule
- type CBOAnalysisOptions
- type CBOConfigurationLoader
- type CBOMetrics
- type CBOOutputFormatter
- type CBORequest
- type CBOResponse
- type CBOService
- type CBOSummary
- type CategorizedError
- type CircularDependency
- type CircularDependencyAnalysis
- type ClassCohesion
- type ClassCoupling
- type Clone
- type CloneConfigurationLoader
- type CloneGroup
- type CloneLocation
- type CloneOutputFormatter
- type ClonePair
- type CloneRequest
- type CloneResponse
- type CloneService
- type CloneSortCriteria
- type CloneStatistics
- type CloneType
- type CohesionAnalysis
- type CommunityAnalysisOutputFormatter
- type CommunityAnalysisRequest
- type CommunityAnalysisResult
- type CommunityAnalysisService
- type CommunityBundle
- type CommunityConfigurationLoader
- type CommunityContextMap
- type CommunityMetrics
- type CommunityModuleDependency
- type ComplexityMetrics
- type ComplexityRequest
- type ComplexityResponse
- func (r *ComplexityResponse) AnalysisFailures() []AnalysisFailure
- func (r *ComplexityResponse) AnalyzedScopes() ([]FunctionComplexity, error)
- func (r *ComplexityResponse) ReportedScopes(sortBy SortCriteria) ([]FunctionComplexity, error)
- func (r *ComplexityResponse) ReportedScopesByComplexity() []FunctionComplexity
- func (r *ComplexityResponse) ValidateAnalyzedScopes() error
- type ComplexityService
- type ComplexitySummary
- type ConcreteDependencySubtype
- type ConfigurationLoader
- type ContextBridgeModule
- type CouplingAnalysis
- type CustomRule
- type CycleSeverity
- type DIAntipatternConfigurationLoader
- type DIAntipatternFinding
- type DIAntipatternOutputFormatter
- type DIAntipatternRequest
- type DIAntipatternResponse
- type DIAntipatternService
- type DIAntipatternSeverity
- type DIAntipatternSummary
- type DIAntipatternType
- type DeadCodeConfigurationLoader
- type DeadCodeFinding
- type DeadCodeFormatter
- type DeadCodeLocation
- type DeadCodeRequest
- type DeadCodeResponse
- type DeadCodeService
- type DeadCodeSeverity
- type DeadCodeSortCriteria
- type DeadCodeSummary
- type DependencyAnalysisResult
- type DependencyPath
- type DiagnosticCode
- type DirectoryComplexityMetrics
- type DirectoryComplexityMetricsList
- type DomainError
- type ErrorCategorizer
- type ErrorCategory
- type EstimatedEffort
- type ExecutableTask
- type FileDeadCode
- type FileMockData
- type FileReader
- type FunctionComplexity
- type FunctionDeadCode
- func (fdc *FunctionDeadCode) CalculateSeverityCounts()
- func (fdc *FunctionDeadCode) GetFindingsAtSeverity(minSeverity DeadCodeSeverity) []DeadCodeFinding
- func (fdc *FunctionDeadCode) HasFindings() bool
- func (fdc *FunctionDeadCode) HasFindingsAtSeverity(minSeverity DeadCodeSeverity) bool
- func (f FunctionDeadCode) ScopeLabel() string
- type HiddenDependencySubtype
- type IssueSeverity
- type IssueType
- type LCOMConfigurationLoader
- type LCOMMetrics
- type LCOMOutputFormatter
- type LCOMRequest
- type LCOMResponse
- type LCOMService
- type LCOMSummary
- type Layer
- type LayerAnalysis
- type LayerRule
- type LayerViolation
- type MockDataConfigurationLoader
- type MockDataFinding
- type MockDataFormatter
- type MockDataLocation
- type MockDataRequest
- type MockDataResponse
- type MockDataService
- type MockDataSeverity
- type MockDataSortCriteria
- type MockDataSummary
- type MockDataType
- type ModuleComplexityMetrics
- type ModuleDeadCodeMetrics
- type ModuleDependencyMetrics
- type ModuleGraphOptions
- type ModuleQualityMetrics
- type OutputFormat
- type OutputFormatter
- type PackageRule
- type ParallelExecutor
- type ProgressManager
- type PythonFileSelection
- type RawMetrics
- type RawMetricsSummary
- type RecommendationCategory
- type RecommendationPriority
- type RecommendationType
- type ReportWriter
- type ResponsibilityAnalysis
- type RiskLevel
- type SRPViolation
- type SortCriteria
- type SourceLocation
- type Suggestion
- type SuggestionCategory
- type SuggestionEffort
- type SuggestionSeverity
- type SystemAnalysisConfigurationLoader
- type SystemAnalysisOutputFormatter
- type SystemAnalysisRequest
- type SystemAnalysisResponse
- type SystemAnalysisService
- type SystemAnalysisSummary
- type SystemIssue
- type SystemRecommendation
- type ViolationSeverity
- type ViolationType
Constants ¶
const ( // Complexity thresholds and penalties ComplexityThresholdHigh = coredomain.ComplexityThresholdHigh ComplexityThresholdMedium = coredomain.ComplexityThresholdMedium ComplexityThresholdLow = coredomain.ComplexityThresholdLow ComplexityPenaltyHigh = coredomain.ComplexityPenaltyHigh ComplexityPenaltyMedium = coredomain.ComplexityPenaltyMedium ComplexityPenaltyLow = coredomain.ComplexityPenaltyLow // Code duplication thresholds and penalties // 0% = perfect, 60% = max penalty (using fragment ratio: clonedFragments/totalFragments) DuplicationThresholdHigh = coredomain.DuplicationThresholdHigh DuplicationThresholdMedium = coredomain.DuplicationThresholdMedium DuplicationThresholdLow = coredomain.DuplicationThresholdLow DuplicationPenaltyHigh = coredomain.DuplicationPenaltyHigh DuplicationPenaltyMedium = coredomain.DuplicationPenaltyMedium DuplicationPenaltyLow = coredomain.DuplicationPenaltyLow // CBO coupling scoring curve (used by calculateCouplingPenalty) // Penalty grows linearly with the weighted ratio of problematic classes // and saturates (reaches the max penalty) at CouplingSaturationRatio. CouplingMediumWeight = coredomain.CouplingMediumWeight CouplingSaturationRatio = coredomain.CouplingSaturationRatio // LCOM cohesion scoring curve (used by calculateCohesionPenalty) // Penalty grows linearly with the weighted ratio of low-cohesion classes // and saturates (reaches the max penalty) at CohesionSaturationRatio. CohesionMediumWeight = 0.3 // Medium-risk classes count 0.3 vs High = 1.0 CohesionSaturationRatio = 0.40 // weighted ratio at which the penalty maxes out // Maximum penalties MaxDeadCodePenalty = coredomain.MaxDeadCodePenalty MaxCriticalPenalty = coredomain.MaxCriticalPenalty MaxCyclesPenalty = coredomain.MaxCyclesPenalty MaxDepthPenalty = coredomain.MaxDepthPenalty MaxArchPenalty = coredomain.MaxArchPenalty MaxMSDPenalty = coredomain.MaxMSDPenalty // Community detection scoring only applies when communities ran // with at least two detected communities). The risk score is a weighted // blend of the factors below; the health-score penalty is bounded at // MaxCommunityPenalty so disabling communities cannot move existing grades. MaxCommunityPenalty = 10 // bounded contribution to the overall health score CommunityModularityTarget = 0.30 // Q at or above which modularity risk is zero CommunityCrossEdgeSaturation = 0.50 // cross-community edge ratio at which that risk maxes out // Risk-factor weights (core factors sum to 1.0; optional factors are added // and the blend is renormalised over whatever factors are available). CommunityModularityWeight = 0.40 CommunityCrossEdgeWeight = 0.30 CommunityBridgeWeight = 0.30 CommunityPackageWeight = 0.25 CommunityLayerWeight = 0.25 // Per-community risk_level thresholds, expressed as risk ratios (0..1). CommunityRiskHighRatio = 0.60 // >= high CommunityRiskMediumRatio = 0.30 // >= medium, otherwise low // Parse-error penalty bounds MinParseErrorPenalty = coredomain.MinParseErrorPenalty MaxParseErrorPenalty = coredomain.MaxParseErrorPenalty // Score display scale - all categories normalized to this base MaxScoreBase = coredomain.MaxScoreBase // Actual maximum penalty values for normalization MaxDependencyPenalty = coredomain.MaxDependencyPenalty // 16 MaxArchitecturePenalty = coredomain.MaxArchitecturePenalty // 12 // Grade thresholds GradeAThreshold = coredomain.GradeAThreshold GradeBThreshold = coredomain.GradeBThreshold GradeCThreshold = coredomain.GradeCThreshold GradeDThreshold = coredomain.GradeDThreshold // Score quality thresholds (aligned with grade thresholds) ScoreThresholdExcellent = coredomain.ScoreThresholdExcellent // Excellent: 90-100 ScoreThresholdGood = coredomain.ScoreThresholdGood // Good: 75-89 ScoreThresholdFair = coredomain.ScoreThresholdFair // Fair: 60-74 // Other constants MinimumScore = coredomain.MinimumScore HealthyThreshold = coredomain.HealthyThreshold FallbackComplexityThreshold = coredomain.FallbackComplexityThreshold FallbackPenalty = coredomain.FallbackPenalty )
Health Score Calculation Constants Shared thresholds, penalties, and grade mapping come from polyscan core so grade computation stays identical across language analyzers. pyscn-specific categories (cohesion, community) keep their constants here.
const ( // DefaultType1CloneThreshold represents the similarity threshold for Type-1 clones. // Type-1 clones are identical code fragments except for variations in whitespace, // layout and comments. Allows whitespace/comment differences (≥85%). DefaultType1CloneThreshold = 0.85 // DefaultType2CloneThreshold represents the similarity threshold for Type-2 clones. // Type-2 clones are syntactically identical fragments except for variations in // identifiers, literals, types, layout and comments. Allows identifier/literal changes (≥75%). DefaultType2CloneThreshold = 0.75 // DefaultType3CloneThreshold represents the similarity threshold for Type-3 clones. // Type-3 clones are copied fragments with further modifications such as changed, // added or removed statements. Excluded by default; threshold maintains ordering (≥70%). DefaultType3CloneThreshold = 0.70 // DefaultType4CloneThreshold represents the similarity threshold for Type-4 clones. // Type-4 clones are syntactically different but functionally similar fragments. // They perform the same computation but through different syntactic variants. // Detects functional similarity (≥65%). DefaultType4CloneThreshold = 0.65 )
CloneThresholds defines the standard similarity thresholds for different types of code clones. These values are based on research in clone detection and represent industry standards.
References: - Roy, C. K., & Cordy, J. R. (2007). A survey on software clone detection research - Bellon, S., et al. (2007). Comparison and evaluation of clone detection tools
const ( // DefaultDFAPairCountWeight is the weight for total def-use pair count similarity. // Higher pair count often indicates more complex data flow, which is a key semantic indicator. DefaultDFAPairCountWeight = 0.25 // DefaultDFAChainLengthWeight is the weight for average chain length similarity. // Chain length (uses per definition) indicates variable reuse patterns. DefaultDFAChainLengthWeight = 0.20 // DefaultDFACrossBlockWeight is the weight for cross-block pair ratio similarity. // Cross-block pairs indicate data dependencies across control flow, a key structural pattern. DefaultDFACrossBlockWeight = 0.20 // DefaultDFADefKindWeight is the weight for definition kind distribution similarity. // Different definition kinds (assign, param, loop) indicate different coding patterns. DefaultDFADefKindWeight = 0.20 // DefaultDFAUseKindWeight is the weight for use kind distribution similarity. // How variables are used (read, call, attribute) reflects access patterns. DefaultDFAUseKindWeight = 0.15 )
DFA (Data Flow Analysis) Feature Weights for semantic similarity comparison. These weights determine how each DFA metric contributes to the overall similarity score.
const ( // DefaultCFGFeatureWeight is the weight for CFG-based features in semantic similarity. // CFG captures control flow structure (branches, loops, etc.). DefaultCFGFeatureWeight = 0.60 // DefaultDFAFeatureWeight is the weight for DFA-based features in semantic similarity. // DFA captures data flow patterns (variable definitions and uses). DefaultDFAFeatureWeight = 0.40 // DefaultSemanticMinCyclomaticComplexity is the minimum cyclomatic complexity // (McCabe's V(G) = E - N + 2) a fragment's CFG must have to be eligible for // Type-4 (semantic) clone classification. Fully linear fragments (V(G)=1) // produce saturated, indiscriminate CFG similarity scores — the "tiny linear // function looks like every other tiny linear function" problem observed in // cross-repo audits — because pyscn's CFG builder emits the same handful of // entry/linear/exit blocks regardless of how many statements the body has. // // Gating on V(G) >= 2 cleanly admits any fragment with at least one decision // (if / for / while / try / with) while rejecting purely linear shapes. Using // cyclomatic complexity instead of raw block count avoids penalising standalone // control-flow statement fragments (e.g. `NodeIf` without `else`), whose CFG // happens to have fewer synthetic blocks than the equivalent function body. DefaultSemanticMinCyclomaticComplexity = 2 )
Combined Semantic Feature Weights for Type-4 clone detection. When DFA analysis is enabled, both CFG and DFA features contribute to similarity.
const ( // DefaultComplexityLowThreshold is the upper bound for low-risk complexity. // Functions with complexity <= 9 are considered simple and maintainable. DefaultComplexityLowThreshold = 9 // DefaultComplexityMediumThreshold is the upper bound for medium-risk complexity. // Functions with complexity 10-19 require attention but are acceptable. DefaultComplexityMediumThreshold = 19 // DefaultComplexityMinFilter is the minimum complexity to include in reports. // Default 1 means all functions are included. DefaultComplexityMinFilter = 1 // DefaultComplexityMaxLimit is the maximum complexity limit for enforcement. // 0 means no limit is enforced. DefaultComplexityMaxLimit = 0 // DefaultCognitiveComplexityThreshold is the high-risk threshold for // SonarQube-style cognitive complexity. DefaultCognitiveComplexityThreshold = 25 // DefaultNestingDepthThreshold is the high-risk threshold for maximum // nesting depth. DefaultNestingDepthThreshold = 7 // DefaultFunctionSLOCWarnThreshold is the upper bound for function SLOC // before a function is reported as long (analogous to LowThreshold for McCabe). DefaultFunctionSLOCWarnThreshold = 50 // FunctionSLOCCriticalMultiplier separates the two long-function tiers. It // also derives whichever tier the user leaves unset from the one they set. FunctionSLOCCriticalMultiplier = 2 // DefaultFunctionSLOCCriticalThreshold is the upper bound for function SLOC // before a function fails the check gate (analogous to MediumThreshold for McCabe). DefaultFunctionSLOCCriticalThreshold = DefaultFunctionSLOCWarnThreshold * FunctionSLOCCriticalMultiplier )
Complexity thresholds based on McCabe cyclomatic complexity. Reference: McCabe, T.J. (1976). A Complexity Measure
const ( // DefaultCBOLowThreshold is the upper bound for low-risk coupling. // Classes with CBO <= 3 are well-encapsulated. DefaultCBOLowThreshold = 3 // DefaultCBOMediumThreshold is the upper bound for medium-risk coupling. // Classes with CBO 4-7 may need refactoring consideration. DefaultCBOMediumThreshold = 7 )
CBO thresholds based on Chidamber & Kemerer metrics suite. Reference: Chidamber, S.R. & Kemerer, C.F. (1994). A Metrics Suite for OOD
const ( // DefaultArchitectureMinCohesion is the minimum package cohesion score before a package is flagged. DefaultArchitectureMinCohesion = 0.5 // DefaultArchitectureMaxResponsibilities is the maximum inferred responsibilities per module. DefaultArchitectureMaxResponsibilities = 3 )
const ( // DefaultLCOMLowThreshold is the upper bound for low-risk LCOM. // Classes with LCOM4 <= 2 have high cohesion. DefaultLCOMLowThreshold = 2 // DefaultLCOMMediumThreshold is the upper bound for medium-risk LCOM. // Classes with LCOM4 3-5 have acceptable cohesion. DefaultLCOMMediumThreshold = 5 // DefaultCommunityAlgorithm is the community detection algorithm identifier. DefaultCommunityAlgorithm = "leiden" // DefaultCommunityScope is the graph scope for community detection. DefaultCommunityScope = "module" // DefaultCommunityMinSize is the minimum community size after detection. DefaultCommunityMinSize = 1 // DefaultCommunityResolution is the Leiden resolution parameter. DefaultCommunityResolution = 1.0 )
LCOM4 thresholds based on Hitz & Montazeri graph-based algorithm. Reference: Hitz, M. & Montazeri, B. (1995). Measuring Coupling and Cohesion in OO Systems
const ( // DefaultDeadCodeMinSeverity is the minimum severity level for dead code reports. // Options: "info", "warning", "critical" DefaultDeadCodeMinSeverity = "warning" // DefaultDeadCodeContextLines is the number of context lines shown around dead code. DefaultDeadCodeContextLines = 3 // DefaultDeadCodeSortBy is the default sort order for dead code results. // Options: "severity", "file", "line" DefaultDeadCodeSortBy = "severity" )
const ( // DefaultCloneMinLines is the minimum number of lines for a code fragment to be considered. DefaultCloneMinLines = 10 // DefaultCloneMinNodes is the minimum number of AST nodes for a code fragment. DefaultCloneMinNodes = 20 // DefaultCloneMaxEditDistance is the maximum tree edit distance for clone comparison. DefaultCloneMaxEditDistance = 50.0 // DefaultCloneSimilarityThreshold is the general similarity threshold for clone detection. // Aligned with Type-4 threshold to include all detected clones in reports. DefaultCloneSimilarityThreshold = 0.65 // DefaultCloneGroupingThreshold is the threshold for grouping related clones. // Uses Type-4 threshold as default for grouping to include all detected clones. DefaultCloneGroupingThreshold = DefaultType4CloneThreshold )
const ( // DefaultLSHAutoThreshold is the fragment count threshold for automatic LSH activation. // When fragment count exceeds this, LSH acceleration is automatically enabled. DefaultLSHAutoThreshold = 500 // DefaultLSHAutoPairThreshold is the estimated pair count threshold for // automatic LSH activation. This catches small repos with enough fragments // to make exact pairwise APTED comparisons too expensive. DefaultLSHAutoPairThreshold = 10000 // DefaultLSHSimilarityThreshold is the minimum similarity for LSH candidate filtering. DefaultLSHSimilarityThreshold = 0.50 // DefaultLSHBands is the number of bands in the LSH algorithm. DefaultLSHBands = 32 // DefaultLSHRows is the number of rows per band in the LSH algorithm. DefaultLSHRows = 4 // DefaultLSHHashes is the total number of hash functions used. DefaultLSHHashes = 128 )
const ( // DefaultMaxMemoryMB is the maximum memory usage in megabytes for batch processing. DefaultMaxMemoryMB = 100 // DefaultBatchSize is the default batch size for processing files. DefaultBatchSize = 100 // DefaultMaxGoroutines is the default number of concurrent goroutines. DefaultMaxGoroutines = 4 // DefaultTimeoutSeconds is the default timeout in seconds for analysis operations. DefaultTimeoutSeconds = 300 )
const ( // DefaultDIConstructorParamThreshold is the maximum allowed constructor parameters. // Classes with more than 5 parameters in __init__ are flagged as constructor over-injection. // Reference: Martin, R.C. (2008). Clean Code - recommends max 3-4, we use 5 as threshold. DefaultDIConstructorParamThreshold = 5 // DefaultDIMinSeverity is the minimum severity level for DI anti-pattern reports. // Options: "info", "warning", "error" DefaultDIMinSeverity = "warning" )
const ( // DefaultMockDataMinSeverity is the minimum severity level for mock data reports. // Options: "info", "warning", "error" DefaultMockDataMinSeverity = "warning" // DefaultMockDataSortBy is the default sort order for mock data results. // Options: "severity", "file", "line", "type" DefaultMockDataSortBy = "severity" // DefaultMockDataIgnoreTests determines whether test files are ignored by default. DefaultMockDataIgnoreTests = true )
const ( ErrCodeInvalidInput = "INVALID_INPUT" ErrCodeFileNotFound = "FILE_NOT_FOUND" ErrCodeParseError = "PARSE_ERROR" ErrCodeAnalysisError = "ANALYSIS_ERROR" ErrCodeConfigError = "CONFIG_ERROR" ErrCodeOutputError = "OUTPUT_ERROR" ErrCodeUnsupportedFormat = "UNSUPPORTED_FORMAT" ErrCodeTimeout = "TIMEOUT" ErrCodeCancelled = "CANCELLED" ErrCodeNotImplemented = "NOT_IMPLEMENTED" ErrCodeInternal = "INTERNAL" )
Domain error codes
const AnalyzeSchemaVersion = 1
AnalyzeSchemaVersion identifies the key layout of the analyze JSON/YAML report. Bump it on any breaking change to the documented keys (rename, removal, type change) so consumers can detect the change; additive changes do not bump it.
const CommunityContextMapModuleLimit = 10
CommunityContextMapModuleLimit caps how many modules are listed per bundle before the remainder is collapsed into a "... +N more" marker, keeping the map token-efficient for AI agents on large repositories.
const CommunityContextMapVersion = 1
CommunityContextMapVersion is the schema version of CommunityContextMap. Bump it when the shape of the context map changes in a breaking way.
const ModuleFunctionName = "<module>"
ModuleFunctionName is the user-facing label used for module-scope (top-level) code in places that key/display per-function results. The angle brackets follow Python's own convention (e.g. tracebacks and `dis` output) and signal that this is not a real function defined in the source.
Variables ¶
var CloneTypeDescriptions = map[int]string{
1: "Identical code fragments except for whitespace, layout and comments",
2: "Syntactically identical except for variations in identifiers, literals and types",
3: "Copied fragments with further modifications (changed, added or removed statements)",
4: "Syntactically different but functionally similar code fragments",
}
CloneTypeDescriptions provides detailed descriptions for each clone type
var CloneTypeNames = map[int]string{
1: "Type-1 (Identical)",
2: "Type-2 (Renamed)",
3: "Type-3 (Near-Miss)",
4: "Type-4 (Semantic)",
}
CloneTypeNames provides human-readable names for clone types
var DefaultEnabledCloneTypeStrings = []string{"type1", "type2", "type4"}
DefaultEnabledCloneTypeStrings provides string representations for config files.
var DefaultEnabledCloneTypes = []CloneType{Type1Clone, Type2Clone, Type4Clone}
DefaultEnabledCloneTypes defines the clone types enabled by default. Type-3 is excluded by default to reduce near-miss false positives in day-to-day analysis. Users can opt in when they want broader detection.
Functions ¶
func AggregateComplexityByModule ¶ added in v1.29.0
func AggregateComplexityByModule(functions []FunctionComplexity) map[string]ModuleComplexityMetrics
AggregateComplexityByModule derives module metrics from the complete, pre-filter complexity population owned by the complexity service.
func AggregateDeadCodeByModule ¶ added in v1.29.0
func AggregateDeadCodeByModule(files []FileDeadCode) map[string]ModuleDeadCodeMetrics
AggregateDeadCodeByModule derives module metrics from the complete, pre-severity-filter dead-code population owned by the dead-code service.
func BoolPtr ¶ added in v1.4.0
BoolPtr creates a pointer to a boolean value This is useful for creating pointer boolean values inline
func BoolValue ¶ added in v1.4.0
BoolValue safely dereferences a boolean pointer, returning defaultVal if nil This allows safe access to pointer booleans with explicit defaults
func DefaultAnalysisExcludePatterns ¶ added in v1.22.4
func DefaultAnalysisExcludePatterns() []string
DefaultAnalysisExcludePatterns returns the canonical default file-glob patterns excluded from all analyses (CBO, complexity, dead code, clones, LCOM, system analysis). Callers must copy before mutating.
func DefaultAnalysisIncludePatterns ¶ added in v1.22.5
func DefaultAnalysisIncludePatterns() []string
DefaultAnalysisIncludePatterns returns the canonical runtime source-file globs used by implementation analyses.
func DefaultMockDataDomains ¶ added in v1.7.0
func DefaultMockDataDomains() []string
DefaultMockDataDomains returns the default domains that indicate mock data. These are reserved domains per RFC 2606 and common test domains.
func DefaultMockDataKeywords ¶ added in v1.7.0
func DefaultMockDataKeywords() []string
DefaultMockDataKeywords returns the default keywords used to detect mock data. These are common identifiers used in placeholder/mock data.
func DefaultMockDataTestPatterns ¶ added in v1.7.0
func DefaultMockDataTestPatterns() []string
DefaultMockDataTestPatterns returns the default patterns for test files to ignore.
func DefaultPythonModuleIncludePatterns ¶ added in v1.22.5
func DefaultPythonModuleIncludePatterns() []string
DefaultPythonModuleIncludePatterns returns the full Python module surface. Dependency analysis uses this because stub files define importable modules.
func DefaultPythonSourceIncludePatterns ¶ added in v1.22.5
func DefaultPythonSourceIncludePatterns() []string
DefaultPythonSourceIncludePatterns returns runtime Python implementation files. Analyses that score executable code should use this contract.
func Float64Ptr ¶ added in v1.25.0
Float64Ptr creates a pointer to a float64 value.
func GetGradeFromScore ¶
GetGradeFromScore maps a health score to a letter grade
func NewAnalysisError ¶
NewAnalysisError creates an analysis error
func NewCancelledError ¶ added in v1.10.1
NewCancelledError creates a cancellation error
func NewConfigError ¶
NewConfigError creates a configuration error
func NewDomainError ¶
NewDomainError creates a new domain error
func NewFileNotFoundError ¶
NewFileNotFoundError creates a file not found error
func NewInternalError ¶ added in v1.10.1
NewInternalError creates an internal error
func NewInvalidInputError ¶
NewInvalidInputError creates an invalid input error
func NewNotImplementedError ¶ added in v1.10.1
NewNotImplementedError creates a not implemented error
func NewOutputError ¶
NewOutputError creates an output error
func NewParseError ¶
NewParseError creates a parse error
func NewTimeoutError ¶ added in v1.10.1
NewTimeoutError creates a timeout error
func NewUnsupportedFormatError ¶
NewUnsupportedFormatError creates an unsupported format error
func NewValidationError ¶
NewValidationError creates a validation error
func ScoreCommunityResult ¶ added in v1.25.0
func ScoreCommunityResult(result *CommunityAnalysisResult)
ScoreCommunityResult computes the system-level community risk score and the per-community risk_level, mutating the result in place. It is the single entry point used by both the standalone community command and the analyze health score, so the numbers stay consistent. Safe to call with a nil result.
func ServiceLocatorMethodNames ¶ added in v1.16.0
func ServiceLocatorMethodNames() []string
ServiceLocatorMethodNames returns the method names that indicate service locator pattern Note: Generic .get() methods are excluded to avoid false positives with dict.get() etc.
func ShouldUseLSH ¶ added in v1.0.3
ShouldUseLSH determines whether to use LSH based on configuration and fragment count. This centralizes the legacy LSH decision logic used by callers that only know fragment count.
func ShouldUseLSHWithPairEstimate ¶ added in v1.20.0
func ShouldUseLSHWithPairEstimate(lshEnabled string, fragmentCount int, autoThreshold int, pairThreshold int) bool
ShouldUseLSHWithPairEstimate determines whether to use LSH based on explicit configuration, fragment count, and the estimated number of pairwise comparisons.
func ValidateFunctionSLOCThresholds ¶ added in v1.29.1
ValidateFunctionSLOCThresholds checks the long-function tiers against each other. A non-positive value means "not configured" and is left to the layer's own defaulting; only a fully specified, inverted pair is an error. Messages name the configuration keys, which match the CLI flags.
Types ¶
type AnalysisCoverage ¶ added in v1.30.0
type AnalysisCoverage struct {
TotalFiles int
AnalyzedFiles int
SkippedFiles int
Diagnostics []AnalysisDiagnostic
}
AnalysisCoverage records how much of the discovered project was analyzed.
type AnalysisDiagnostic ¶ added in v1.30.0
type AnalysisDiagnostic struct {
FilePath string `json:"file_path" yaml:"file_path"`
Code DiagnosticCode `json:"code" yaml:"code"`
Message string `json:"message" yaml:"message"`
}
AnalysisDiagnostic records why a discovered source file was not analyzed.
type AnalysisFailure ¶ added in v1.30.0
type AnalysisFailure struct {
Analysis AnalysisKind `json:"analysis" yaml:"analysis"`
Code AnalysisFailureCode `json:"code" yaml:"code"`
Message string `json:"message" yaml:"message"`
FilePath string `json:"file_path,omitempty" yaml:"file_path,omitempty"`
// contains filtered or unexported fields
}
AnalysisFailure records an analyzer failure independently of project discovery and parsing diagnostics.
func NewAnalysisFailure ¶ added in v1.30.0
func NewAnalysisFailure(analysis AnalysisKind, code AnalysisFailureCode, filePath, message string, cause error) AnalysisFailure
NewAnalysisFailure creates a public typed failure while retaining its underlying cause for in-process error inspection.
func (AnalysisFailure) Error ¶ added in v1.30.0
func (f AnalysisFailure) Error() string
Error implements error without changing the serialized failure contract.
func (AnalysisFailure) Unwrap ¶ added in v1.30.0
func (f AnalysisFailure) Unwrap() error
Unwrap exposes the retained analyzer cause to errors.Is and errors.As.
type AnalysisFailureCode ¶ added in v1.30.0
type AnalysisFailureCode string
AnalysisFailureCode identifies a failure produced while an analyzer runs.
const AnalysisFailureCodeExecution AnalysisFailureCode = "execution_error"
AnalysisFailureCodeExecution identifies an analyzer execution failure.
type AnalysisFailureReporter ¶ added in v1.30.0
type AnalysisFailureReporter interface {
AnalysisFailures() []AnalysisFailure
}
AnalysisFailureReporter is implemented by analysis results and errors that carry typed execution failures.
type AnalysisKind ¶ added in v1.30.0
type AnalysisKind string
AnalysisKind identifies an analyzer in cross-analyzer results.
const ( // AnalysisKindComplexity identifies complexity analysis. AnalysisKindComplexity AnalysisKind = "complexity" // AnalysisKindDeadCode identifies dead-code analysis. AnalysisKindDeadCode AnalysisKind = "deadcode" // AnalysisKindClones identifies clone analysis. AnalysisKindClones AnalysisKind = "clones" // AnalysisKindCBO identifies class-coupling analysis. AnalysisKindCBO AnalysisKind = "cbo" // AnalysisKindLCOM identifies class-cohesion analysis. AnalysisKindLCOM AnalysisKind = "lcom" // AnalysisKindSystem identifies dependency and architecture analysis. AnalysisKindSystem AnalysisKind = "system" // AnalysisKindCommunities identifies module-community analysis. AnalysisKindCommunities AnalysisKind = "communities" // AnalysisKindMockData identifies mock-data analysis. AnalysisKindMockData AnalysisKind = "mockdata" // AnalysisKindDI identifies dependency-injection anti-pattern analysis. AnalysisKindDI AnalysisKind = "di" )
type AnalysisScopeKind ¶ added in v1.30.0
type AnalysisScopeKind string
AnalysisScopeKind identifies the Python execution scope that owns a complexity result. Methods and nested functions are function scopes; class suites are class scopes because Python executes their statements separately while constructing the class object.
const ( AnalysisScopeUnknown AnalysisScopeKind = "" AnalysisScopeModule AnalysisScopeKind = "module" AnalysisScopeFunction AnalysisScopeKind = "function" AnalysisScopeClass AnalysisScopeKind = "class" )
func (AnalysisScopeKind) Validate ¶ added in v1.30.0
func (k AnalysisScopeKind) Validate() error
Validate reports whether the kind names a supported Python execution scope. Analyzer-owned records must never use AnalysisScopeUnknown.
type AnalyzeConfigurationLoader ¶ added in v1.16.0
type AnalyzeConfigurationLoader interface {
LoadAnalyzeExecutionConfig(configPath string, targetPath string) (AnalyzeExecutionConfig, error)
}
AnalyzeConfigurationLoader resolves and loads configuration for AnalyzeUseCase.
type AnalyzeExecutionConfig ¶ added in v1.16.0
type AnalyzeExecutionConfig struct {
ConfigPath string
ProjectRoot string
IncludePatterns []string
ExcludePatterns []string
Recursive bool
ShowDetails bool
ComplexityEnabled bool
ComplexityReportUnchanged bool
ComplexityMinComplexity int
ComplexityLowThreshold int
ComplexityMediumThreshold int
ComplexityMaxComplexity int
CognitiveComplexityThreshold int
NestingDepthThreshold int
FunctionSLOCWarnThreshold int
FunctionSLOCCriticalThreshold int
DeadCodeEnabled bool
CloneLSHEnabled string
CloneLSHAutoThreshold int
SystemEnabled bool
SystemAnalyzeDependencies bool
SystemAnalyzeArchitecture bool
ModuleGraph ModuleGraphOptions
CommunitiesEnabled bool
CommunitiesEnabledExplicit bool
}
AnalyzeExecutionConfig contains the resolved configuration that AnalyzeUseCase needs after config file discovery and loading.
func (AnalyzeExecutionConfig) PythonFileSelection ¶ added in v1.30.0
func (c AnalyzeExecutionConfig) PythonFileSelection() PythonFileSelection
PythonFileSelection returns an owned value for passing the configured source scope across aggregate-analysis boundaries.
type AnalyzeOutputFormatter ¶ added in v1.14.0
type AnalyzeOutputFormatter interface {
Write(response *AnalyzeResponse, format OutputFormat, writer io.Writer) error
}
AnalyzeOutputFormatter defines the interface for formatting unified analysis results
type AnalyzeResponse ¶
type AnalyzeResponse struct {
// Analysis results
Complexity *ComplexityResponse `json:"complexity,omitempty" yaml:"complexity,omitempty"`
DeadCode *DeadCodeResponse `json:"dead_code,omitempty" yaml:"dead_code,omitempty"`
Clone *CloneResponse `json:"clone,omitempty" yaml:"clone,omitempty"`
CBO *CBOResponse `json:"cbo,omitempty" yaml:"cbo,omitempty"`
LCOM *LCOMResponse `json:"lcom,omitempty" yaml:"lcom,omitempty"`
System *SystemAnalysisResponse `json:"system,omitempty" yaml:"system,omitempty"`
Communities *CommunityAnalysisResult `json:"community_analysis,omitempty" yaml:"community_analysis,omitempty"`
MockData *MockDataResponse `json:"mock_data,omitempty" yaml:"mock_data,omitempty"`
// Cross-analysis module quality rollups
ModuleQuality []ModuleQualityMetrics `json:"module_quality,omitempty" yaml:"module_quality,omitempty"`
// Actionable suggestions derived from analysis results
Suggestions []Suggestion `json:"suggestions,omitempty" yaml:"suggestions,omitempty"`
// Project-level read and parse failures, independent of selected analyzers.
Diagnostics []AnalysisDiagnostic `json:"diagnostics,omitempty" yaml:"diagnostics,omitempty"`
// Analyzer execution failures. Partial results remain available when set.
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty"`
// Overall summary
Summary AnalyzeSummary `json:"summary" yaml:"summary"`
// Metadata
SchemaVersion int `json:"schema_version" yaml:"schema_version"`
GeneratedAt time.Time `json:"generated_at" yaml:"generated_at"`
Duration int64 `json:"duration_ms" yaml:"duration_ms"`
Version string `json:"version" yaml:"version"`
}
AnalyzeResponse represents the combined results of all analyses
type AnalyzeSummary ¶
type AnalyzeSummary struct {
// File statistics
TotalFiles int `json:"total_files" yaml:"total_files"`
AnalyzedFiles int `json:"analyzed_files" yaml:"analyzed_files"`
SkippedFiles int `json:"skipped_files" yaml:"skipped_files"`
// Analysis status
ComplexityEnabled bool `json:"complexity_enabled" yaml:"complexity_enabled"`
DeadCodeEnabled bool `json:"dead_code_enabled" yaml:"dead_code_enabled"`
CloneEnabled bool `json:"clone_enabled" yaml:"clone_enabled"`
CBOEnabled bool `json:"cbo_enabled" yaml:"cbo_enabled"`
MockDataEnabled bool `json:"mock_data_enabled" yaml:"mock_data_enabled"`
// System-level (module dependencies & architecture) summary used for scoring
DepsEnabled bool `json:"deps_enabled" yaml:"deps_enabled"`
ArchEnabled bool `json:"arch_enabled" yaml:"arch_enabled"`
CommunitiesEnabled bool `json:"communities_enabled" yaml:"communities_enabled"`
DepsTotalModules int `json:"deps_total_modules" yaml:"deps_total_modules"`
DepsModulesInCycles int `json:"deps_modules_in_cycles" yaml:"deps_modules_in_cycles"`
DepsMaxDepth int `json:"deps_max_depth" yaml:"deps_max_depth"`
DepsMainSequenceDeviation float64 `json:"deps_main_sequence_deviation" yaml:"deps_main_sequence_deviation"`
ArchCompliance float64 `json:"arch_compliance" yaml:"arch_compliance"`
// Community detection metrics used for scoring (populated when CommunitiesEnabled).
CommunityCount int `json:"community_count" yaml:"community_count"`
CommunityModularity float64 `json:"community_modularity" yaml:"community_modularity"`
CommunityBridgeModules int `json:"community_bridge_modules" yaml:"community_bridge_modules"`
CommunityInternalEdges int `json:"community_internal_edges" yaml:"community_internal_edges"`
CommunityCrossEdges int `json:"community_cross_edges" yaml:"community_cross_edges"`
CommunityPackageAlignment *float64 `json:"community_package_alignment,omitempty" yaml:"community_package_alignment,omitempty"`
CommunityLayerAlignment *float64 `json:"community_layer_alignment,omitempty" yaml:"community_layer_alignment,omitempty"`
// Key metrics
// TotalFunctions is the complete analyzed population used for aggregate metrics.
TotalFunctions int `json:"total_functions" yaml:"total_functions"`
// Class-scope fields are reported separately from the established function
// aggregates and do not change health-score semantics.
TotalClassScopes int `json:"total_class_scopes" yaml:"total_class_scopes"`
MaxClassComplexity int `json:"max_class_complexity" yaml:"max_class_complexity"`
MaxClassCognitiveComplexity int `json:"max_class_cognitive_complexity" yaml:"max_class_cognitive_complexity"`
MaxClassNestingDepth int `json:"max_class_nesting_depth" yaml:"max_class_nesting_depth"`
HighComplexityClassScopeCount int `json:"high_complexity_class_scope_count" yaml:"high_complexity_class_scope_count"`
// FunctionsParsed is always equal to TotalFunctions. It is retained only
// for JSON/YAML schema compatibility and will be removed; consumers should
// read TotalFunctions.
FunctionsParsed int `json:"functions_parsed" yaml:"functions_parsed"`
AverageComplexity float64 `json:"average_complexity" yaml:"average_complexity"`
AverageCognitiveComplexity float64 `json:"average_cognitive_complexity" yaml:"average_cognitive_complexity"`
AverageNestingDepth float64 `json:"average_nesting_depth" yaml:"average_nesting_depth"`
HighComplexityCount int `json:"high_complexity_count" yaml:"high_complexity_count"`
DeadCodeCount int `json:"dead_code_count" yaml:"dead_code_count"`
CriticalDeadCode int `json:"critical_dead_code" yaml:"critical_dead_code"`
WarningDeadCode int `json:"warning_dead_code" yaml:"warning_dead_code"`
InfoDeadCode int `json:"info_dead_code" yaml:"info_dead_code"`
TotalClones int `json:"total_clones" yaml:"total_clones"`
ClonePairs int `json:"clone_pairs" yaml:"clone_pairs"`
CloneGroups int `json:"clone_groups" yaml:"clone_groups"`
CodeDuplication float64 `json:"code_duplication_percentage" yaml:"code_duplication_percentage"`
CBOClasses int `json:"cbo_classes" yaml:"cbo_classes"`
HighCouplingClasses int `json:"high_coupling_classes" yaml:"high_coupling_classes"` // CBO > 7 (High Risk)
MediumCouplingClasses int `json:"medium_coupling_classes" yaml:"medium_coupling_classes"` // 3 < CBO ≤ 7 (Medium Risk)
AverageCoupling float64 `json:"average_coupling" yaml:"average_coupling"`
LCOMEnabled bool `json:"lcom_enabled" yaml:"lcom_enabled"`
LCOMClasses int `json:"lcom_classes" yaml:"lcom_classes"`
HighLCOMClasses int `json:"high_lcom_classes" yaml:"high_lcom_classes"` // LCOM4 > 5 (High Risk)
MediumLCOMClasses int `json:"medium_lcom_classes" yaml:"medium_lcom_classes"` // 2 < LCOM4 ≤ 5 (Medium Risk)
AverageLCOM float64 `json:"average_lcom" yaml:"average_lcom"`
MockDataCount int `json:"mock_data_count" yaml:"mock_data_count"`
MockDataErrorCount int `json:"mock_data_error_count" yaml:"mock_data_error_count"`
MockDataWarningCount int `json:"mock_data_warning_count" yaml:"mock_data_warning_count"`
MockDataInfoCount int `json:"mock_data_info_count" yaml:"mock_data_info_count"`
// Overall health score (0-100)
HealthScore int `json:"health_score" yaml:"health_score"`
Grade string `json:"grade" yaml:"grade"` // A, B, C, D, F
// Individual category scores (0-100)
ComplexityScore int `json:"complexity_score" yaml:"complexity_score"`
DeadCodeScore int `json:"dead_code_score" yaml:"dead_code_score"`
DuplicationScore int `json:"duplication_score" yaml:"duplication_score"`
CouplingScore int `json:"coupling_score" yaml:"coupling_score"`
CohesionScore int `json:"cohesion_score" yaml:"cohesion_score"`
DependencyScore int `json:"dependency_score" yaml:"dependency_score"`
ArchitectureScore int `json:"architecture_score" yaml:"architecture_score"`
CommunityScore int `json:"community_score" yaml:"community_score"`
// CommunityRiskScore is a system-level 0-100 risk signal (higher = worse).
// It is the inverse of CommunityScore and only meaningful when communities ran.
CommunityRiskScore int `json:"community_risk_score" yaml:"community_risk_score"`
}
AnalyzeSummary provides an overall summary of all analyses
func (*AnalyzeSummary) CalculateFallbackScore ¶
func (s *AnalyzeSummary) CalculateFallbackScore() int
CalculateFallbackScore provides a simple fallback health score calculation Used when validation fails to provide a basic score based on available metrics
func (*AnalyzeSummary) CalculateHealthScore ¶
func (s *AnalyzeSummary) CalculateHealthScore() error
CalculateHealthScore calculates an overall health score based on analysis results
func (*AnalyzeSummary) HasIssues ¶
func (s *AnalyzeSummary) HasIssues() bool
HasIssues returns true if any issues were found
func (*AnalyzeSummary) IsHealthy ¶
func (s *AnalyzeSummary) IsHealthy() bool
IsHealthy returns true if the codebase is considered healthy
func (*AnalyzeSummary) Validate ¶
func (s *AnalyzeSummary) Validate() error
Validate checks if the summary contains valid values
type ArchitectureAnalysisResult ¶
type ArchitectureAnalysisResult struct {
// Overall architecture compliance
ComplianceScore float64 `json:"compliance_score" yaml:"compliance_score"` // Overall compliance score (0-1, where 1.0 = 100% compliant). Computed as 1 - WeightedViolations/TotalRules (clamped to [0,1]).
TotalViolations int `json:"total_violations" yaml:"total_violations"` // Raw number of violations (one per ArchitectureViolation entry).
WeightedViolations int `json:"weighted_violations" yaml:"weighted_violations"` // Severity-weighted violation count used as the ComplianceScore numerator: error * 5 + warning * 1.
TotalRules int `json:"total_rules" yaml:"total_rules"` // Total number of rule invocations checked (ComplianceScore denominator).
// Layer analysis
LayerAnalysis *LayerAnalysis `json:"layer_analysis" yaml:"layer_analysis"` // Layer violation analysis
CohesionAnalysis *CohesionAnalysis `json:"cohesion_analysis" yaml:"cohesion_analysis"` // Package cohesion analysis
ResponsibilityAnalysis *ResponsibilityAnalysis `json:"responsibility_analysis" yaml:"responsibility_analysis"` // SRP violation analysis
// Detailed violations
Violations []ArchitectureViolation `json:"violations" yaml:"violations"` // All architecture violations
SeverityBreakdown map[ViolationSeverity]int `json:"severity_breakdown" yaml:"severity_breakdown"` // Violations by severity
// Architecture recommendations
Recommendations []ArchitectureRecommendation `json:"recommendations" yaml:"recommendations"` // Specific recommendations
RefactoringTargets []string `json:"refactoring_targets" yaml:"refactoring_targets"` // Modules needing refactoring
}
ArchitectureAnalysisResult contains architecture validation results
type ArchitectureRecommendation ¶
type ArchitectureRecommendation struct {
Type RecommendationType `json:"type" yaml:"type"` // Type of recommendation
Priority RecommendationPriority `json:"priority" yaml:"priority"` // Priority level
Title string `json:"title" yaml:"title"` // Short title
Description string `json:"description" yaml:"description"` // Detailed description
Benefits []string `json:"benefits" yaml:"benefits"` // Expected benefits
Effort EstimatedEffort `json:"effort" yaml:"effort"` // Estimated effort
Modules []string `json:"modules" yaml:"modules"` // Affected modules
Steps []string `json:"steps" yaml:"steps"` // Implementation steps
}
ArchitectureRecommendation represents a specific architecture improvement recommendation
type ArchitectureRules ¶
type ArchitectureRules struct {
// Style is an optional preset name: "layered", "hexagonal", "clean", "mvc".
// When non-empty and Layers/Rules are empty, the service loads the matching
// preset's layers and rules. Empty/"layered" preserves the legacy behavior.
Style string `json:"style" yaml:"style"`
// Layer rules
Layers []Layer `json:"layers" yaml:"layers"`
Rules []LayerRule `json:"rules" yaml:"rules"`
// Package rules
PackageRules []PackageRule `json:"package_rules" yaml:"package_rules"`
// Custom rules
CustomRules []CustomRule `json:"custom_rules" yaml:"custom_rules"`
// Neutral prefixes to strip from module names before layer matching
NeutralPrefixes []string `json:"neutral_prefixes" yaml:"neutral_prefixes"`
// Global settings
StrictMode bool `json:"strict_mode" yaml:"strict_mode"`
AllowedPatterns []string `json:"allowed_patterns" yaml:"allowed_patterns"`
ForbiddenPatterns []string `json:"forbidden_patterns" yaml:"forbidden_patterns"`
}
ArchitectureRules defines architecture validation rules
type ArchitectureViolation ¶
type ArchitectureViolation struct {
Type ViolationType `json:"type" yaml:"type"` // Type of violation
Severity ViolationSeverity `json:"severity" yaml:"severity"` // Severity level
Module string `json:"module" yaml:"module"` // Module involved
Target string `json:"target" yaml:"target"` // Target of violation (if applicable)
Rule string `json:"rule" yaml:"rule"` // Rule that was violated
Description string `json:"description" yaml:"description"` // Human-readable description
Suggestion string `json:"suggestion" yaml:"suggestion"` // Suggested remediation
Location *SourceLocation `json:"location" yaml:"location"` // Location in code (if available)
}
ArchitectureViolation represents an architecture rule violation
type BridgeModule ¶ added in v1.25.0
type BridgeModule struct {
Module string `json:"module" yaml:"module"`
Community string `json:"community" yaml:"community"`
CrossCommunityEdges int `json:"cross_community_edges" yaml:"cross_community_edges"`
TargetCommunities []string `json:"target_communities" yaml:"target_communities"`
}
BridgeModule describes a module that couples multiple communities.
type CBOAnalysisOptions ¶
type CBOAnalysisOptions struct {
// Include system and built-in dependencies
IncludeBuiltins bool
// Maximum depth for dependency resolution
MaxDependencyDepth int
// Exclude patterns for class names
ExcludeClassPatterns []string
// Only analyze public classes (exclude private classes starting with _)
PublicClassesOnly bool
}
CBOAnalysisOptions provides configuration for CBO analysis behavior
type CBOConfigurationLoader ¶
type CBOConfigurationLoader interface {
// LoadConfig loads configuration from the specified path
LoadConfig(path string) (*CBORequest, error)
// LoadDefaultConfig discovers configuration from targetPath (the analyzed
// path) and falls back to built-in defaults when none is found
LoadDefaultConfig(targetPath string) *CBORequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *CBORequest, override *CBORequest) *CBORequest
}
CBOConfigurationLoader defines the interface for loading CBO configuration
type CBOMetrics ¶
type CBOMetrics struct {
// Core CBO metric - number of classes this class depends on
CouplingCount int `json:"coupling_count" yaml:"coupling_count"`
// Breakdown by dependency type
InheritanceDependencies int `json:"inheritance_dependencies" yaml:"inheritance_dependencies"` // Base classes
TypeHintDependencies int `json:"type_hint_dependencies" yaml:"type_hint_dependencies"` // Type annotations
InstantiationDependencies int `json:"instantiation_dependencies" yaml:"instantiation_dependencies"` // Object creation
AttributeAccessDependencies int `json:"attribute_access_dependencies" yaml:"attribute_access_dependencies"` // Method calls and attribute access
ImportDependencies int `json:"import_dependencies" yaml:"import_dependencies"` // Explicitly imported classes
// Dependency details
DependentClasses []string `json:"dependent_classes" yaml:"dependent_classes"` // List of class names this class depends on
}
CBOMetrics represents detailed CBO metrics for a class
type CBOOutputFormatter ¶
type CBOOutputFormatter interface {
// Format formats the analysis response according to the specified format
Format(response *CBOResponse, format OutputFormat) (string, error)
// Write writes the formatted output to the writer
Write(response *CBOResponse, format OutputFormat, writer io.Writer) error
}
CBOOutputFormatter defines the interface for formatting CBO analysis results
type CBORequest ¶
type CBORequest struct {
// Input files or directories to analyze
Paths []string
// Output configuration
OutputFormat OutputFormat
OutputWriter io.Writer
OutputPath string // Path to save output file (for HTML format)
NoOpen bool // Don't auto-open HTML in browser
ShowDetails *bool // nil = unset, non-nil = explicitly set
// Filtering and sorting
MinCBO int
MaxCBO int // 0 means no limit
SortBy SortCriteria
ShowZeros *bool // Include classes with CBO = 0
// CBO thresholds for risk assessment
LowThreshold int // Default: 3 (industry standard)
MediumThreshold int // Default: 7 (industry standard)
// Configuration
ConfigPath string
// Analysis options
Recursive *bool
IncludePatterns []string
ExcludePatterns []string
// Analysis scope
IncludeBuiltins *bool // Include dependencies on built-in types
IncludeImports *bool // Include imported modules in dependency count
GroupNamespaceImports *bool // Collapse alias.Member references to a single alias edge
}
CBORequest represents a request for CBO (Coupling Between Objects) analysis
func DefaultCBORequest ¶
func DefaultCBORequest() *CBORequest
DefaultCBORequest returns a CBORequest with default values Threshold values are sourced from domain/defaults.go
type CBOResponse ¶
type CBOResponse struct {
// Analysis results
Classes []ClassCoupling `json:"classes" yaml:"classes"`
Summary CBOSummary `json:"summary" yaml:"summary"`
// Warnings and issues
Warnings []string `json:"warnings" yaml:"warnings"`
Errors []string `json:"errors" yaml:"errors"`
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty"`
// Metadata
GeneratedAt string `json:"generated_at" yaml:"generated_at"`
Version string `json:"version" yaml:"version"`
Config interface{} `json:"config" yaml:"config"` // Configuration used for analysis
}
CBOResponse represents the complete CBO analysis result
func (*CBOResponse) AnalysisFailures ¶ added in v1.30.0
func (r *CBOResponse) AnalysisFailures() []AnalysisFailure
AnalysisFailures returns CBO failures for aggregate analysis.
type CBOService ¶
type CBOService interface {
// Analyze performs CBO analysis on the given request
Analyze(ctx context.Context, req CBORequest) (*CBOResponse, error)
// AnalyzeFile analyzes a single Python file
AnalyzeFile(ctx context.Context, filePath string, req CBORequest) (*CBOResponse, error)
}
CBOService defines the core business logic for CBO analysis
type CBOSummary ¶
type CBOSummary struct {
TotalClasses int `json:"total_classes" yaml:"total_classes"`
AverageCBO float64 `json:"average_cbo" yaml:"average_cbo"`
MaxCBO int `json:"max_cbo" yaml:"max_cbo"`
MinCBO int `json:"min_cbo" yaml:"min_cbo"`
ClassesAnalyzed int `json:"classes_analyzed" yaml:"classes_analyzed"`
FilesAnalyzed int `json:"files_analyzed" yaml:"files_analyzed"`
// Risk distribution
LowRiskClasses int `json:"low_risk_classes" yaml:"low_risk_classes"`
MediumRiskClasses int `json:"medium_risk_classes" yaml:"medium_risk_classes"`
HighRiskClasses int `json:"high_risk_classes" yaml:"high_risk_classes"`
// CBO distribution
CBODistribution map[string]int `json:"cbo_distribution" yaml:"cbo_distribution"`
// Most coupled classes (top 10)
MostCoupledClasses []ClassCoupling `json:"most_coupled_classes" yaml:"most_coupled_classes"`
// Classes with highest impact (most depended upon)
MostDependedUponClasses []string `json:"most_depended_upon_classes" yaml:"most_depended_upon_classes"`
}
CBOSummary represents aggregate CBO statistics
type CategorizedError ¶
type CategorizedError struct {
Category ErrorCategory
Message string
Original error
}
CategorizedError represents an error with category information
func (*CategorizedError) Error ¶
func (e *CategorizedError) Error() string
Error implements the error interface
type CircularDependency ¶
type CircularDependency struct {
Modules []string `json:"modules" yaml:"modules"` // Modules in the cycle
Dependencies []DependencyPath `json:"dependencies" yaml:"dependencies"` // Dependency paths forming the cycle
Severity CycleSeverity `json:"severity" yaml:"severity"` // Severity level
Size int `json:"size" yaml:"size"` // Number of modules
Description string `json:"description" yaml:"description"` // Human-readable description
}
CircularDependency represents a circular dependency
type CircularDependencyAnalysis ¶
type CircularDependencyAnalysis struct {
HasCircularDependencies bool `json:"has_circular_dependencies" yaml:"has_circular_dependencies"` // True if cycles exist
TotalCycles int `json:"total_cycles" yaml:"total_cycles"` // Number of circular dependencies
TotalModulesInCycles int `json:"total_modules_in_cycles" yaml:"total_modules_in_cycles"` // Number of modules involved in cycles
CircularDependencies []CircularDependency `json:"circular_dependencies" yaml:"circular_dependencies"` // All detected cycles
CycleBreakingSuggestions []string `json:"cycle_breaking_suggestions" yaml:"cycle_breaking_suggestions"` // Suggestions for breaking cycles
CoreInfrastructure []string `json:"core_infrastructure" yaml:"core_infrastructure"` // Modules in multiple cycles
}
CircularDependencyAnalysis contains circular dependency analysis results
type ClassCohesion ¶ added in v1.11.0
type ClassCohesion struct {
// Class identification
Name string `json:"name" yaml:"name"`
FilePath string `json:"file_path" yaml:"file_path"`
StartLine int `json:"start_line" yaml:"start_line"`
EndLine int `json:"end_line" yaml:"end_line"`
// LCOM metrics
Metrics LCOMMetrics `json:"metrics" yaml:"metrics"`
// Risk assessment
RiskLevel RiskLevel `json:"risk_level" yaml:"risk_level"`
}
ClassCohesion represents LCOM analysis result for a single class
type ClassCoupling ¶
type ClassCoupling struct {
// Class identification
Name string `json:"name" yaml:"name"`
FilePath string `json:"file_path" yaml:"file_path"`
StartLine int `json:"start_line" yaml:"start_line"`
EndLine int `json:"end_line" yaml:"end_line"`
// CBO metrics
Metrics CBOMetrics `json:"metrics" yaml:"metrics"`
// Risk assessment
RiskLevel RiskLevel `json:"risk_level" yaml:"risk_level"`
// Additional context
IsAbstract bool `json:"is_abstract" yaml:"is_abstract"`
BaseClasses []string `json:"base_classes" yaml:"base_classes"`
}
ClassCoupling represents CBO analysis result for a single class
type Clone ¶
type Clone struct {
ID int `json:"id" yaml:"id" csv:"id"`
Type CloneType `json:"type" yaml:"type" csv:"type"`
Location *CloneLocation `json:"location" yaml:"location" csv:"location"`
Content string `json:"content,omitempty" yaml:"content,omitempty" csv:"content"`
Hash string `json:"hash" yaml:"hash" csv:"hash"`
Size int `json:"size" yaml:"size" csv:"size"` // Number of AST nodes
LineCount int `json:"line_count" yaml:"line_count" csv:"line_count"`
Complexity int `json:"complexity" yaml:"complexity" csv:"complexity"`
}
Clone represents a detected code clone
type CloneConfigurationLoader ¶
type CloneConfigurationLoader interface {
// LoadCloneConfig loads clone detection configuration from file
LoadCloneConfig(configPath string) (*CloneRequest, error)
// SaveCloneConfig saves clone detection configuration to file
SaveCloneConfig(config *CloneRequest, configPath string) error
// GetDefaultCloneConfig discovers clone configuration from targetPath (the
// analyzed path) and falls back to built-in defaults when none is found
GetDefaultCloneConfig(targetPath string) *CloneRequest
// MergeConfig merges request values over loaded configuration.
MergeConfig(base *CloneRequest, override *CloneRequest) *CloneRequest
}
CloneConfigurationLoader defines the interface for loading clone detection configuration
type CloneGroup ¶
type CloneGroup struct {
ID int `json:"id" yaml:"id" csv:"id"`
Clones []*Clone `json:"clones" yaml:"clones" csv:"clones"`
Type CloneType `json:"type" yaml:"type" csv:"type"`
Similarity float64 `json:"similarity" yaml:"similarity" csv:"similarity"`
Size int `json:"size" yaml:"size" csv:"size"`
}
CloneGroup represents a group of related clones
func (*CloneGroup) AddClone ¶
func (cg *CloneGroup) AddClone(clone *Clone)
AddClone adds a clone to the group
func (*CloneGroup) String ¶
func (cg *CloneGroup) String() string
String returns string representation of CloneGroup
type CloneLocation ¶
type CloneLocation struct {
FilePath string `json:"file_path" yaml:"file_path" csv:"file_path"`
StartLine int `json:"start_line" yaml:"start_line" csv:"start_line"`
EndLine int `json:"end_line" yaml:"end_line" csv:"end_line"`
StartCol int `json:"start_col" yaml:"start_col" csv:"start_col"`
EndCol int `json:"end_col" yaml:"end_col" csv:"end_col"`
}
CloneLocation represents a location of a clone in source code
func (*CloneLocation) LineCount ¶
func (cl *CloneLocation) LineCount() int
LineCount returns the number of lines in this location
func (*CloneLocation) String ¶
func (cl *CloneLocation) String() string
String returns string representation of CloneLocation
type CloneOutputFormatter ¶
type CloneOutputFormatter interface {
// FormatCloneResponse formats a clone response according to the specified format
FormatCloneResponse(response *CloneResponse, format OutputFormat, writer io.Writer) error
// FormatCloneStatistics formats clone statistics
FormatCloneStatistics(stats *CloneStatistics, format OutputFormat, writer io.Writer) error
}
CloneOutputFormatter defines the interface for formatting clone detection results
type ClonePair ¶
type ClonePair struct {
ID int `json:"id" yaml:"id" csv:"id"`
Clone1 *Clone `json:"clone1" yaml:"clone1" csv:"clone1"`
Clone2 *Clone `json:"clone2" yaml:"clone2" csv:"clone2"`
Similarity float64 `json:"similarity" yaml:"similarity" csv:"similarity"`
Distance float64 `json:"distance" yaml:"distance" csv:"distance"`
Type CloneType `json:"type" yaml:"type" csv:"type"`
Confidence float64 `json:"confidence" yaml:"confidence" csv:"confidence"`
}
ClonePair represents a pair of similar code clones
type CloneRequest ¶
type CloneRequest struct {
// Input parameters
Paths []string `json:"paths"`
Recursive *bool `json:"recursive"`
IncludePatterns []string `json:"include_patterns"`
ExcludePatterns []string `json:"exclude_patterns"`
// Analysis configuration
MinLines int `json:"min_lines"`
MinNodes int `json:"min_nodes"`
SimilarityThreshold float64 `json:"similarity_threshold"`
MaxEditDistance float64 `json:"max_edit_distance"`
IgnoreLiterals *bool `json:"ignore_literals"`
IgnoreIdentifiers *bool `json:"ignore_identifiers"`
SkipDocstrings *bool `json:"skip_docstrings"`
// Type-specific thresholds
Type1Threshold float64 `json:"type1_threshold"`
Type2Threshold float64 `json:"type2_threshold"`
Type3Threshold float64 `json:"type3_threshold"`
Type4Threshold float64 `json:"type4_threshold"`
// Advanced analysis options
EnableDFA bool `json:"enable_dfa"` // Enable Data Flow Analysis for enhanced Type-4 detection
// Output configuration
OutputFormat OutputFormat `json:"output_format"`
OutputWriter io.Writer `json:"-"`
OutputPath string `json:"output_path"` // Path to save output file (for HTML format)
NoOpen bool `json:"no_open"` // Don't auto-open HTML in browser
ShowDetails *bool `json:"show_details"`
ShowContent *bool `json:"show_content"`
SortBy SortCriteria `json:"sort_by"`
GroupClones *bool `json:"group_clones"`
// Grouping options
GroupMode string `json:"group_mode"` // connected, star, complete_linkage, k_core
GroupThreshold float64 `json:"group_threshold"` // Minimum similarity for group membership
KCoreK int `json:"k_core_k"` // k-core's k value
// Filtering
MinSimilarity float64 `json:"min_similarity"`
MaxSimilarity float64 `json:"max_similarity"`
CloneTypes []CloneType `json:"clone_types"`
// Configuration file
ConfigPath string `json:"config_path"`
// Performance configuration
Timeout time.Duration `json:"timeout"` // Maximum time for clone analysis (0 = no timeout)
// LSH acceleration (opt-in)
LSHEnabled string `json:"lsh_enabled"` // "auto", "true", "false"
LSHAutoThreshold int `json:"lsh_auto_threshold"` // Auto-enable LSH for N+ fragments
LSHSimilarityThreshold float64 `json:"lsh_similarity_threshold"`
LSHBands int `json:"lsh_bands"`
LSHRows int `json:"lsh_rows"`
LSHHashes int `json:"lsh_hashes"`
}
CloneRequest represents a request for clone detection
func DefaultCloneRequest ¶
func DefaultCloneRequest() *CloneRequest
DefaultCloneRequest returns a default clone request
func (*CloneRequest) HasValidOutputWriter ¶
func (req *CloneRequest) HasValidOutputWriter() bool
HasValidOutputWriter checks if the request has a valid output writer
func (*CloneRequest) ShouldGroupClones ¶
func (req *CloneRequest) ShouldGroupClones() bool
ShouldGroupClones determines if clones should be grouped
func (*CloneRequest) ShouldShowContent ¶
func (req *CloneRequest) ShouldShowContent() bool
ShouldShowContent determines if content should be included in output
func (*CloneRequest) Validate ¶
func (req *CloneRequest) Validate() error
Validate validates a clone request
type CloneResponse ¶
type CloneResponse struct {
// Results
Clones []*Clone `json:"clones" yaml:"clones" csv:"clones"`
ClonePairs []*ClonePair `json:"clone_pairs" yaml:"clone_pairs" csv:"clone_pairs"`
CloneGroups []*CloneGroup `json:"clone_groups" yaml:"clone_groups" csv:"clone_groups"`
Statistics *CloneStatistics `json:"statistics" yaml:"statistics" csv:"statistics"`
// Metadata
Request *CloneRequest `json:"request,omitempty" yaml:"request,omitempty" csv:"-"`
Duration int64 `json:"duration_ms" yaml:"duration_ms" csv:"duration_ms"`
Success bool `json:"success" yaml:"success" csv:"success"`
Error string `json:"error,omitempty" yaml:"error,omitempty" csv:"error"`
// Errors holds per-file failures. Error above reports why the whole run
// failed; a file listed here was skipped while the run itself succeeded,
// so its contents are absent from every statistic in this response.
Errors []string `json:"errors,omitempty" yaml:"errors,omitempty" csv:"-"`
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty" csv:"-"`
}
CloneResponse represents the response from clone detection
func (*CloneResponse) AnalysisFailures ¶ added in v1.30.0
func (r *CloneResponse) AnalysisFailures() []AnalysisFailure
AnalysisFailures returns clone failures for aggregate analysis.
type CloneService ¶
type CloneService interface {
// DetectClones performs clone detection on the given request
DetectClones(ctx context.Context, req *CloneRequest) (*CloneResponse, error)
// DetectClonesInFiles performs clone detection on specific files
DetectClonesInFiles(ctx context.Context, filePaths []string, req *CloneRequest) (*CloneResponse, error)
// ComputeSimilarity computes similarity between two code fragments
ComputeSimilarity(ctx context.Context, fragment1, fragment2 string) (float64, error)
}
CloneService defines the interface for clone detection services
type CloneSortCriteria ¶
type CloneSortCriteria string
CloneSortCriteria defines how to sort clone results
const ( SortClonesByLocation CloneSortCriteria = "location" SortClonesBySimilarity CloneSortCriteria = "similarity" SortClonesBySize CloneSortCriteria = "size" SortClonesByType CloneSortCriteria = "type" SortClonesByConfidence CloneSortCriteria = "confidence" )
type CloneStatistics ¶
type CloneStatistics struct {
TotalFragments int `json:"total_fragments" yaml:"total_fragments" csv:"total_fragments"` // All extracted fragments (functions, classes, etc.)
TotalClones int `json:"total_clones" yaml:"total_clones" csv:"total_clones"` // Fragments detected as clones
TotalClonePairs int `json:"total_clone_pairs" yaml:"total_clone_pairs" csv:"total_clone_pairs"`
TotalCloneGroups int `json:"total_clone_groups" yaml:"total_clone_groups" csv:"total_clone_groups"`
ClonesByType map[string]int `json:"clones_by_type" yaml:"clones_by_type" csv:"clones_by_type"`
AverageSimilarity float64 `json:"average_similarity" yaml:"average_similarity" csv:"average_similarity"`
LinesAnalyzed int `json:"lines_analyzed" yaml:"lines_analyzed" csv:"lines_analyzed"`
NodesAnalyzed int `json:"nodes_analyzed" yaml:"nodes_analyzed" csv:"nodes_analyzed"`
FilesAnalyzed int `json:"files_analyzed" yaml:"files_analyzed" csv:"files_analyzed"`
}
CloneStatistics provides statistics about clone detection results
func NewCloneStatistics ¶
func NewCloneStatistics() *CloneStatistics
NewCloneStatistics creates a new clone statistics instance
type CloneType ¶
type CloneType int
CloneType represents different types of code clones
const ( // Type1Clone - Identical code fragments (except whitespace and comments) Type1Clone CloneType = iota + 1 // Type2Clone - Syntactically identical but with different identifiers/literals Type2Clone // Type3Clone - Syntactically similar with small modifications Type3Clone // Type4Clone - Functionally similar but syntactically different Type4Clone )
type CohesionAnalysis ¶
type CohesionAnalysis struct {
PackageCohesion map[string]float64 `json:"package_cohesion" yaml:"package_cohesion"` // Package -> cohesion score
LowCohesionPackages []string `json:"low_cohesion_packages" yaml:"low_cohesion_packages"` // Packages with low cohesion
CohesionSuggestions map[string]string `json:"cohesion_suggestions" yaml:"cohesion_suggestions"` // Package -> suggestion
}
CohesionAnalysis contains package cohesion analysis
type CommunityAnalysisOutputFormatter ¶ added in v1.25.0
type CommunityAnalysisOutputFormatter interface {
Format(response *CommunityAnalysisResult, format OutputFormat) (string, error)
Write(response *CommunityAnalysisResult, format OutputFormat, writer io.Writer) error
}
CommunityAnalysisOutputFormatter defines the interface for formatting community results.
type CommunityAnalysisRequest ¶ added in v1.25.0
type CommunityAnalysisRequest struct {
// Input files or directories to analyze
Paths []string
// SourcePaths preserves the original user-provided paths before file expansion.
// Used for project-root detection when Paths contains only resolved files.
SourcePaths []string
// Output configuration
OutputFormat OutputFormat
OutputWriter io.Writer
OutputPath string
NoOpen bool
// Configuration
ConfigPath string
ProjectRoot string
Recursive *bool
IncludePatterns []string
ExcludePatterns []string
// Community detection options
Algorithm string
Scope string
MinCommunitySize int
IncludeLazyEdges *bool
ReportBridgeModules *bool
Resolution float64
// Module graph options
IncludeStdLib *bool
IncludeThirdParty *bool
FollowRelative *bool
// ArchitectureRules supplies configured layers for layer mismatch scoring.
// Loaded from config when not set explicitly.
ArchitectureRules *ArchitectureRules
}
CommunityAnalysisRequest represents a request for module community detection.
func DefaultCommunityAnalysisRequest ¶ added in v1.25.0
func DefaultCommunityAnalysisRequest() *CommunityAnalysisRequest
DefaultCommunityAnalysisRequest returns a CommunityAnalysisRequest with default values.
type CommunityAnalysisResult ¶ added in v1.25.0
type CommunityAnalysisResult struct {
Algorithm string `json:"algorithm" yaml:"algorithm"`
Scope string `json:"scope" yaml:"scope"`
TotalCommunities int `json:"total_communities" yaml:"total_communities"`
Modularity float64 `json:"modularity" yaml:"modularity"`
Communities []CommunityMetrics `json:"communities" yaml:"communities"`
BridgeModules []BridgeModule `json:"bridge_modules" yaml:"bridge_modules"`
// Package mismatch metrics compare inferred communities to declared package boundaries.
PackageAlignmentScore *float64 `json:"package_alignment_score,omitempty" yaml:"package_alignment_score,omitempty"`
SplitPackages []string `json:"split_packages,omitempty" yaml:"split_packages,omitempty"`
MixedCommunities []string `json:"mixed_communities,omitempty" yaml:"mixed_communities,omitempty"`
// Layer mismatch metrics compare inferred communities to configured architecture layers.
LayerAlignmentScore *float64 `json:"layer_alignment_score,omitempty" yaml:"layer_alignment_score,omitempty"`
CrossLayerCommunities []string `json:"cross_layer_communities,omitempty" yaml:"cross_layer_communities,omitempty"`
LayerBridgeModules []string `json:"layer_bridge_modules,omitempty" yaml:"layer_bridge_modules,omitempty"`
// RiskScore is a system-level community risk score (0-100, higher = worse),
// populated by ScoreCommunityResult. Nil when fewer than two communities were
// detected (no meaningful modular structure to score).
RiskScore *int `json:"community_risk_score,omitempty" yaml:"community_risk_score,omitempty"`
// ContextMap is a compact, agent-optimized view of the communities (which
// modules to inspect together, which modules bridge clusters). Populated by
// ScoreCommunityResult whenever at least one community was detected.
ContextMap *CommunityContextMap `json:"community_context_map,omitempty" yaml:"community_context_map,omitempty"`
// ModuleDependencies holds directed edges for DOT export and is omitted from JSON/YAML.
ModuleDependencies []CommunityModuleDependency `json:"-" yaml:"-"`
// BridgeModuleCount is the number of detected bridge modules from the
// underlying analysis. It is tracked independently of BridgeModules (which is
// only populated when bridge reporting is enabled) so risk scoring does not
// depend on a presentation option. Omitted from JSON/YAML.
BridgeModuleCount int `json:"-" yaml:"-"`
Warnings []string `json:"warnings,omitempty" yaml:"warnings,omitempty"`
Errors []string `json:"errors,omitempty" yaml:"errors,omitempty"`
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty"`
GeneratedAt string `json:"generated_at" yaml:"generated_at"`
Version string `json:"version" yaml:"version"`
Config interface{} `json:"config,omitempty" yaml:"config,omitempty"`
}
CommunityAnalysisResult represents the complete community analysis output.
func (*CommunityAnalysisResult) AnalysisFailures ¶ added in v1.30.0
func (r *CommunityAnalysisResult) AnalysisFailures() []AnalysisFailure
AnalysisFailures returns community-analysis failures for aggregate analysis.
type CommunityAnalysisService ¶ added in v1.25.0
type CommunityAnalysisService interface {
Analyze(ctx context.Context, req CommunityAnalysisRequest) (*CommunityAnalysisResult, error)
}
CommunityAnalysisService defines the core business logic for community analysis.
type CommunityBundle ¶ added in v1.25.0
type CommunityBundle struct {
CommunityID string `json:"community_id" yaml:"community_id"`
Modules []string `json:"modules" yaml:"modules"`
ModuleCount int `json:"module_count" yaml:"module_count"`
Packages []string `json:"packages" yaml:"packages"`
RiskLevel string `json:"risk_level" yaml:"risk_level"`
BridgeModules []string `json:"bridge_modules" yaml:"bridge_modules"`
SuggestedReviewScope string `json:"suggested_review_scope,omitempty" yaml:"suggested_review_scope,omitempty"`
Summary string `json:"summary" yaml:"summary"`
}
CommunityBundle is a single cluster of modules an agent should review together.
type CommunityConfigurationLoader ¶ added in v1.25.0
type CommunityConfigurationLoader interface {
LoadConfig(path string) (*CommunityAnalysisRequest, error)
LoadDefaultConfig(targetPath string) *CommunityAnalysisRequest
MergeConfig(base *CommunityAnalysisRequest, override *CommunityAnalysisRequest) *CommunityAnalysisRequest
}
CommunityConfigurationLoader defines the interface for loading community configuration.
type CommunityContextMap ¶ added in v1.25.0
type CommunityContextMap struct {
Version int `json:"version" yaml:"version"`
Bundles []CommunityBundle `json:"bundles" yaml:"bundles"`
BridgeModules []ContextBridgeModule `json:"bridge_modules" yaml:"bridge_modules"`
}
CommunityContextMap is a compact, agent-optimized view of the community analysis. It tells AI coding/review agents which modules to inspect together and which modules bridge otherwise-separate clusters. It is derived entirely from CommunityAnalysisResult and carries no LLM-generated content.
func BuildCommunityContextMap ¶ added in v1.25.0
func BuildCommunityContextMap(result *CommunityAnalysisResult) *CommunityContextMap
BuildCommunityContextMap derives a compact, deterministic context map from a scored community analysis result. It returns nil when there is nothing to map (no result or no communities). Call ScoreCommunityResult first so per-community risk levels are populated.
type CommunityMetrics ¶ added in v1.25.0
type CommunityMetrics struct {
ID string `json:"id" yaml:"id"`
Modules []string `json:"modules" yaml:"modules"`
Packages []string `json:"packages" yaml:"packages"`
InternalEdges int `json:"internal_edges" yaml:"internal_edges"`
ExternalEdges int `json:"external_edges" yaml:"external_edges"`
ExternalDependencyRatio float64 `json:"external_dependency_ratio" yaml:"external_dependency_ratio"`
IncomingCrossCommunityEdges int `json:"incoming_cross_community_edges" yaml:"incoming_cross_community_edges"`
OutgoingCrossCommunityEdges int `json:"outgoing_cross_community_edges" yaml:"outgoing_cross_community_edges"`
Size int `json:"size" yaml:"size"`
// Package mismatch metrics (omitted when package metadata is unavailable).
DominantPackage string `json:"dominant_package,omitempty" yaml:"dominant_package,omitempty"`
PackageCount int `json:"package_count,omitempty" yaml:"package_count,omitempty"`
PackageAlignment float64 `json:"package_alignment,omitempty" yaml:"package_alignment,omitempty"`
// Layer mismatch metrics (omitted when architecture layers are not configured).
DominantLayer string `json:"dominant_layer,omitempty" yaml:"dominant_layer,omitempty"`
LayerCount int `json:"layer_count,omitempty" yaml:"layer_count,omitempty"`
Layers []string `json:"layers,omitempty" yaml:"layers,omitempty"`
LayerAlignment *float64 `json:"layer_alignment,omitempty" yaml:"layer_alignment,omitempty"`
// RiskLevel classifies the community as low/medium/high using documented
// thresholds (see docs/ANALYZE_SCORING.md). Populated by ScoreCommunityResult.
RiskLevel string `json:"risk_level,omitempty" yaml:"risk_level,omitempty"`
}
CommunityMetrics describes one detected module community.
type CommunityModuleDependency ¶ added in v1.25.0
CommunityModuleDependency is a directed module dependency edge used for graph export.
type ComplexityMetrics ¶
type ComplexityMetrics struct {
// McCabe cyclomatic complexity
Complexity int `json:"complexity" yaml:"complexity"`
// Cognitive complexity (SonarQube-style)
CognitiveComplexity int `json:"cognitive_complexity" yaml:"cognitive_complexity"`
// CFG metrics
Nodes int `json:"nodes" yaml:"nodes"`
Edges int `json:"edges" yaml:"edges"`
// Nesting depth
NestingDepth int `json:"nesting_depth" yaml:"nesting_depth"`
// Statement counts
IfStatements int `json:"if_statements" yaml:"if_statements"`
LoopStatements int `json:"loop_statements" yaml:"loop_statements"`
ExceptionHandlers int `json:"exception_handlers" yaml:"exception_handlers"`
SwitchCases int `json:"switch_cases" yaml:"switch_cases"`
// SLOC is the source lines of code within this function's line range.
// Computed using the same line-classification logic as raw_metrics.
SLOC int `json:"sloc" yaml:"sloc"`
}
ComplexityMetrics represents detailed complexity metrics for a function
type ComplexityRequest ¶
type ComplexityRequest struct {
// Input files or directories to analyze
Paths []string `json:"paths" yaml:"paths"`
// Output configuration
OutputFormat OutputFormat `json:"output_format" yaml:"output_format"`
OutputWriter io.Writer `json:"-" yaml:"-"`
OutputPath string `json:"output_path" yaml:"output_path"` // Path to save output file (for HTML format)
NoOpen bool `json:"no_open" yaml:"no_open"` // Don't auto-open HTML in browser
ShowDetails *bool `json:"show_details" yaml:"show_details"` // nil = unset, non-nil = explicitly set
// Filtering and sorting
MinComplexity int `json:"min_complexity" yaml:"min_complexity"`
MaxComplexity int `json:"max_complexity" yaml:"max_complexity"` // 0 means no limit
SortBy SortCriteria `json:"sort_by" yaml:"sort_by"`
// Complexity thresholds
LowThreshold int `json:"low_threshold" yaml:"low_threshold"`
MediumThreshold int `json:"medium_threshold" yaml:"medium_threshold"`
CognitiveComplexityThreshold int `json:"cognitive_complexity_threshold" yaml:"cognitive_complexity_threshold"`
NestingDepthThreshold int `json:"nesting_depth_threshold" yaml:"nesting_depth_threshold"`
// Function SLOC thresholds
FunctionSLOCWarnThreshold int `json:"function_sloc_warn_threshold" yaml:"function_sloc_warn_threshold"`
FunctionSLOCCriticalThreshold int `json:"function_sloc_critical_threshold" yaml:"function_sloc_critical_threshold"`
// Analysis toggles loaded from configuration when present.
// Nil means "use the default enabled behavior".
Enabled *bool `json:"enabled" yaml:"enabled"`
ReportUnchanged *bool `json:"report_unchanged" yaml:"report_unchanged"`
// Configuration
ConfigPath string `json:"config_path" yaml:"config_path"`
// Analysis options
Recursive *bool `json:"recursive" yaml:"recursive"` // nil = unset, non-nil = explicitly set
IncludePatterns []string `json:"include_patterns" yaml:"include_patterns"`
ExcludePatterns []string `json:"exclude_patterns" yaml:"exclude_patterns"`
}
ComplexityRequest represents a request for complexity analysis
type ComplexityResponse ¶
type ComplexityResponse struct {
// Functions retains the established module and function population.
Functions []FunctionComplexity `json:"functions" yaml:"functions"`
// ClassScopes is an additive collection of executable class-suite results.
// It uses the same typed metric record without changing function summaries.
ClassScopes []FunctionComplexity `json:"class_scopes,omitempty" yaml:"class_scopes,omitempty"`
ByDirectory DirectoryComplexityMetricsList `json:"by_directory" yaml:"by_directory"`
Summary ComplexitySummary `json:"summary" yaml:"summary"`
// AnalyzedFunctions is the complete population before presentation filters.
// It is consumed by app-level aggregations and is not part of public output.
AnalyzedFunctions []FunctionComplexity `json:"-" yaml:"-"`
// AnalyzedClassScopes is the complete class-suite population before
// presentation filters and is not part of public output.
AnalyzedClassScopes []FunctionComplexity `json:"-" yaml:"-"`
// ModuleRollups are derived before report filters are applied. They are consumed
// by the unified analyze command and are not part of standalone complexity output.
ModuleRollups map[string]ModuleComplexityMetrics `json:"-" yaml:"-"`
// File-level raw code metrics
RawMetrics []RawMetrics `json:"raw_metrics,omitempty" yaml:"raw_metrics,omitempty"`
RawMetricsSummary *RawMetricsSummary `json:"raw_metrics_summary,omitempty" yaml:"raw_metrics_summary,omitempty"`
// Warnings and issues
Warnings []string `json:"warnings" yaml:"warnings"`
Errors []string `json:"errors" yaml:"errors"`
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty"`
// Metadata
GeneratedAt string `json:"generated_at" yaml:"generated_at"`
Version string `json:"version" yaml:"version"`
Config interface{} `json:"config" yaml:"config"` // Configuration used for analysis
Request *ComplexityRequest `json:"request,omitempty"` // Merged configuration request
}
ComplexityResponse represents the complete analysis result
func (*ComplexityResponse) AnalysisFailures ¶ added in v1.30.0
func (r *ComplexityResponse) AnalysisFailures() []AnalysisFailure
AnalysisFailures returns complexity failures for aggregate analysis.
func (*ComplexityResponse) AnalyzedScopes ¶ added in v1.30.0
func (r *ComplexityResponse) AnalyzedScopes() ([]FunctionComplexity, error)
AnalyzedScopes returns an independently owned copy of the complete, pre-filter population. Both collections must be initialized by the analysis producer, including when either population is empty.
func (*ComplexityResponse) ReportedScopes ¶ added in v1.30.0
func (r *ComplexityResponse) ReportedScopes(sortBy SortCriteria) ([]FunctionComplexity, error)
ReportedScopes returns the complete visible execution-scope population in the requested order. The returned slice never aliases response storage.
func (*ComplexityResponse) ReportedScopesByComplexity ¶ added in v1.30.0
func (r *ComplexityResponse) ReportedScopesByComplexity() []FunctionComplexity
ReportedScopesByComplexity returns all visible scopes in a stable severity order for presentation. It never mutates response storage.
func (*ComplexityResponse) ValidateAnalyzedScopes ¶ added in v1.30.0
func (r *ComplexityResponse) ValidateAnalyzedScopes() error
ValidateAnalyzedScopes enforces the producer-owned population contract without allocating a combined result slice.
type ComplexityService ¶
type ComplexityService interface {
// Analyze performs complexity analysis on the given request
Analyze(ctx context.Context, req ComplexityRequest) (*ComplexityResponse, error)
// AnalyzeFile analyzes a single Python file
AnalyzeFile(ctx context.Context, filePath string, req ComplexityRequest) (*ComplexityResponse, error)
}
ComplexityService defines the core business logic for complexity analysis
type ComplexitySummary ¶
type ComplexitySummary struct {
// TotalFunctions is the complete analyzed function population used by all
// aggregate metrics, including the established module pseudo-record.
// Presentation filters only limit ComplexityResponse.Functions.
TotalFunctions int `json:"total_functions" yaml:"total_functions"`
// TotalClassScopes is the complete executable class-suite population.
// Class maxima are published separately and do not alter function aggregates
// or health-score semantics.
TotalClassScopes int `json:"total_class_scopes" yaml:"total_class_scopes"`
MaxClassComplexity int `json:"max_class_complexity" yaml:"max_class_complexity"`
MaxClassCognitiveComplexity int `json:"max_class_cognitive_complexity" yaml:"max_class_cognitive_complexity"`
MaxClassNestingDepth int `json:"max_class_nesting_depth" yaml:"max_class_nesting_depth"`
HighRiskClassScopes int `json:"high_risk_class_scopes" yaml:"high_risk_class_scopes"`
// FunctionsParsed is always equal to TotalFunctions. It is retained only
// for JSON/YAML schema compatibility and will be removed; consumers should
// read TotalFunctions. The displayed subset is len(ComplexityResponse.Functions).
FunctionsParsed int `json:"functions_parsed" yaml:"functions_parsed"`
AverageComplexity float64 `json:"average_complexity" yaml:"average_complexity"`
AverageCognitiveComplexity float64 `json:"average_cognitive_complexity" yaml:"average_cognitive_complexity"`
AverageNestingDepth float64 `json:"average_nesting_depth" yaml:"average_nesting_depth"`
MaxComplexity int `json:"max_complexity" yaml:"max_complexity"`
MinComplexity int `json:"min_complexity" yaml:"min_complexity"`
// FilesAnalyzed is the number of files that were successfully parsed and
// contributed to the metrics above.
FilesAnalyzed int `json:"files_analyzed" yaml:"files_analyzed"`
// TotalFiles is the number of files the request covered, parsed or not.
TotalFiles int `json:"total_files" yaml:"total_files"`
// SkippedFiles is the number of files dropped because they could not be
// read or parsed. Their contents are absent from every metric, so a
// consumer must read this before trusting the aggregates.
SkippedFiles int `json:"skipped_files" yaml:"skipped_files"`
// Risk distribution
LowRiskFunctions int `json:"low_risk_functions" yaml:"low_risk_functions"`
MediumRiskFunctions int `json:"medium_risk_functions" yaml:"medium_risk_functions"`
HighRiskFunctions int `json:"high_risk_functions" yaml:"high_risk_functions"`
// Complexity distribution
ComplexityDistribution map[string]int `json:"complexity_distribution" yaml:"complexity_distribution"`
}
ComplexitySummary represents aggregate function statistics. The established module pseudo-record remains in this population; executable class suites are reported separately and do not alter function counts or averages.
type ConcreteDependencySubtype ¶ added in v1.16.0
type ConcreteDependencySubtype string
ConcreteDependencySubtype represents the subtype of concrete dependency
const ( // ConcreteDepTypeHint indicates type hint with concrete class ConcreteDepTypeHint ConcreteDependencySubtype = "type_hint" // ConcreteDepInstantiation indicates direct instantiation in constructor ConcreteDepInstantiation ConcreteDependencySubtype = "instantiation" )
type ConfigurationLoader ¶
type ConfigurationLoader interface {
// LoadConfig loads configuration from the specified path
LoadConfig(path string) (*ComplexityRequest, error)
// LoadDefaultConfig discovers configuration from targetPath (the analyzed
// path) and falls back to built-in defaults when none is found
LoadDefaultConfig(targetPath string) *ComplexityRequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *ComplexityRequest, override *ComplexityRequest) *ComplexityRequest
}
ConfigurationLoader defines the interface for loading configuration
type ContextBridgeModule ¶ added in v1.25.0
type ContextBridgeModule struct {
Module string `json:"module" yaml:"module"`
Connects []string `json:"connects" yaml:"connects"`
Reason string `json:"reason" yaml:"reason"`
}
ContextBridgeModule is a module that couples two or more communities, surfaced at the top level so agents widen review scope across cluster boundaries.
type CouplingAnalysis ¶
type CouplingAnalysis struct {
// Overall coupling metrics
AverageCoupling float64 `json:"average_coupling" yaml:"average_coupling"` // Average coupling across all modules
CouplingDistribution map[int]int `json:"coupling_distribution" yaml:"coupling_distribution"` // Coupling value -> count
HighlyCoupledModules []string `json:"highly_coupled_modules" yaml:"highly_coupled_modules"` // Modules with high coupling
LooselyCoupledModules []string `json:"loosely_coupled_modules" yaml:"loosely_coupled_modules"` // Modules with low coupling
// Instability analysis
AverageInstability float64 `json:"average_instability" yaml:"average_instability"` // Average instability
StableModules []string `json:"stable_modules" yaml:"stable_modules"` // Low instability modules
InstableModules []string `json:"instable_modules" yaml:"instable_modules"` // High instability modules
// Main sequence analysis
MainSequenceDeviation float64 `json:"main_sequence_deviation" yaml:"main_sequence_deviation"` // Average distance from main sequence
ZoneOfPain []string `json:"zone_of_pain" yaml:"zone_of_pain"` // Stable + concrete modules
ZoneOfUselessness []string `json:"zone_of_uselessness" yaml:"zone_of_uselessness"` // Unstable + abstract modules
MainSequence []string `json:"main_sequence" yaml:"main_sequence"` // Well-positioned modules
}
CouplingAnalysis contains detailed coupling analysis
type CustomRule ¶
type CustomRule struct {
Name string `json:"name" yaml:"name"`
Pattern string `json:"pattern" yaml:"pattern"`
Description string `json:"description" yaml:"description"`
Severity ViolationSeverity `json:"severity" yaml:"severity"`
}
CustomRule defines custom validation rules
type CycleSeverity ¶
type CycleSeverity string
CycleSeverity represents severity of circular dependencies
const ( CycleSeverityLow CycleSeverity = "low" CycleSeverityMedium CycleSeverity = "medium" CycleSeverityHigh CycleSeverity = "high" CycleSeverityCritical CycleSeverity = "critical" )
type DIAntipatternConfigurationLoader ¶ added in v1.16.0
type DIAntipatternConfigurationLoader interface {
// LoadConfig loads configuration from the specified path
LoadConfig(path string) (*DIAntipatternRequest, error)
// LoadDefaultConfig discovers configuration from targetPath (the analyzed
// path) and falls back to built-in defaults when none is found
LoadDefaultConfig(targetPath string) *DIAntipatternRequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *DIAntipatternRequest, override *DIAntipatternRequest) *DIAntipatternRequest
}
DIAntipatternConfigurationLoader defines the interface for loading DI anti-pattern configuration
type DIAntipatternFinding ¶ added in v1.16.0
type DIAntipatternFinding struct {
// Type of the anti-pattern
Type DIAntipatternType `json:"type"`
// Subtype for hidden dependency and concrete dependency patterns
Subtype string `json:"subtype,omitempty"`
// Severity of the finding
Severity DIAntipatternSeverity `json:"severity"`
// Class name where the anti-pattern was found
ClassName string `json:"class_name,omitempty"`
// Method name where the anti-pattern was found
MethodName string `json:"method_name,omitempty"`
// Location in source code
Location SourceLocation `json:"location"`
// Human-readable description of the issue
Description string `json:"description"`
// Suggestion for fixing the issue
Suggestion string `json:"suggestion"`
// Additional details specific to the anti-pattern type
Details map[string]interface{} `json:"details,omitempty"`
}
DIAntipatternFinding represents a single DI anti-pattern detection result
type DIAntipatternOutputFormatter ¶ added in v1.16.0
type DIAntipatternOutputFormatter interface {
// Format formats the analysis response according to the specified format
Format(response *DIAntipatternResponse, format OutputFormat) (string, error)
// Write writes the formatted output to the writer
Write(response *DIAntipatternResponse, format OutputFormat, writer io.Writer) error
}
DIAntipatternOutputFormatter defines the interface for formatting DI anti-pattern analysis results
type DIAntipatternRequest ¶ added in v1.16.0
type DIAntipatternRequest struct {
// Input files or directories to analyze
Paths []string
// Output configuration
OutputFormat OutputFormat
OutputWriter io.Writer
OutputPath string
NoOpen bool
// Analysis options
Recursive *bool
IncludePatterns []string
ExcludePatterns []string
// Configuration
ConfigPath string
// DI-specific options
// ConstructorParamThreshold is the maximum allowed constructor parameters (default: 5)
ConstructorParamThreshold int
// MinSeverity filters findings by minimum severity level
MinSeverity DIAntipatternSeverity
// SortBy specifies the sort order
SortBy SortCriteria
}
DIAntipatternRequest represents a request for DI anti-pattern analysis
func DefaultDIAntipatternRequest ¶ added in v1.16.0
func DefaultDIAntipatternRequest() *DIAntipatternRequest
DefaultDIAntipatternRequest returns a DIAntipatternRequest with default values
func (*DIAntipatternRequest) Validate ¶ added in v1.16.0
func (r *DIAntipatternRequest) Validate() error
Validate validates the request parameters
type DIAntipatternResponse ¶ added in v1.16.0
type DIAntipatternResponse struct {
// Findings contains all detected anti-patterns
Findings []DIAntipatternFinding `json:"findings"`
// Summary contains aggregate statistics
Summary DIAntipatternSummary `json:"summary"`
// Warnings contains non-fatal issues encountered during analysis
Warnings []string `json:"warnings,omitempty"`
// Errors contains errors encountered during analysis
Errors []string `json:"errors,omitempty"`
// Diagnostics contains typed file read and parse failures.
Diagnostics []AnalysisDiagnostic `json:"diagnostics,omitempty"`
// Failures contains DI calculation failures.
Failures []AnalysisFailure `json:"failures,omitempty"`
// Metadata
GeneratedAt string `json:"generated_at"`
Version string `json:"version"`
Config interface{} `json:"config,omitempty"`
}
DIAntipatternResponse represents the complete DI anti-pattern analysis result
type DIAntipatternService ¶ added in v1.16.0
type DIAntipatternService interface {
// Analyze performs DI anti-pattern analysis on the given request
Analyze(ctx context.Context, req DIAntipatternRequest) (*DIAntipatternResponse, error)
// AnalyzeFile analyzes a single Python file
AnalyzeFile(ctx context.Context, filePath string, req DIAntipatternRequest) (*DIAntipatternResponse, error)
}
DIAntipatternService defines the interface for DI anti-pattern analysis
type DIAntipatternSeverity ¶ added in v1.16.0
type DIAntipatternSeverity string
DIAntipatternSeverity represents the severity level of a DI anti-pattern
const ( // DIAntipatternSeverityInfo indicates informational severity DIAntipatternSeverityInfo DIAntipatternSeverity = "info" // DIAntipatternSeverityWarning indicates warning severity DIAntipatternSeverityWarning DIAntipatternSeverity = "warning" // DIAntipatternSeverityError indicates error severity DIAntipatternSeverityError DIAntipatternSeverity = "error" )
func (DIAntipatternSeverity) IsAtLeast ¶ added in v1.16.0
func (s DIAntipatternSeverity) IsAtLeast(other DIAntipatternSeverity) bool
IsAtLeast returns true if this severity is at least as severe as the given level
func (DIAntipatternSeverity) SeverityOrder ¶ added in v1.16.0
func (s DIAntipatternSeverity) SeverityOrder() int
SeverityOrder returns numeric order for severity (higher = more severe)
type DIAntipatternSummary ¶ added in v1.16.0
type DIAntipatternSummary struct {
// TotalFindings is the total number of findings
TotalFindings int `json:"total_findings"`
// ByType breaks down findings by anti-pattern type
ByType map[DIAntipatternType]int `json:"by_type"`
// BySeverity breaks down findings by severity
BySeverity map[DIAntipatternSeverity]int `json:"by_severity"`
// FilesAnalyzed is the number of files analyzed
FilesAnalyzed int `json:"files_analyzed"`
// AffectedClasses is the number of classes with at least one finding
AffectedClasses int `json:"affected_classes"`
}
DIAntipatternSummary represents aggregate statistics for DI anti-pattern analysis
type DIAntipatternType ¶ added in v1.16.0
type DIAntipatternType string
DIAntipatternType represents the type of DI anti-pattern detected
const ( // DIAntipatternConstructorOverInjection indicates too many constructor parameters DIAntipatternConstructorOverInjection DIAntipatternType = "constructor_over_injection" // DIAntipatternHiddenDependency indicates a hidden dependency pattern DIAntipatternHiddenDependency DIAntipatternType = "hidden_dependency" // DIAntipatternConcreteDependency indicates dependency on concrete class DIAntipatternConcreteDependency DIAntipatternType = "concrete_dependency" // DIAntipatternServiceLocator indicates service locator anti-pattern DIAntipatternServiceLocator DIAntipatternType = "service_locator" )
type DeadCodeConfigurationLoader ¶
type DeadCodeConfigurationLoader interface {
// LoadConfig loads dead code configuration from the specified path
LoadConfig(path string) (*DeadCodeRequest, error)
// LoadDefaultConfig discovers configuration from targetPath (the analyzed
// path) and falls back to built-in defaults when none is found
LoadDefaultConfig(targetPath string) *DeadCodeRequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *DeadCodeRequest, override *DeadCodeRequest) *DeadCodeRequest
}
DeadCodeConfigurationLoader defines the interface for loading dead code configuration
type DeadCodeFinding ¶
type DeadCodeFinding struct {
// Location information
Location DeadCodeLocation `json:"location" yaml:"location"`
// Execution-scope context. FunctionName is retained for public compatibility.
FunctionName string `json:"function_name" yaml:"function_name"`
ScopeKind AnalysisScopeKind `json:"scope_kind" yaml:"scope_kind"`
// Dead code details
Code string `json:"code" yaml:"code"`
Reason string `json:"reason" yaml:"reason"`
Severity DeadCodeSeverity `json:"severity" yaml:"severity"`
Description string `json:"description" yaml:"description"`
// Context information (surrounding code)
Context []string `json:"context,omitempty" yaml:"context,omitempty"`
// Metadata
BlockID string `json:"block_id,omitempty" yaml:"block_id,omitempty"`
}
DeadCodeFinding represents a single dead code detection result owned by an explicit Python execution scope.
type DeadCodeFormatter ¶
type DeadCodeFormatter interface {
// Format formats the dead code analysis response according to the specified format
Format(response *DeadCodeResponse, format OutputFormat) (string, error)
// Write writes the formatted dead code output to the writer
Write(response *DeadCodeResponse, format OutputFormat, writer io.Writer) error
// FormatFinding formats a single dead code finding
FormatFinding(finding DeadCodeFinding, format OutputFormat) (string, error)
}
DeadCodeFormatter defines the interface for formatting dead code analysis results
type DeadCodeLocation ¶
type DeadCodeLocation struct {
FilePath string `json:"file_path" yaml:"file_path"`
StartLine int `json:"start_line" yaml:"start_line"`
EndLine int `json:"end_line" yaml:"end_line"`
StartColumn int `json:"start_column" yaml:"start_column"`
EndColumn int `json:"end_column" yaml:"end_column"`
}
DeadCodeLocation represents the location of dead code
type DeadCodeRequest ¶
type DeadCodeRequest struct {
// Input files or directories to analyze
Paths []string `json:"paths" yaml:"paths"`
// Output configuration
OutputFormat OutputFormat `json:"output_format" yaml:"output_format"`
OutputWriter io.Writer `json:"-" yaml:"-"`
OutputPath string `json:"output_path" yaml:"output_path"` // Path to save output file (for HTML format)
NoOpen bool `json:"no_open" yaml:"no_open"` // Don't auto-open HTML in browser
ShowContext *bool `json:"show_context" yaml:"show_context"` // nil = use default (false), non-nil = explicitly set
ContextLines int `json:"context_lines" yaml:"context_lines"` // Number of lines to show around dead code
// Filtering and sorting
MinSeverity DeadCodeSeverity `json:"min_severity" yaml:"min_severity"`
SortBy DeadCodeSortCriteria `json:"sort_by" yaml:"sort_by"`
// Analysis options
Recursive *bool `json:"recursive" yaml:"recursive"` // nil = unset, non-nil = explicitly set
IncludePatterns []string `json:"include_patterns" yaml:"include_patterns"`
ExcludePatterns []string `json:"exclude_patterns" yaml:"exclude_patterns"`
IgnorePatterns []string `json:"ignore_patterns" yaml:"ignore_patterns"` // Patterns for code to ignore (e.g., comments, debug code)
// Configuration
ConfigPath string `json:"config_path" yaml:"config_path"`
// Dead code specific options
DetectAfterReturn *bool `json:"detect_after_return" yaml:"detect_after_return"` // nil = use default (true), non-nil = explicitly set
DetectAfterBreak *bool `json:"detect_after_break" yaml:"detect_after_break"` // nil = use default (true), non-nil = explicitly set
DetectAfterContinue *bool `json:"detect_after_continue" yaml:"detect_after_continue"` // nil = use default (true), non-nil = explicitly set
DetectAfterRaise *bool `json:"detect_after_raise" yaml:"detect_after_raise"` // nil = use default (true), non-nil = explicitly set
DetectUnreachableBranches *bool `json:"detect_unreachable_branches" yaml:"detect_unreachable_branches"` // nil = use default (true), non-nil = explicitly set
}
DeadCodeRequest represents a request for dead code analysis
func DefaultDeadCodeRequest ¶
func DefaultDeadCodeRequest() *DeadCodeRequest
Default configuration values for dead code analysis
func (*DeadCodeRequest) Validate ¶
func (req *DeadCodeRequest) Validate() error
Validate validates the dead code request
type DeadCodeResponse ¶
type DeadCodeResponse struct {
// Analysis results
Files []FileDeadCode `json:"files" yaml:"files"`
Summary DeadCodeSummary `json:"summary" yaml:"summary"`
// ModuleRollups are derived before severity filters are applied. They are consumed
// by the unified analyze command and are not part of standalone dead-code output.
ModuleRollups map[string]ModuleDeadCodeMetrics `json:"-" yaml:"-"`
// Warnings and issues
Warnings []string `json:"warnings" yaml:"warnings"`
Errors []string `json:"errors" yaml:"errors"`
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty"`
// Metadata
GeneratedAt string `json:"generated_at" yaml:"generated_at"`
Version string `json:"version" yaml:"version"`
Config interface{} `json:"config" yaml:"config"` // Configuration used for analysis
Request *DeadCodeRequest `json:"request,omitempty" yaml:"request,omitempty"` // Merged configuration request
}
DeadCodeResponse represents the complete dead code analysis result
func (*DeadCodeResponse) AnalysisFailures ¶ added in v1.30.0
func (r *DeadCodeResponse) AnalysisFailures() []AnalysisFailure
AnalysisFailures returns dead-code failures for aggregate analysis.
type DeadCodeService ¶
type DeadCodeService interface {
// Analyze performs dead code analysis on the given request
Analyze(ctx context.Context, req DeadCodeRequest) (*DeadCodeResponse, error)
// AnalyzeFile analyzes a single Python file for dead code
AnalyzeFile(ctx context.Context, filePath string, req DeadCodeRequest) (*FileDeadCode, error)
// AnalyzeFunction analyzes a single function for dead code
AnalyzeFunction(ctx context.Context, functionCFG interface{}, req DeadCodeRequest) (*FunctionDeadCode, error)
}
DeadCodeService defines the core business logic for dead code analysis
type DeadCodeSeverity ¶
type DeadCodeSeverity string
DeadCodeSeverity represents the severity level of dead code findings
const ( DeadCodeSeverityCritical DeadCodeSeverity = "critical" DeadCodeSeverityWarning DeadCodeSeverity = "warning" DeadCodeSeverityInfo DeadCodeSeverity = "info" )
func (DeadCodeSeverity) IsAtLeast ¶
func (s DeadCodeSeverity) IsAtLeast(minSeverity DeadCodeSeverity) bool
IsAtLeast checks if the severity is at least the specified level
func (DeadCodeSeverity) Level ¶
func (s DeadCodeSeverity) Level() int
SeverityLevel returns the numeric level for comparison
type DeadCodeSortCriteria ¶
type DeadCodeSortCriteria string
DeadCodeSortCriteria represents the criteria for sorting dead code results
const ( DeadCodeSortBySeverity DeadCodeSortCriteria = "severity" DeadCodeSortByLine DeadCodeSortCriteria = "line" DeadCodeSortByFile DeadCodeSortCriteria = "file" DeadCodeSortByFunction DeadCodeSortCriteria = "function" )
type DeadCodeSummary ¶
type DeadCodeSummary struct {
// Overall metrics
TotalFiles int `json:"total_files" yaml:"total_files"`
TotalFunctions int `json:"total_functions" yaml:"total_functions"`
TotalFindings int `json:"total_findings" yaml:"total_findings"`
FilesWithDeadCode int `json:"files_with_dead_code" yaml:"files_with_dead_code"`
FunctionsWithDeadCode int `json:"functions_with_dead_code" yaml:"functions_with_dead_code"`
TotalClassScopes int `json:"total_class_scopes" yaml:"total_class_scopes"`
ClassScopesWithDeadCode int `json:"class_scopes_with_dead_code" yaml:"class_scopes_with_dead_code"`
// Severity distribution
CriticalFindings int `json:"critical_findings" yaml:"critical_findings"`
WarningFindings int `json:"warning_findings" yaml:"warning_findings"`
InfoFindings int `json:"info_findings" yaml:"info_findings"`
// Reason distribution
FindingsByReason map[string]int `json:"findings_by_reason" yaml:"findings_by_reason"`
// Coverage metrics
TotalBlocks int `json:"total_blocks" yaml:"total_blocks"`
DeadBlocks int `json:"dead_blocks" yaml:"dead_blocks"`
OverallDeadRatio float64 `json:"overall_dead_ratio" yaml:"overall_dead_ratio"`
}
DeadCodeSummary represents aggregate statistics for dead code analysis
type DependencyAnalysisResult ¶
type DependencyAnalysisResult struct {
// Dependency graph information
TotalModules int `json:"total_modules" yaml:"total_modules"` // Total number of modules
TotalDependencies int `json:"total_dependencies" yaml:"total_dependencies"` // Total number of dependencies
ResolvedImports int `json:"resolved_imports" yaml:"resolved_imports"` // Internal imports resolved to analyzed modules
UnresolvedImports int `json:"unresolved_imports" yaml:"unresolved_imports"` // Internal imports that could not be resolved
RootModules []string `json:"root_modules" yaml:"root_modules"` // Modules with no dependencies
LeafModules []string `json:"leaf_modules" yaml:"leaf_modules"` // Modules with no dependents
// Dependency metrics
ModuleMetrics map[string]*ModuleDependencyMetrics `json:"module_metrics" yaml:"module_metrics"` // Per-module metrics
DependencyMatrix map[string]map[string]bool `json:"dependency_matrix" yaml:"dependency_matrix"` // Module -> dependencies
// Circular dependency analysis
CircularDependencies *CircularDependencyAnalysis `json:"circular_dependencies" yaml:"circular_dependencies"` // Circular dependency results
// Coupling analysis
CouplingAnalysis *CouplingAnalysis `json:"coupling_analysis" yaml:"coupling_analysis"` // Detailed coupling analysis
// Dependency chains
LongestChains []DependencyPath `json:"longest_chains" yaml:"longest_chains"` // Longest paths through the load-time SCC-condensed dependency graph
MaxDepth int `json:"max_depth" yaml:"max_depth"` // Edges along the chain LongestChains ranks first
}
DependencyAnalysisResult contains module dependency analysis results
type DependencyPath ¶
type DependencyPath struct {
From string `json:"from" yaml:"from"` // Starting module
To string `json:"to" yaml:"to"` // Ending module
Path []string `json:"path" yaml:"path"` // Complete path
Length int `json:"length" yaml:"length"` // Path length
}
DependencyPath represents a path of dependencies
type DiagnosticCode ¶ added in v1.30.0
type DiagnosticCode string
DiagnosticCode identifies a project-level analysis failure category.
const ( // DiagnosticCodeRead identifies a source file that could not be read. DiagnosticCodeRead DiagnosticCode = "read_error" // DiagnosticCodeParse identifies source that could not be parsed. DiagnosticCodeParse DiagnosticCode = "parse_error" )
type DirectoryComplexityMetrics ¶ added in v1.29.0
type DirectoryComplexityMetrics struct {
DirectoryPath string `json:"directory_path" yaml:"directory_path"`
FunctionCount int `json:"function_count" yaml:"function_count"`
AverageComplexity float64 `json:"average_complexity" yaml:"average_complexity"`
MaxComplexity int `json:"max_complexity" yaml:"max_complexity"`
HighRiskFunctionCount int `json:"high_risk_function_count" yaml:"high_risk_function_count"`
AverageNestingDepth float64 `json:"average_nesting_depth" yaml:"average_nesting_depth"`
MaxNestingDepth int `json:"max_nesting_depth" yaml:"max_nesting_depth"`
}
DirectoryComplexityMetrics aggregates the complete analyzed function population for one project-root-relative directory. Presentation filters do not change these metrics, matching the project-wide summary contract.
type DirectoryComplexityMetricsList ¶ added in v1.29.0
type DirectoryComplexityMetricsList []DirectoryComplexityMetrics
DirectoryComplexityMetricsList is the stable serialized collection contract. A zero value is encoded as an empty array so callers never need to distinguish an uninitialized collection from a completed analysis with no reported rows.
func (DirectoryComplexityMetricsList) MarshalJSON ¶ added in v1.29.0
func (metrics DirectoryComplexityMetricsList) MarshalJSON() ([]byte, error)
MarshalJSON encodes an uninitialized collection as an empty JSON array.
func (DirectoryComplexityMetricsList) MarshalYAML ¶ added in v1.29.0
func (metrics DirectoryComplexityMetricsList) MarshalYAML() (interface{}, error)
MarshalYAML encodes an uninitialized collection as an empty YAML array.
type DomainError ¶
DomainError represents errors in the domain layer
func (DomainError) Error ¶
func (e DomainError) Error() string
func (DomainError) Unwrap ¶
func (e DomainError) Unwrap() error
type ErrorCategorizer ¶
type ErrorCategorizer interface {
// Categorize determines the category of an error
Categorize(err error) *CategorizedError
// GetRecoverySuggestions returns recovery suggestions for an error category
GetRecoverySuggestions(category ErrorCategory) []string
}
ErrorCategorizer categorizes errors for better reporting
type ErrorCategory ¶
type ErrorCategory string
ErrorCategory represents the category of an error
const ( ErrorCategoryInput ErrorCategory = "Input Error" ErrorCategoryConfig ErrorCategory = "Configuration Error" ErrorCategoryProcessing ErrorCategory = "Processing Error" ErrorCategoryOutput ErrorCategory = "Output Error" ErrorCategoryTimeout ErrorCategory = "Timeout Error" ErrorCategoryUnknown ErrorCategory = "Unknown Error" )
type EstimatedEffort ¶
type EstimatedEffort string
EstimatedEffort represents estimated implementation effort
const ( EstimatedEffortLow EstimatedEffort = "low" // < 4 hours EstimatedEffortMedium EstimatedEffort = "medium" // 4-16 hours EstimatedEffortHigh EstimatedEffort = "high" // 16-40 hours EstimatedEffortLarge EstimatedEffort = "large" // > 40 hours )
type ExecutableTask ¶
type ExecutableTask interface {
// Name returns the name of the task
Name() string
// Execute runs the task and returns the result
Execute(ctx context.Context) (interface{}, error)
// IsEnabled returns whether the task should be executed
IsEnabled() bool
}
ExecutableTask represents a task that can be executed in parallel
type FileDeadCode ¶
type FileDeadCode struct {
// File identification
FilePath string `json:"file_path" yaml:"file_path"`
// Functions analyzed
Functions []FunctionDeadCode `json:"functions" yaml:"functions"`
// ClassScopes contains executable class-suite results.
ClassScopes []FunctionDeadCode `json:"class_scopes,omitempty" yaml:"class_scopes,omitempty"`
// File-level summary
TotalFindings int `json:"total_findings" yaml:"total_findings"`
TotalFunctions int `json:"total_functions" yaml:"total_functions"`
AffectedFunctions int `json:"affected_functions" yaml:"affected_functions"`
TotalClassScopes int `json:"total_class_scopes" yaml:"total_class_scopes"`
AffectedClassScopes int `json:"affected_class_scopes" yaml:"affected_class_scopes"`
DeadCodeRatio float64 `json:"dead_code_ratio" yaml:"dead_code_ratio"`
}
FileDeadCode represents dead code analysis results for a single file. The historical function collection and counters remain function-only; executable class suites are reported additively with the same typed row model.
func (FileDeadCode) ExecutionScopes ¶ added in v1.30.0
func (f FileDeadCode) ExecutionScopes() []FunctionDeadCode
ExecutionScopes returns an independently owned combined view of the function and executable class-suite results.
type FileMockData ¶ added in v1.7.0
type FileMockData struct {
// File identification
FilePath string `json:"file_path"`
// Findings
Findings []MockDataFinding `json:"findings"`
// File-level summary
TotalFindings int `json:"total_findings"`
ErrorCount int `json:"error_count"`
WarningCount int `json:"warning_count"`
InfoCount int `json:"info_count"`
}
FileMockData represents mock data analysis result for a single file
func (*FileMockData) CalculateSeverityCounts ¶ added in v1.7.0
func (fmd *FileMockData) CalculateSeverityCounts()
CalculateSeverityCounts calculates the count of findings by severity
func (*FileMockData) GetFindingsAtSeverity ¶ added in v1.7.0
func (fmd *FileMockData) GetFindingsAtSeverity(minSeverity MockDataSeverity) []MockDataFinding
GetFindingsAtSeverity returns findings at or above the specified severity level
func (*FileMockData) HasFindings ¶ added in v1.7.0
func (fmd *FileMockData) HasFindings() bool
HasFindings returns true if the file has any mock data findings
func (*FileMockData) HasFindingsAtSeverity ¶ added in v1.7.0
func (fmd *FileMockData) HasFindingsAtSeverity(minSeverity MockDataSeverity) bool
HasFindingsAtSeverity returns true if the file has findings at or above the specified severity
type FileReader ¶
type FileReader interface {
// CollectPythonFiles recursively finds all Python files in the given paths
CollectPythonFiles(paths []string, recursive bool, includePatterns, excludePatterns []string) ([]string, error)
// ReadFile reads the content of a file
ReadFile(path string) ([]byte, error)
// IsValidPythonFile checks if a file is a valid Python file
IsValidPythonFile(path string) bool
// FileExists checks if a file exists and returns an error if not
FileExists(path string) (bool, error)
}
FileReader defines the interface for reading and collecting Python files
type FunctionComplexity ¶
type FunctionComplexity struct {
// Function identification
Name string `json:"name" yaml:"name"`
ScopeKind AnalysisScopeKind `json:"scope_kind" yaml:"scope_kind"`
FilePath string `json:"file_path" yaml:"file_path"`
StartLine int `json:"start_line" yaml:"start_line"`
StartColumn int `json:"start_column" yaml:"start_column"`
EndLine int `json:"end_line" yaml:"end_line"`
// Complexity metrics
Metrics ComplexityMetrics `json:"metrics" yaml:"metrics"`
// Risk assessment
RiskLevel RiskLevel `json:"risk_level" yaml:"risk_level"`
}
FunctionComplexity represents one executable Python scope. The historical type and field names remain part of the public API; ScopeKind distinguishes modules, functions, and class suites without duplicating the result model.
func SortComplexityScopes ¶ added in v1.30.0
func SortComplexityScopes(scopes []FunctionComplexity) []FunctionComplexity
SortComplexityScopes returns an independently owned severity-ranked copy. Ties use source identity so output is deterministic.
func SortComplexityScopesBy ¶ added in v1.30.0
func SortComplexityScopesBy(scopes []FunctionComplexity, sortBy SortCriteria) ([]FunctionComplexity, error)
SortComplexityScopesBy returns an independently owned copy ordered by one of the complexity report's supported criteria. Ties use source identity so independently collected scope kinds still produce deterministic output.
func (FunctionComplexity) ExceedsSLOC ¶ added in v1.29.1
func (f FunctionComplexity) ExceedsSLOC(threshold int) bool
ExceedsSLOC reports whether this function is longer than the given SLOC threshold. Module and class scopes never qualify because this is explicitly a long-function rule. A non-positive threshold disables the check.
func (FunctionComplexity) ScopeLabel ¶ added in v1.30.0
func (f FunctionComplexity) ScopeLabel() string
ScopeLabel returns the canonical user-facing name for an executable scope.
type FunctionDeadCode ¶
type FunctionDeadCode struct {
// Execution-scope identification
Name string `json:"name" yaml:"name"`
ScopeKind AnalysisScopeKind `json:"scope_kind" yaml:"scope_kind"`
FilePath string `json:"file_path" yaml:"file_path"`
// Dead code findings
Findings []DeadCodeFinding `json:"findings" yaml:"findings"`
// Function metrics
TotalBlocks int `json:"total_blocks" yaml:"total_blocks"`
DeadBlocks int `json:"dead_blocks" yaml:"dead_blocks"`
ReachableRatio float64 `json:"reachable_ratio" yaml:"reachable_ratio"`
// Summary by severity
CriticalCount int `json:"critical_count" yaml:"critical_count"`
WarningCount int `json:"warning_count" yaml:"warning_count"`
InfoCount int `json:"info_count" yaml:"info_count"`
}
FunctionDeadCode represents dead code analysis for one execution scope. The historical type and collection names are retained for public compatibility.
func (*FunctionDeadCode) CalculateSeverityCounts ¶
func (fdc *FunctionDeadCode) CalculateSeverityCounts()
CalculateSeverityCounts calculates the count of findings by severity
func (*FunctionDeadCode) GetFindingsAtSeverity ¶
func (fdc *FunctionDeadCode) GetFindingsAtSeverity(minSeverity DeadCodeSeverity) []DeadCodeFinding
GetFindingsAtSeverity returns findings at or above the specified severity level
func (*FunctionDeadCode) HasFindings ¶
func (fdc *FunctionDeadCode) HasFindings() bool
HasFindings returns true if the function has any dead code findings
func (*FunctionDeadCode) HasFindingsAtSeverity ¶
func (fdc *FunctionDeadCode) HasFindingsAtSeverity(minSeverity DeadCodeSeverity) bool
HasFindingsAtSeverity returns true if the function has findings at or above the specified severity
func (FunctionDeadCode) ScopeLabel ¶ added in v1.30.0
func (f FunctionDeadCode) ScopeLabel() string
ScopeLabel returns the canonical user-facing name for this execution scope.
type HiddenDependencySubtype ¶ added in v1.16.0
type HiddenDependencySubtype string
HiddenDependencySubtype represents the subtype of hidden dependency
const ( // HiddenDepGlobal indicates use of global statement HiddenDepGlobal HiddenDependencySubtype = "global_statement" // HiddenDepModuleVariable indicates direct access to module-level variable HiddenDepModuleVariable HiddenDependencySubtype = "module_variable" // HiddenDepSingleton indicates singleton pattern via _instance HiddenDepSingleton HiddenDependencySubtype = "singleton" )
type IssueSeverity ¶
type IssueSeverity string
IssueSeverity represents issue severity
const ( IssueSeverityLow IssueSeverity = "low" IssueSeverityMedium IssueSeverity = "medium" IssueSeverityHigh IssueSeverity = "high" IssueSeverityCritical IssueSeverity = "critical" )
type LCOMConfigurationLoader ¶ added in v1.11.0
type LCOMConfigurationLoader interface {
// LoadConfig loads configuration from the specified path
LoadConfig(path string) (*LCOMRequest, error)
// LoadDefaultConfig discovers configuration from targetPath (the analyzed
// path) and falls back to built-in defaults when none is found
LoadDefaultConfig(targetPath string) *LCOMRequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *LCOMRequest, override *LCOMRequest) *LCOMRequest
}
LCOMConfigurationLoader defines the interface for loading LCOM configuration
type LCOMMetrics ¶ added in v1.11.0
type LCOMMetrics struct {
// Core LCOM4 metric - number of connected components in method-variable graph
LCOM4 int `json:"lcom4" yaml:"lcom4"`
// Method statistics
TotalMethods int `json:"total_methods" yaml:"total_methods"` // All methods in the class
ExcludedMethods int `json:"excluded_methods" yaml:"excluded_methods"` // Methods kept out of the graph (@classmethod, @staticmethod, @abstractmethod, constructors)
// Instance variable statistics
InstanceVariables int `json:"instance_variables" yaml:"instance_variables"` // Distinct self.xxx variables accessed
// Connected component details
MethodGroups [][]string `json:"method_groups" yaml:"method_groups"` // Method names grouped by connected component
}
LCOMMetrics represents detailed LCOM metrics for a class
type LCOMOutputFormatter ¶ added in v1.11.0
type LCOMOutputFormatter interface {
// Format formats the analysis response according to the specified format
Format(response *LCOMResponse, format OutputFormat) (string, error)
// Write writes the formatted output to the writer
Write(response *LCOMResponse, format OutputFormat, writer io.Writer) error
}
LCOMOutputFormatter defines the interface for formatting LCOM analysis results
type LCOMRequest ¶ added in v1.11.0
type LCOMRequest struct {
// Input files or directories to analyze
Paths []string `json:"paths" yaml:"paths"`
// Output configuration
OutputFormat OutputFormat `json:"output_format" yaml:"output_format"`
OutputWriter io.Writer `json:"-" yaml:"-"`
OutputPath string `json:"output_path" yaml:"output_path"` // Path to save output file (for HTML format)
NoOpen bool `json:"no_open" yaml:"no_open"` // Don't auto-open HTML in browser
ShowDetails *bool `json:"show_details" yaml:"show_details"` // nil = unset, non-nil = explicitly set
// Filtering and sorting
MinLCOM int `json:"min_lcom" yaml:"min_lcom"`
MaxLCOM int `json:"max_lcom" yaml:"max_lcom"` // 0 means no limit
SortBy SortCriteria `json:"sort_by" yaml:"sort_by"`
// LCOM thresholds for risk assessment
LowThreshold int `json:"low_threshold" yaml:"low_threshold"` // Default: 2 (LCOM4 <= 2 is low risk)
MediumThreshold int `json:"medium_threshold" yaml:"medium_threshold"` // Default: 5 (LCOM4 3-5 is medium risk)
// Configuration
ConfigPath string `json:"config_path" yaml:"config_path"`
// Analysis options
Recursive *bool `json:"recursive" yaml:"recursive"`
IncludePatterns []string `json:"include_patterns" yaml:"include_patterns"`
ExcludePatterns []string `json:"exclude_patterns" yaml:"exclude_patterns"`
}
LCOMRequest represents a request for LCOM (Lack of Cohesion of Methods) analysis
func DefaultLCOMRequest ¶ added in v1.11.0
func DefaultLCOMRequest() *LCOMRequest
DefaultLCOMRequest returns a LCOMRequest with default values Threshold values are sourced from domain/defaults.go
type LCOMResponse ¶ added in v1.11.0
type LCOMResponse struct {
// Analysis results
Classes []ClassCohesion `json:"classes" yaml:"classes"`
Summary LCOMSummary `json:"summary" yaml:"summary"`
// Warnings and issues
Warnings []string `json:"warnings" yaml:"warnings"`
Errors []string `json:"errors" yaml:"errors"`
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty"`
// Metadata
GeneratedAt string `json:"generated_at" yaml:"generated_at"`
Version string `json:"version" yaml:"version"`
Config interface{} `json:"config" yaml:"config"` // Configuration used for analysis
}
LCOMResponse represents the complete LCOM analysis result
func (*LCOMResponse) AnalysisFailures ¶ added in v1.30.0
func (r *LCOMResponse) AnalysisFailures() []AnalysisFailure
AnalysisFailures returns LCOM failures for aggregate analysis.
type LCOMService ¶ added in v1.11.0
type LCOMService interface {
// Analyze performs LCOM analysis on the given request
Analyze(ctx context.Context, req LCOMRequest) (*LCOMResponse, error)
// AnalyzeFile analyzes a single Python file
AnalyzeFile(ctx context.Context, filePath string, req LCOMRequest) (*LCOMResponse, error)
}
LCOMService defines the core business logic for LCOM analysis
type LCOMSummary ¶ added in v1.11.0
type LCOMSummary struct {
TotalClasses int `json:"total_classes" yaml:"total_classes"`
AverageLCOM float64 `json:"average_lcom" yaml:"average_lcom"`
MaxLCOM int `json:"max_lcom" yaml:"max_lcom"`
MinLCOM int `json:"min_lcom" yaml:"min_lcom"`
ClassesAnalyzed int `json:"classes_analyzed" yaml:"classes_analyzed"`
FilesAnalyzed int `json:"files_analyzed" yaml:"files_analyzed"`
// Risk distribution
LowRiskClasses int `json:"low_risk_classes" yaml:"low_risk_classes"`
MediumRiskClasses int `json:"medium_risk_classes" yaml:"medium_risk_classes"`
HighRiskClasses int `json:"high_risk_classes" yaml:"high_risk_classes"`
// LCOM distribution
LCOMDistribution map[string]int `json:"lcom_distribution" yaml:"lcom_distribution"`
// Least cohesive classes (top 10)
LeastCohesiveClasses []ClassCohesion `json:"least_cohesive_classes" yaml:"least_cohesive_classes"`
}
LCOMSummary represents aggregate LCOM statistics
type Layer ¶
type Layer struct {
Name string `json:"name" yaml:"name"`
Packages []string `json:"packages" yaml:"packages"`
Description string `json:"description" yaml:"description"`
}
Layer defines an architectural layer
type LayerAnalysis ¶
type LayerAnalysis struct {
LayersAnalyzed int `json:"layers_analyzed" yaml:"layers_analyzed"` // Number of layers analyzed
LayerViolations []LayerViolation `json:"layer_violations" yaml:"layer_violations"` // Layer rule violations
LayerCoupling map[string]map[string]int `json:"layer_coupling" yaml:"layer_coupling"` // Layer -> Layer -> dependency count
LayerCohesion map[string]float64 `json:"layer_cohesion" yaml:"layer_cohesion"` // Layer -> cohesion score
ProblematicLayers []string `json:"problematic_layers" yaml:"problematic_layers"` // Layers with violations
}
LayerAnalysis contains layer architecture validation results
type LayerRule ¶
type LayerRule struct {
From string `json:"from" yaml:"from"`
Allow []string `json:"allow" yaml:"allow"`
Deny []string `json:"deny" yaml:"deny"`
// Warn lists target layers that are permitted but discouraged: a dependency
// on one of these emits a warning instead of an error. Used e.g. by the MVC
// preset for view -> model direct access.
Warn []string `json:"warn" yaml:"warn"`
}
LayerRule defines a dependency rule between layers
type LayerViolation ¶
type LayerViolation struct {
FromModule string `json:"from_module" yaml:"from_module"` // Module causing violation
ToModule string `json:"to_module" yaml:"to_module"` // Target module
FromLayer string `json:"from_layer" yaml:"from_layer"` // Source layer
ToLayer string `json:"to_layer" yaml:"to_layer"` // Target layer
Rule string `json:"rule" yaml:"rule"` // Rule that was violated
Severity ViolationSeverity `json:"severity" yaml:"severity"` // Severity of violation
Description string `json:"description" yaml:"description"` // Description of violation
Suggestion string `json:"suggestion" yaml:"suggestion"` // Suggested fix
}
LayerViolation represents a layer architecture rule violation
type MockDataConfigurationLoader ¶ added in v1.7.0
type MockDataConfigurationLoader interface {
// LoadConfig loads mock data configuration from the specified path
LoadConfig(path string) (*MockDataRequest, error)
// LoadDefaultConfig discovers configuration from targetPath (the analyzed
// path) and falls back to built-in defaults when none is found
LoadDefaultConfig(targetPath string) *MockDataRequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *MockDataRequest, override *MockDataRequest) *MockDataRequest
}
MockDataConfigurationLoader defines the interface for loading mock data configuration
type MockDataFinding ¶ added in v1.7.0
type MockDataFinding struct {
// Location information
Location MockDataLocation `json:"location"`
// Mock data details
Value string `json:"value"` // The detected mock value
Type MockDataType `json:"type"` // Type of mock data
Severity MockDataSeverity `json:"severity"`
Description string `json:"description"` // Why this was flagged
Rationale string `json:"rationale"` // Detection rationale
// Context information
Context string `json:"context,omitempty"` // Surrounding code
VariableName string `json:"variable_name,omitempty"` // Variable name if applicable
}
MockDataFinding represents a single mock data detection result
type MockDataFormatter ¶ added in v1.7.0
type MockDataFormatter interface {
// Format formats the mock data analysis response according to the specified format
Format(response *MockDataResponse, format OutputFormat) (string, error)
// Write writes the formatted mock data output to the writer
Write(response *MockDataResponse, format OutputFormat, writer io.Writer) error
}
MockDataFormatter defines the interface for formatting mock data analysis results
type MockDataLocation ¶ added in v1.7.0
type MockDataLocation struct {
FilePath string `json:"file_path"`
StartLine int `json:"start_line"`
EndLine int `json:"end_line"`
StartColumn int `json:"start_column"`
EndColumn int `json:"end_column"`
}
MockDataLocation represents the location of detected mock data
type MockDataRequest ¶ added in v1.7.0
type MockDataRequest struct {
// Input files or directories to analyze
Paths []string
// Output configuration
OutputFormat OutputFormat
OutputWriter io.Writer
OutputPath string // Path to save output file (for HTML format)
NoOpen bool // Don't auto-open HTML in browser
// Filtering and sorting
MinSeverity MockDataSeverity
SortBy MockDataSortCriteria
// Analysis options
Recursive *bool // nil = unset, non-nil = explicitly set
IncludePatterns []string
ExcludePatterns []string
IgnoreTests *bool // nil = use default (true), non-nil = explicitly set
// Configuration
ConfigPath string
// Mock data specific options
Keywords []string // Keywords to detect (mock, fake, dummy, etc.)
Domains []string // Domains to detect (example.com, etc.)
IgnorePatterns []string // Patterns in code to ignore
EnabledTypes []MockDataType // Types of mock data to detect (empty = all)
}
MockDataRequest represents a request for mock data analysis
func DefaultMockDataRequest ¶ added in v1.7.0
func DefaultMockDataRequest() *MockDataRequest
Default configuration values for mock data analysis
func (*MockDataRequest) Validate ¶ added in v1.7.0
func (req *MockDataRequest) Validate() error
Validate validates the mock data request
type MockDataResponse ¶ added in v1.7.0
type MockDataResponse struct {
// Analysis results
Files []FileMockData `json:"files"`
Summary MockDataSummary `json:"summary"`
// Warnings and issues
Warnings []string `json:"warnings"`
Errors []string `json:"errors"`
// Diagnostics contains typed file read and parse failures.
Diagnostics []AnalysisDiagnostic `json:"diagnostics,omitempty"`
// Failures contains detector execution failures.
Failures []AnalysisFailure `json:"failures,omitempty"`
// Metadata
GeneratedAt string `json:"generated_at"`
Version string `json:"version"`
Config interface{} `json:"config"` // Configuration used for analysis
}
MockDataResponse represents the complete mock data analysis result
type MockDataService ¶ added in v1.7.0
type MockDataService interface {
// Analyze performs mock data analysis on the given request
Analyze(ctx context.Context, req MockDataRequest) (*MockDataResponse, error)
// AnalyzeFile analyzes a single Python file for mock data
AnalyzeFile(ctx context.Context, filePath string, req MockDataRequest) (*FileMockData, error)
}
MockDataService defines the core business logic for mock data analysis
type MockDataSeverity ¶ added in v1.7.0
type MockDataSeverity string
MockDataSeverity represents the severity level of mock data findings
const ( MockDataSeverityError MockDataSeverity = "error" MockDataSeverityWarning MockDataSeverity = "warning" MockDataSeverityInfo MockDataSeverity = "info" )
func (MockDataSeverity) IsAtLeast ¶ added in v1.7.0
func (s MockDataSeverity) IsAtLeast(minSeverity MockDataSeverity) bool
IsAtLeast checks if the severity is at least the specified level
func (MockDataSeverity) Level ¶ added in v1.7.0
func (s MockDataSeverity) Level() int
Level returns the numeric level for comparison
type MockDataSortCriteria ¶ added in v1.7.0
type MockDataSortCriteria string
MockDataSortCriteria represents the criteria for sorting mock data results
const ( MockDataSortBySeverity MockDataSortCriteria = "severity" MockDataSortByLine MockDataSortCriteria = "line" MockDataSortByFile MockDataSortCriteria = "file" MockDataSortByType MockDataSortCriteria = "type" )
type MockDataSummary ¶ added in v1.7.0
type MockDataSummary struct {
// Overall metrics
TotalFiles int `json:"total_files"`
TotalFindings int `json:"total_findings"`
FilesWithMockData int `json:"files_with_mock_data"`
// Severity distribution
ErrorFindings int `json:"error_findings"`
WarningFindings int `json:"warning_findings"`
InfoFindings int `json:"info_findings"`
// Type distribution
FindingsByType map[MockDataType]int `json:"findings_by_type"`
}
MockDataSummary represents aggregate statistics for mock data analysis
func (*MockDataSummary) CalculateTypeCounts ¶ added in v1.7.0
func (s *MockDataSummary) CalculateTypeCounts(files []FileMockData)
CalculateTypeCounts calculates the count of findings by type
type MockDataType ¶ added in v1.7.0
type MockDataType string
MockDataType represents the type of mock data detected
const ( MockDataTypeKeyword MockDataType = "keyword" // mock, fake, dummy, etc. MockDataTypeDomain MockDataType = "domain" // example.com, test.com, etc. MockDataTypeEmail MockDataType = "email" // test@example.com, etc. MockDataTypePhone MockDataType = "phone" // 000-0000-0000, etc. MockDataTypeUUID MockDataType = "uuid" // low-entropy UUIDs MockDataTypePlaceholder MockDataType = "placeholder" // TODO, FIXME, XXX, etc. MockDataTypeRepetitive MockDataType = "repetitive" // aaaa, 1111, etc. MockDataTypeTestCredential MockDataType = "test_credential" // password123, secret, etc. )
type ModuleComplexityMetrics ¶ added in v1.29.0
type ModuleComplexityMetrics struct {
AnalyzedFunctionCount int `json:"analyzed_function_count" yaml:"analyzed_function_count"`
AverageComplexity float64 `json:"average_complexity" yaml:"average_complexity"`
AverageCognitiveComplexity float64 `json:"average_cognitive_complexity" yaml:"average_cognitive_complexity"`
MaxComplexity int `json:"max_complexity" yaml:"max_complexity"`
HighRiskFunctionCount int `json:"high_risk_function_count" yaml:"high_risk_function_count"`
ExceptionHandlerCount int `json:"exception_handler_count" yaml:"exception_handler_count"`
}
ModuleComplexityMetrics is the canonical module-level function-complexity contract. The <module> pseudo-record and executable class suites are excluded.
type ModuleDeadCodeMetrics ¶ added in v1.29.0
type ModuleDeadCodeMetrics struct {
DeadCodeFindingCount int `json:"dead_code_finding_count" yaml:"dead_code_finding_count"`
DeadCodeBlockCount int `json:"dead_code_block_count" yaml:"dead_code_block_count"`
}
ModuleDeadCodeMetrics is the canonical module-level dead-code contract. Both counts describe findings enabled by detector options before severity filtering.
type ModuleDependencyMetrics ¶
type ModuleDependencyMetrics struct {
// Basic information
ModuleName string `json:"module_name" yaml:"module_name"` // Module name
Package string `json:"package" yaml:"package"` // Package name
FilePath string `json:"file_path" yaml:"file_path"` // File path
IsPackage bool `json:"is_package" yaml:"is_package"` // True if this is a package
// Size metrics
LinesOfCode int `json:"lines_of_code" yaml:"lines_of_code"` // Total lines of code
FunctionCount int `json:"function_count" yaml:"function_count"` // Number of functions
ClassCount int `json:"class_count" yaml:"class_count"` // Number of classes
AbstractClassCount int `json:"abstract_class_count" yaml:"abstract_class_count"` // Number of abstract classes
PublicInterface []string `json:"public_interface" yaml:"public_interface"` // Public names exported
// Coupling metrics (Robert Martin's metrics)
AfferentCoupling int `json:"afferent_coupling" yaml:"afferent_coupling"` // Ca - modules that depend on this one
EfferentCoupling int `json:"efferent_coupling" yaml:"efferent_coupling"` // Ce - modules this one depends on
Instability float64 `json:"instability" yaml:"instability"` // I = Ce / (Ca + Ce)
Abstractness float64 `json:"abstractness" yaml:"abstractness"` // A - abstractness measure
Distance float64 `json:"distance" yaml:"distance"` // D - distance from main sequence
// Quality metrics
Maintainability float64 `json:"maintainability" yaml:"maintainability"` // Maintainability index (0-100)
TechnicalDebt float64 `json:"technical_debt" yaml:"technical_debt"` // Estimated technical debt in hours
RiskLevel RiskLevel `json:"risk_level" yaml:"risk_level"` // Overall risk assessment
// Dependencies
DirectDependencies []string `json:"direct_dependencies" yaml:"direct_dependencies"` // Modules this directly depends on
TransitiveDependencies []string `json:"transitive_dependencies" yaml:"transitive_dependencies"` // All transitive dependencies
Dependents []string `json:"dependents" yaml:"dependents"` // Modules that depend on this one
}
ModuleDependencyMetrics contains dependency metrics for a single module
type ModuleGraphOptions ¶ added in v1.30.0
ModuleGraphOptions is the resolved module graph policy shared by graph consumers during one analysis execution.
type ModuleQualityMetrics ¶ added in v1.29.0
type ModuleQualityMetrics struct {
ModuleName string `json:"module_name,omitempty" yaml:"module_name,omitempty"`
FilePath string `json:"file_path" yaml:"file_path"`
LinesOfCode int `json:"lines_of_code" yaml:"lines_of_code"`
FunctionCount int `json:"function_count" yaml:"function_count"`
ModuleComplexityMetrics `yaml:",inline"`
ModuleDeadCodeMetrics `yaml:",inline"`
}
ModuleQualityMetrics is the public per-file view assembled by unified analysis.
type OutputFormat ¶
type OutputFormat string
OutputFormat represents the supported output formats
const ( OutputFormatText OutputFormat = "text" OutputFormatJSON OutputFormat = "json" OutputFormatYAML OutputFormat = "yaml" OutputFormatCSV OutputFormat = "csv" OutputFormatHTML OutputFormat = "html" OutputFormatDOT OutputFormat = "dot" )
type OutputFormatter ¶
type OutputFormatter interface {
// Format formats the analysis response according to the specified format
Format(response *ComplexityResponse, format OutputFormat) (string, error)
// Write writes the formatted output to the writer
Write(response *ComplexityResponse, format OutputFormat, writer io.Writer) error
}
OutputFormatter defines the interface for formatting analysis results
type PackageRule ¶
type PackageRule struct {
Package string `json:"package" yaml:"package"`
MaxSize int `json:"max_size" yaml:"max_size"`
MaxCoupling int `json:"max_coupling" yaml:"max_coupling"`
MinCohesion float64 `json:"min_cohesion" yaml:"min_cohesion"`
AllowedDependencies []string `json:"allowed_dependencies" yaml:"allowed_dependencies"`
}
PackageRule defines rules for packages
type ParallelExecutor ¶
type ParallelExecutor interface {
// Execute runs tasks in parallel with the given configuration
Execute(ctx context.Context, tasks []ExecutableTask) error
// SetMaxConcurrency sets the maximum number of concurrent tasks
SetMaxConcurrency(max int)
// SetTimeout sets the timeout for all tasks
SetTimeout(timeout time.Duration)
}
ParallelExecutor manages parallel execution of tasks
type ProgressManager ¶
type ProgressManager interface {
// Initialize sets up progress tracking with the maximum value
Initialize(maxValue int)
// Start starts the progress bar
Start()
// Complete marks the progress as completed
Complete(success bool)
// Update updates the progress
Update(processed, total int)
// SetWriter sets the output writer for progress bars
SetWriter(writer io.Writer)
// IsInteractive returns true if progress bars should be shown
IsInteractive() bool
// Close cleans up any resources
Close()
}
ProgressManager manages progress tracking for analysis
type PythonFileSelection ¶ added in v1.30.0
PythonFileSelection is the canonical configured source-file scope for one aggregate analysis execution.
func (PythonFileSelection) ForModules ¶ added in v1.30.0
func (s PythonFileSelection) ForModules() PythonFileSelection
ForModules expands implementation-file rules to cover matching stub modules without broadening their configured directory scope.
type RawMetrics ¶ added in v1.15.0
type RawMetrics struct {
FilePath string `json:"file_path" yaml:"file_path"`
SLOC int `json:"sloc" yaml:"sloc"`
LLOC int `json:"lloc" yaml:"lloc"`
CommentLines int `json:"comment_lines" yaml:"comment_lines"`
DocstringLines int `json:"docstring_lines" yaml:"docstring_lines"`
BlankLines int `json:"blank_lines" yaml:"blank_lines"`
TotalLines int `json:"total_lines" yaml:"total_lines"`
CommentRatio float64 `json:"comment_ratio" yaml:"comment_ratio"`
}
RawMetrics represents file-level raw code metrics.
type RawMetricsSummary ¶ added in v1.15.0
type RawMetricsSummary struct {
FilesAnalyzed int `json:"files_analyzed" yaml:"files_analyzed"`
SLOC int `json:"sloc" yaml:"sloc"`
LLOC int `json:"lloc" yaml:"lloc"`
CommentLines int `json:"comment_lines" yaml:"comment_lines"`
DocstringLines int `json:"docstring_lines" yaml:"docstring_lines"`
BlankLines int `json:"blank_lines" yaml:"blank_lines"`
TotalLines int `json:"total_lines" yaml:"total_lines"`
CommentRatio float64 `json:"comment_ratio" yaml:"comment_ratio"`
}
RawMetricsSummary represents aggregated raw code metrics across files.
type RecommendationCategory ¶
type RecommendationCategory string
RecommendationCategory represents recommendation category
const ( RecommendationCategoryArchitecture RecommendationCategory = "architecture" RecommendationCategoryRefactoring RecommendationCategory = "refactoring" RecommendationCategoryTesting RecommendationCategory = "testing" RecommendationCategoryDocumentation RecommendationCategory = "documentation" RecommendationCategoryProcess RecommendationCategory = "process" )
type RecommendationPriority ¶
type RecommendationPriority string
RecommendationPriority represents priority level
const ( RecommendationPriorityLow RecommendationPriority = "low" RecommendationPriorityMedium RecommendationPriority = "medium" RecommendationPriorityHigh RecommendationPriority = "high" RecommendationPriorityCritical RecommendationPriority = "critical" )
type RecommendationType ¶
type RecommendationType string
RecommendationType represents the type of recommendation
const ( RecommendationTypeRefactor RecommendationType = "refactor" // Code refactoring RecommendationTypeRestructure RecommendationType = "restructure" // Architectural restructuring RecommendationTypeExtract RecommendationType = "extract" // Extract module/package RecommendationTypeMerge RecommendationType = "merge" // Merge modules RecommendationTypeInterface RecommendationType = "interface" // Add abstraction )
type ReportWriter ¶
type ReportWriter interface {
// Write writes formatted content using the provided writeFunc.
// - If outputPath is non-empty, implementations should create/truncate the file
// at that path and pass the file as the writer to writeFunc.
// - If outputPath is empty, implementations should pass the provided writer to writeFunc.
// Implementations may emit user-facing status messages (e.g., file paths) and
// optionally open HTML outputs in a browser when format is OutputFormatHTML and noOpen is false.
Write(writer io.Writer, outputPath string, format OutputFormat, noOpen bool, writeFunc func(io.Writer) error) error
}
ReportWriter abstracts writing reports to a destination (file or writer) and handling side-effects like opening HTML reports in a browser.
Implementations live in the service layer.
type ResponsibilityAnalysis ¶
type ResponsibilityAnalysis struct {
SRPViolations []SRPViolation `json:"srp_violations" yaml:"srp_violations"` // SRP violations detected
ModuleResponsibilities map[string][]string `json:"module_responsibilities" yaml:"module_responsibilities"` // Module -> responsibilities
OverloadedModules []string `json:"overloaded_modules" yaml:"overloaded_modules"` // Modules with too many responsibilities
}
ResponsibilityAnalysis contains Single Responsibility Principle analysis
type SRPViolation ¶
type SRPViolation struct {
Module string `json:"module" yaml:"module"` // Module with violation
Responsibilities []string `json:"responsibilities" yaml:"responsibilities"` // Multiple responsibilities detected
Severity ViolationSeverity `json:"severity" yaml:"severity"` // Severity level
Suggestion string `json:"suggestion" yaml:"suggestion"` // Refactoring suggestion
}
SRPViolation represents a Single Responsibility Principle violation
type SortCriteria ¶
type SortCriteria string
SortCriteria represents the criteria for sorting results
const ( SortByComplexity SortCriteria = "complexity" SortByName SortCriteria = "name" SortByRisk SortCriteria = "risk" SortBySimilarity SortCriteria = "similarity" SortBySize SortCriteria = "size" SortByLocation SortCriteria = "location" SortByCoupling SortCriteria = "coupling" // For CBO metrics SortBySeverity SortCriteria = "severity" // For anti-pattern findings SortByCohesion SortCriteria = "cohesion" // For LCOM metrics )
type SourceLocation ¶
type SourceLocation struct {
FilePath string `json:"file_path" yaml:"file_path"`
StartLine int `json:"start_line" yaml:"start_line"`
EndLine int `json:"end_line" yaml:"end_line"`
StartCol int `json:"start_col" yaml:"start_col"`
EndCol int `json:"end_col" yaml:"end_col"`
}
SourceLocation represents a location in source code
func (*SourceLocation) LineCount ¶
func (sl *SourceLocation) LineCount() int
LineCount returns the number of lines in this location
func (*SourceLocation) String ¶
func (sl *SourceLocation) String() string
String returns string representation of SourceLocation
type Suggestion ¶ added in v1.12.0
type Suggestion struct {
Category SuggestionCategory `json:"category"`
Severity SuggestionSeverity `json:"severity"`
Effort SuggestionEffort `json:"effort"`
Title string `json:"title"`
Description string `json:"description"`
Steps []string `json:"steps,omitempty"`
FilePath string `json:"file_path,omitempty"`
Function string `json:"function,omitempty"`
ClassName string `json:"class_name,omitempty"`
StartLine int `json:"start_line,omitempty"`
MetricValue string `json:"metric_value,omitempty"`
Threshold string `json:"threshold,omitempty"`
}
Suggestion represents an actionable improvement suggestion derived from analysis results
func GenerateSuggestions ¶ added in v1.12.0
func GenerateSuggestions(response *AnalyzeResponse) []Suggestion
GenerateSuggestions derives actionable suggestions from AnalyzeResponse. Suggestions are sorted by priority: severity (critical > warning > info) then effort (easy first).
func (Suggestion) SeverityIcon ¶ added in v1.12.0
func (s Suggestion) SeverityIcon() string
SeverityIcon returns an emoji icon for the suggestion severity
type SuggestionCategory ¶ added in v1.12.0
type SuggestionCategory string
SuggestionCategory represents the analysis category of a suggestion
const ( SuggestionCategoryComplexity SuggestionCategory = "complexity" SuggestionCategoryDeadCode SuggestionCategory = "dead_code" SuggestionCategoryClone SuggestionCategory = "clone" SuggestionCategoryCoupling SuggestionCategory = "coupling" SuggestionCategoryCohesion SuggestionCategory = "cohesion" SuggestionCategoryDependency SuggestionCategory = "dependency" SuggestionCategoryArchitecture SuggestionCategory = "architecture" )
type SuggestionEffort ¶ added in v1.12.0
type SuggestionEffort string
SuggestionEffort represents the estimated effort to address a suggestion
const ( SuggestionEffortEasy SuggestionEffort = "easy" SuggestionEffortModerate SuggestionEffort = "moderate" SuggestionEffortHard SuggestionEffort = "hard" )
type SuggestionSeverity ¶ added in v1.12.0
type SuggestionSeverity string
SuggestionSeverity represents the importance of a suggestion
const ( SuggestionSeverityCritical SuggestionSeverity = "critical" SuggestionSeverityWarning SuggestionSeverity = "warning" SuggestionSeverityInfo SuggestionSeverity = "info" )
type SystemAnalysisConfigurationLoader ¶
type SystemAnalysisConfigurationLoader interface {
// LoadConfig loads configuration from the specified path
LoadConfig(path string) (*SystemAnalysisRequest, error)
// LoadDefaultConfig discovers configuration from targetPath (the analyzed
// path) and falls back to built-in defaults when none is found
LoadDefaultConfig(targetPath string) *SystemAnalysisRequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *SystemAnalysisRequest, override *SystemAnalysisRequest) *SystemAnalysisRequest
}
SystemAnalysisConfigurationLoader defines configuration loading interface
type SystemAnalysisOutputFormatter ¶
type SystemAnalysisOutputFormatter interface {
// Format formats the analysis response according to the specified format
Format(response *SystemAnalysisResponse, format OutputFormat) (string, error)
// Write writes the formatted output to the writer
Write(response *SystemAnalysisResponse, format OutputFormat, writer io.Writer) error
}
SystemAnalysisOutputFormatter defines formatting interface
type SystemAnalysisRequest ¶
type SystemAnalysisRequest struct {
// Input files or directories to analyze
Paths []string
// ProjectRoot overrides automatic project-root inference when set.
ProjectRoot string
// Output configuration
OutputFormat OutputFormat
OutputWriter io.Writer
OutputPath string // Path to save output file
NoOpen bool // Don't auto-open HTML in browser
// Analysis scope
AnalyzeDependencies *bool // Enable dependency analysis
AnalyzeArchitecture *bool // Enable architecture validation
// Configuration
ConfigPath string
Recursive *bool
IncludePatterns []string
ExcludePatterns []string
// Analysis options
IncludeStdLib *bool // Include standard library dependencies
IncludeThirdParty *bool // Include third-party dependencies
FollowRelative *bool // Follow relative imports
DetectCycles *bool // Detect circular dependencies
ValidateArchitecture *bool // Validate architecture rules
ValidateCohesion *bool // Validate package cohesion
ValidateResponsibility *bool // Validate single responsibility boundaries
MinCohesion float64 // Minimum acceptable package cohesion
MaxResponsibilities int // Maximum inferred responsibilities per module
CohesionViolationSeverity ViolationSeverity // Severity for package cohesion violations
ResponsibilityViolationSeverity ViolationSeverity // Severity for SRP violations
// Architecture rules (loaded from config or specified directly)
ArchitectureRules *ArchitectureRules
// Integration with other analyses
ComplexityData map[string]int // Module -> average complexity
ClonesData map[string]float64 // Module -> duplication ratio
DeadCodeData map[string]int // Module -> dead code lines
}
SystemAnalysisRequest represents a request for comprehensive system-level analysis
func DefaultSystemAnalysisRequest ¶
func DefaultSystemAnalysisRequest() *SystemAnalysisRequest
DefaultSystemAnalysisRequest returns a SystemAnalysisRequest with default values
type SystemAnalysisResponse ¶
type SystemAnalysisResponse struct {
// Core analysis results
DependencyAnalysis *DependencyAnalysisResult `json:"dependency_analysis" yaml:"dependency_analysis"` // Module dependency analysis
ArchitectureAnalysis *ArchitectureAnalysisResult `json:"architecture_analysis" yaml:"architecture_analysis"` // Architecture validation results
// Summary information
Summary SystemAnalysisSummary `json:"summary" yaml:"summary"` // High-level summary
// Issues and recommendations
Issues []SystemIssue `json:"issues" yaml:"issues"` // Critical issues found
Recommendations []SystemRecommendation `json:"recommendations" yaml:"recommendations"` // Improvement recommendations
Warnings []string `json:"warnings" yaml:"warnings"` // Analysis warnings
Errors []string `json:"errors" yaml:"errors"` // Analysis errors
Failures []AnalysisFailure `json:"failures,omitempty" yaml:"failures,omitempty"`
// Metadata
GeneratedAt time.Time `json:"generated_at" yaml:"generated_at"` // When the analysis was generated
Duration int64 `json:"duration" yaml:"duration"` // Analysis duration in milliseconds
Version string `json:"version" yaml:"version"` // Tool version
Config interface{} `json:"config" yaml:"config"` // Configuration used for analysis
}
SystemAnalysisResponse represents the complete system analysis result
func (*SystemAnalysisResponse) AnalysisFailures ¶ added in v1.30.0
func (r *SystemAnalysisResponse) AnalysisFailures() []AnalysisFailure
AnalysisFailures returns system-analysis failures for aggregate analysis.
type SystemAnalysisService ¶
type SystemAnalysisService interface {
// Analyze performs comprehensive system analysis
Analyze(ctx context.Context, req SystemAnalysisRequest) (*SystemAnalysisResponse, error)
// AnalyzeDependencies performs dependency analysis only
AnalyzeDependencies(ctx context.Context, req SystemAnalysisRequest) (*DependencyAnalysisResult, error)
// AnalyzeArchitecture performs architecture validation only
AnalyzeArchitecture(ctx context.Context, req SystemAnalysisRequest) (*ArchitectureAnalysisResult, error)
}
SystemAnalysisService defines the core business logic for system analysis
type SystemAnalysisSummary ¶
type SystemAnalysisSummary struct {
// System overview
TotalModules int `json:"total_modules" yaml:"total_modules"` // Total number of modules analyzed
TotalPackages int `json:"total_packages" yaml:"total_packages"` // Total number of packages
TotalDependencies int `json:"total_dependencies" yaml:"total_dependencies"` // Total dependency relationships
ProjectRoot string `json:"project_root" yaml:"project_root"` // Project root directory
ResolvedImports int `json:"resolved_imports" yaml:"resolved_imports"` // Internal imports resolved to analyzed modules
UnresolvedImports int `json:"unresolved_imports" yaml:"unresolved_imports"` // Internal imports that could not be resolved
// Quality scores (0-100, higher is better)
OverallQualityScore float64 `json:"overall_quality_score" yaml:"overall_quality_score"` // Composite quality score
MaintainabilityScore float64 `json:"maintainability_score" yaml:"maintainability_score"` // Average maintainability index
ArchitectureScore float64 `json:"architecture_score" yaml:"architecture_score"` // Architecture compliance score
ModularityScore float64 `json:"modularity_score" yaml:"modularity_score"` // System modularity score
TechnicalDebtHours float64 `json:"technical_debt_hours" yaml:"technical_debt_hours"` // Total estimated technical debt
// Key metrics
AverageCoupling float64 `json:"average_coupling" yaml:"average_coupling"` // Average module coupling
AverageInstability float64 `json:"average_instability" yaml:"average_instability"` // Average instability
CyclicDependencies int `json:"cyclic_dependencies" yaml:"cyclic_dependencies"` // Number of modules in cycles
ArchitectureViolations int `json:"architecture_violations" yaml:"architecture_violations"` // Number of architecture rule violations
HighRiskModules int `json:"high_risk_modules" yaml:"high_risk_modules"` // Number of high-risk modules
// Recommendations summary
CriticalIssues int `json:"critical_issues" yaml:"critical_issues"` // Number of critical issues requiring immediate attention
RefactoringCandidates int `json:"refactoring_candidates" yaml:"refactoring_candidates"` // Number of modules needing refactoring
ArchitectureImprovements int `json:"architecture_improvements" yaml:"architecture_improvements"` // Number of architecture improvements suggested
}
SystemAnalysisSummary provides a high-level overview of system quality
type SystemIssue ¶
type SystemIssue struct {
Type IssueType `json:"type" yaml:"type"` // Type of issue
Severity IssueSeverity `json:"severity" yaml:"severity"` // Severity level
Title string `json:"title" yaml:"title"` // Issue title
Description string `json:"description" yaml:"description"` // Detailed description
Impact string `json:"impact" yaml:"impact"` // Impact description
Modules []string `json:"modules" yaml:"modules"` // Affected modules
Suggestion string `json:"suggestion" yaml:"suggestion"` // Remediation suggestion
}
SystemIssue represents a critical system-level issue
type SystemRecommendation ¶
type SystemRecommendation struct {
Category RecommendationCategory `json:"category" yaml:"category"` // Category of recommendation
Priority RecommendationPriority `json:"priority" yaml:"priority"` // Priority level
Title string `json:"title" yaml:"title"` // Recommendation title
Description string `json:"description" yaml:"description"` // Detailed description
Rationale string `json:"rationale" yaml:"rationale"` // Why this is recommended
Benefits []string `json:"benefits" yaml:"benefits"` // Expected benefits
Steps []string `json:"steps" yaml:"steps"` // Implementation steps
Resources []string `json:"resources" yaml:"resources"` // Additional resources
Effort EstimatedEffort `json:"effort" yaml:"effort"` // Estimated effort
}
SystemRecommendation represents a system-level improvement recommendation
type ViolationSeverity ¶
type ViolationSeverity string
ViolationSeverity represents the severity of a violation
const ( ViolationSeverityInfo ViolationSeverity = "info" ViolationSeverityWarning ViolationSeverity = "warning" ViolationSeverityError ViolationSeverity = "error" ViolationSeverityCritical ViolationSeverity = "critical" )
type ViolationType ¶
type ViolationType string
ViolationType represents the type of architecture violation
const ( ViolationTypeLayer ViolationType = "layer" // Layer dependency violation ViolationTypeCycle ViolationType = "cycle" // Circular dependency ViolationTypeCoupling ViolationType = "coupling" // Excessive coupling ViolationTypeResponsibility ViolationType = "responsibility" // SRP violation ViolationTypeCohesion ViolationType = "cohesion" // Low cohesion )