Documentation
¶
Index ¶
- Constants
- Variables
- func BoolPtr(b bool) *bool
- func BoolValue(b *bool, defaultVal bool) bool
- 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 ShouldUseLSH(lshEnabled string, fragmentCount int, autoThreshold int) bool
- func ShouldUseLSHWithPairEstimate(lshEnabled string, fragmentCount int, autoThreshold int, pairThreshold int) bool
- type AnalyzeResponse
- type AnalyzeSummary
- type ArchitectureAnalysisResult
- type ArchitectureRecommendation
- type ArchitectureRules
- type ArchitectureViolation
- type CBOAnalysisOptions
- type CBOConfigurationLoader
- type CBOMetrics
- type CBOOutputFormatter
- type CBORequest
- type CBOResponse
- type CBOService
- type CBOSummary
- type CategorizedError
- type CheckResult
- type CheckSummary
- type CheckViolation
- type CircularDependency
- type CircularDependencyAnalysis
- 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 ComplexityMetrics
- type ComplexityRequest
- type ComplexityResponse
- type ComplexityService
- type ComplexitySummary
- type ConfigurationLoader
- type CouplingAnalysis
- type CustomRule
- type CycleSeverity
- type DeadCodeConfigurationLoader
- type DeadCodeFinding
- type DeadCodeFormatter
- type DeadCodeLocation
- type DeadCodeRequest
- type DeadCodeResponse
- type DeadCodeService
- type DeadCodeSeverity
- type DeadCodeSortCriteria
- type DeadCodeSummary
- type DependencyAnalysisResult
- type DependencyEdge
- type DependencyEdgeType
- type DependencyGraph
- func (g *DependencyGraph) AddEdge(edge *DependencyEdge)
- func (g *DependencyGraph) AddNode(node *ModuleNode)
- func (g *DependencyGraph) EdgeCount() int
- func (g *DependencyGraph) GetAllNodeIDs() []string
- func (g *DependencyGraph) GetIncomingEdges(nodeID string) []*DependencyEdge
- func (g *DependencyGraph) GetNode(id string) *ModuleNode
- func (g *DependencyGraph) GetOutgoingEdges(nodeID string) []*DependencyEdge
- func (g *DependencyGraph) NodeCount() int
- func (g *DependencyGraph) UpdateNodeFlags()
- type DependencyGraphRequest
- type DependencyGraphResponse
- type DependencyPath
- type DomainError
- type ErrorCategorizer
- type ErrorCategory
- type EstimatedEffort
- type ExecutableTask
- type Export
- type ExportSpecifier
- type FileDeadCode
- type FileReader
- type FunctionComplexity
- type FunctionDeadCode
- type Import
- type ImportSpecifier
- type ImportType
- type IssueSeverity
- type IssueType
- type JSFileReader
- type Layer
- type LayerAnalysis
- type LayerRule
- type LayerViolation
- type ModuleAnalysisRequest
- type ModuleAnalysisResponse
- type ModuleAnalysisResult
- type ModuleAnalysisSummary
- type ModuleDependency
- type ModuleDependencyMetrics
- type ModuleInfo
- type ModuleNode
- type ModuleType
- type OutputFormat
- type OutputFormatter
- type PackageRule
- type ParallelExecutor
- type ProgressManager
- type RecommendationCategory
- type RecommendationPriority
- type RecommendationType
- type ReportWriter
- type ResponsibilityAnalysis
- type RiskLevel
- type SRPViolation
- type SortCriteria
- type SourceLocation
- type SystemAnalysisConfigurationLoader
- type SystemAnalysisOutputFormatter
- type SystemAnalysisRequest
- type SystemAnalysisResponse
- type SystemAnalysisService
- type SystemAnalysisSummary
- type SystemIssue
- type SystemRecommendation
- type TaskProgress
- type ViolationSeverity
- type ViolationType
Constants ¶
const ( // Complexity thresholds and penalties ComplexityThresholdHigh = 20 ComplexityThresholdMedium = 10 ComplexityThresholdLow = 5 ComplexityPenaltyHigh = 20 ComplexityPenaltyMedium = 12 ComplexityPenaltyLow = 6 // Code duplication thresholds and penalties // 0% = perfect, 30% = max penalty (using fragment ratio: clonedFragments/totalFragments) DuplicationThresholdHigh = 30.0 DuplicationThresholdMedium = 15.0 DuplicationThresholdLow = 0.0 DuplicationPenaltyHigh = 20 DuplicationPenaltyMedium = 12 DuplicationPenaltyLow = 6 // 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 = 0.3 // Medium-risk classes count 0.3 vs High = 1.0 CouplingSaturationRatio = 0.40 // weighted ratio at which the penalty maxes out // Maximum penalties MaxDeadCodePenalty = 20 MaxCriticalPenalty = 10 MaxCyclesPenalty = 10 // Increased from 8 for stricter scoring MaxDepthPenalty = 3 // Increased from 2 for stricter scoring MaxArchPenalty = 12 // Increased from 8 for stricter scoring MaxMSDPenalty = 3 // Increased from 2 for stricter scoring // Score display scale - all categories normalized to this base MaxScoreBase = 20 // Actual maximum penalty values for normalization MaxDependencyPenalty = MaxCyclesPenalty + MaxDepthPenalty + MaxMSDPenalty // 16 MaxArchitecturePenalty = MaxArchPenalty // 12 // Grade thresholds (stricter than before) GradeAThreshold = 90 // Increased from 85 GradeBThreshold = 75 // Increased from 70 GradeCThreshold = 60 // Increased from 55 GradeDThreshold = 45 // Increased from 40 // Score quality thresholds (aligned with grade thresholds) ScoreThresholdExcellent = 90 // Excellent: 90-100 (increased from 85) ScoreThresholdGood = 75 // Good: 75-89 (increased from 70) ScoreThresholdFair = 60 // Fair: 60-74 (increased from 55) // Other constants MinimumScore = 0 // Changed from 10 to allow truly low scores for severely problematic code HealthyThreshold = 70 FallbackComplexityThreshold = 10 FallbackPenalty = 5 )
Health Score Calculation Constants
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 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 signal that this is not a real function defined in the source.
Variables ¶
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 BoolPtr ¶
BoolPtr creates a pointer to a boolean value This is useful for creating pointer boolean values inline
func BoolValue ¶
BoolValue safely dereferences a boolean pointer, returning defaultVal if nil This allows safe access to pointer booleans with explicit defaults
func GetGradeFromScore ¶
GetGradeFromScore maps a health score to a letter grade
func NewAnalysisError ¶
NewAnalysisError creates an analysis error
func NewCancelledError ¶ added in v0.7.0
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 v0.7.0
NewInternalError creates an internal error
func NewInvalidInputError ¶
NewInvalidInputError creates an invalid input error
func NewNotImplementedError ¶ added in v0.7.0
NewNotImplementedError creates a not implemented error
func NewOutputError ¶
NewOutputError creates an output error
func NewParseError ¶
NewParseError creates a parse error
func NewTimeoutError ¶ added in v0.7.0
NewTimeoutError creates a timeout error
func NewUnsupportedFormatError ¶
NewUnsupportedFormatError creates an unsupported format error
func NewValidationError ¶
NewValidationError creates a validation error
func ShouldUseLSH ¶
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 v0.7.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.
Types ¶
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"`
System *SystemAnalysisResponse `json:"system,omitempty" yaml:"system,omitempty"`
// Overall summary
Summary AnalyzeSummary `json:"summary" yaml:"summary"`
// Metadata
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"`
// 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"`
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"`
// Key metrics
TotalFunctions int `json:"total_functions" yaml:"total_functions"`
AverageComplexity float64 `json:"average_complexity" yaml:"average_complexity"`
HighComplexityCount int `json:"high_complexity_count" yaml:"high_complexity_count"`
MediumComplexityCount int `json:"medium_complexity_count" yaml:"medium_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"`
// 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"`
DependencyScore int `json:"dependency_score" yaml:"dependency_score"`
ArchitectureScore int `json:"architecture_score" yaml:"architecture_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 // Overall compliance score (0-1, where 1.0 = 100% compliant). Computed as 1 - WeightedViolations/TotalRules (clamped to [0,1]).
TotalViolations int // Raw number of violations (one per ArchitectureViolation entry).
WeightedViolations int // Severity-weighted violation count used as the ComplianceScore numerator: error * 5 + warning * 1.
TotalRules int // Total number of rule invocations checked (ComplianceScore denominator).
// Layer analysis
LayerAnalysis *LayerAnalysis // Layer violation analysis
CohesionAnalysis *CohesionAnalysis // Package cohesion analysis
ResponsibilityAnalysis *ResponsibilityAnalysis // SRP violation analysis
// Detailed violations
Violations []ArchitectureViolation // All architecture violations
SeverityBreakdown map[ViolationSeverity]int // Violations by severity
// Architecture recommendations
Recommendations []ArchitectureRecommendation // Specific recommendations
RefactoringTargets []string // Modules needing refactoring
}
ArchitectureAnalysisResult contains architecture validation results
type ArchitectureRecommendation ¶
type ArchitectureRecommendation struct {
Type RecommendationType // Type of recommendation
Priority RecommendationPriority // Priority level
Title string // Short title
Description string // Detailed description
Benefits []string // Expected benefits
Effort EstimatedEffort // Estimated effort
Modules []string // Affected modules
Steps []string // Implementation steps
}
ArchitectureRecommendation represents a specific architecture improvement recommendation
type ArchitectureRules ¶
type ArchitectureRules struct {
// 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"`
// 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 // Type of violation
Severity ViolationSeverity // Severity level
Module string // Module involved
Target string // Target of violation (if applicable)
Rule string // Rule that was violated
Description string // Human-readable description
Suggestion string // Suggested remediation
Location *SourceLocation // Location in code (if available)
}
ArchitectureViolation represents an architecture rule violation
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 loads the default configuration
LoadDefaultConfig() *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
// Breakdown by dependency type
InheritanceDependencies int // Base classes
TypeHintDependencies int // Type annotations
InstantiationDependencies int // Object creation
AttributeAccessDependencies int // Method calls and attribute access
ImportDependencies int // Explicitly imported classes
// Dependency details
DependentClasses []string // 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
// 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
}
CBORequest represents a request for CBO (Coupling Between Objects) analysis
func DefaultCBORequest ¶
func DefaultCBORequest() *CBORequest
DefaultCBORequest returns a CBORequest with default values
type CBOResponse ¶
type CBOResponse struct {
// Analysis results
Classes []ClassCoupling
Summary CBOSummary
// Warnings and issues
Warnings []string
Errors []string
// Metadata
GeneratedAt string
Version string
Config interface{} // Configuration used for analysis
}
CBOResponse represents the complete CBO analysis result
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 JavaScript/TypeScript 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
AverageCBO float64
MaxCBO int
MinCBO int
ClassesAnalyzed int
FilesAnalyzed int
// Risk distribution
LowRiskClasses int
MediumRiskClasses int
HighRiskClasses int
// CBO distribution
CBODistribution map[string]int
// Most coupled classes (top 10)
MostCoupledClasses []ClassCoupling
// Classes with highest impact (most depended upon)
MostDependedUponClasses []string
}
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 CheckResult ¶
type CheckResult struct {
Passed bool `json:"passed"`
ExitCode int `json:"exit_code"`
Violations []CheckViolation `json:"violations"`
Summary CheckSummary `json:"summary"`
Duration int64 `json:"duration_ms"`
GeneratedAt string `json:"generated_at"`
Version string `json:"version"`
}
CheckResult represents the result of a quality check
type CheckSummary ¶
type CheckSummary struct {
FilesAnalyzed int `json:"files_analyzed"`
TotalViolations int `json:"total_violations"`
ComplexityChecked bool `json:"complexity_checked"`
DeadCodeChecked bool `json:"deadcode_checked"`
DepsChecked bool `json:"deps_checked"`
HighComplexityFunctions int `json:"high_complexity_functions"`
DeadCodeFindings int `json:"dead_code_findings"`
CircularDependencies int `json:"circular_dependencies"`
}
CheckSummary provides aggregate statistics
type CheckViolation ¶
type CheckViolation struct {
Category string `json:"category"` // complexity, deadcode, deps
Rule string `json:"rule"` // max-complexity, no-dead-code, etc.
Severity string `json:"severity"` // error, warning
Message string `json:"message"` // Human-readable description
Location string `json:"location,omitempty"` // File:line if applicable
Actual string `json:"actual"` // Actual value
Threshold string `json:"threshold,omitempty"` // Configured threshold
}
CheckViolation represents a single threshold violation
type CircularDependency ¶
type CircularDependency struct {
Modules []string // Modules in the cycle
Dependencies []DependencyPath // Dependency paths forming the cycle
Severity CycleSeverity // Severity level
Size int // Number of modules
Description string // Human-readable description
}
CircularDependency represents a circular dependency
type CircularDependencyAnalysis ¶
type CircularDependencyAnalysis struct {
HasCircularDependencies bool // True if cycles exist
TotalCycles int // Number of circular dependencies
TotalModulesInCycles int // Number of modules involved in cycles
CircularDependencies []CircularDependency // All detected cycles
CycleBreakingSuggestions []string // Suggestions for breaking cycles
CoreInfrastructure []string // Modules in multiple cycles
}
CircularDependencyAnalysis contains circular dependency analysis results
type ClassCoupling ¶
type ClassCoupling struct {
// Class identification
Name string
FilePath string
StartLine int
EndLine int
// CBO metrics
Metrics CBOMetrics
// Risk assessment
RiskLevel RiskLevel
// Additional context
IsAbstract bool
BaseClasses []string
}
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 returns default clone detection configuration
GetDefaultCloneConfig() *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"`
// Type-specific thresholds
Type1Threshold float64 `json:"type1_threshold"`
Type2Threshold float64 `json:"type2_threshold"`
Type3Threshold float64 `json:"type3_threshold"`
Type4Threshold float64 `json:"type4_threshold"`
// 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"`
}
CloneResponse represents the response from clone detection
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 // Package -> cohesion score
LowCohesionPackages []string // Packages with low cohesion
CohesionSuggestions map[string]string // Package -> suggestion
}
CohesionAnalysis contains package cohesion analysis
type ComplexityMetrics ¶
type ComplexityMetrics struct {
// McCabe cyclomatic complexity
Complexity int `json:"complexity" yaml:"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"`
}
ComplexityMetrics represents detailed complexity metrics for a function
type ComplexityRequest ¶
type ComplexityRequest 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
// Filtering and sorting
MinComplexity int
MaxComplexity int // 0 means no limit
SortBy SortCriteria
// Complexity thresholds
LowThreshold int
MediumThreshold int
// Configuration
ConfigPath string
// Analysis options
Recursive bool
IncludePatterns []string
ExcludePatterns []string
}
ComplexityRequest represents a request for complexity analysis
type ComplexityResponse ¶
type ComplexityResponse struct {
// Analysis results
Functions []FunctionComplexity `json:"functions" yaml:"functions"`
Summary ComplexitySummary `json:"summary" yaml:"summary"`
// Warnings and issues
Warnings []string `json:"warnings,omitempty" yaml:"warnings,omitempty"`
Errors []string `json:"errors,omitempty" yaml:"errors,omitempty"`
// Metadata
GeneratedAt string `json:"generated_at" yaml:"generated_at"`
Version string `json:"version" yaml:"version"`
Config interface{} `json:"config,omitempty" yaml:"config,omitempty"` // Configuration used for analysis
}
ComplexityResponse represents the complete analysis result
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 JavaScript/TypeScript 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 int `json:"total_functions" yaml:"total_functions"`
AverageComplexity float64 `json:"average_complexity" yaml:"average_complexity"`
MaxComplexity int `json:"max_complexity" yaml:"max_complexity"`
MinComplexity int `json:"min_complexity" yaml:"min_complexity"`
FilesAnalyzed int `json:"files_analyzed" yaml:"files_analyzed"`
// 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,omitempty" yaml:"complexity_distribution,omitempty"`
}
ComplexitySummary represents aggregate statistics
type ConfigurationLoader ¶
type ConfigurationLoader interface {
// LoadConfig loads configuration from the specified path
LoadConfig(path string) (*ComplexityRequest, error)
// LoadDefaultConfig loads the default configuration
LoadDefaultConfig() *ComplexityRequest
// MergeConfig merges CLI flags with configuration file
MergeConfig(base *ComplexityRequest, override *ComplexityRequest) *ComplexityRequest
}
ConfigurationLoader defines the interface for loading configuration
type CouplingAnalysis ¶
type CouplingAnalysis struct {
// Overall coupling metrics
AverageCoupling float64 // Average coupling across all modules
CouplingDistribution map[int]int // Coupling value -> count
HighlyCoupledModules []string // Modules with high coupling
LooselyCoupledModules []string // Modules with low coupling
// Instability analysis
AverageInstability float64 // Average instability
StableModules []string // Low instability modules
InstableModules []string // High instability modules
// Main sequence analysis
MainSequenceDeviation float64 // Average distance from main sequence
ZoneOfPain []string // Stable + concrete modules
ZoneOfUselessness []string // Unstable + abstract modules
MainSequence []string // 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 DeadCodeConfigurationLoader ¶
type DeadCodeConfigurationLoader interface {
// LoadConfig loads dead code configuration from the specified path
LoadConfig(path string) (*DeadCodeRequest, error)
// LoadDefaultConfig loads the default dead code configuration
LoadDefaultConfig() *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"`
// Function context
FunctionName string `json:"function_name"`
// Dead code details
Code string `json:"code"`
Reason string `json:"reason"`
Severity DeadCodeSeverity `json:"severity"`
Description string `json:"description"`
// Context information (surrounding code)
Context []string `json:"context,omitempty"`
// Metadata
BlockID string `json:"block_id,omitempty"`
}
DeadCodeFinding represents a single dead code detection result
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"`
StartLine int `json:"start_line"`
EndLine int `json:"end_line"`
StartColumn int `json:"start_column"`
EndColumn int `json:"end_column"`
}
DeadCodeLocation represents the location of dead code
type DeadCodeRequest ¶
type DeadCodeRequest 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
ShowContext *bool // nil = use default (false), non-nil = explicitly set
ContextLines int // Number of lines to show around dead code
// Filtering and sorting
MinSeverity DeadCodeSeverity
SortBy DeadCodeSortCriteria
// Analysis options
Recursive bool
IncludePatterns []string
ExcludePatterns []string
IgnorePatterns []string // Patterns for code to ignore (e.g., comments, debug code)
// Configuration
ConfigPath string
// Dead code specific options
DetectAfterReturn *bool // nil = use default (true), non-nil = explicitly set
DetectAfterBreak *bool // nil = use default (true), non-nil = explicitly set
DetectAfterContinue *bool // nil = use default (true), non-nil = explicitly set
DetectAfterThrow *bool // nil = use default (true), non-nil = explicitly set
DetectUnreachableBranches *bool // 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"`
Summary DeadCodeSummary `json:"summary"`
// Warnings and issues
Warnings []string `json:"warnings"`
Errors []string `json:"errors"`
// Metadata
GeneratedAt string `json:"generated_at"`
Version string `json:"version"`
Config interface{} `json:"config"` // Configuration used for analysis
}
DeadCodeResponse represents the complete dead code analysis result
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 JavaScript/TypeScript 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"`
TotalFunctions int `json:"total_functions"`
TotalFindings int `json:"total_findings"`
FilesWithDeadCode int `json:"files_with_dead_code"`
FunctionsWithDeadCode int `json:"functions_with_dead_code"`
// Severity distribution
CriticalFindings int `json:"critical_findings"`
WarningFindings int `json:"warning_findings"`
InfoFindings int `json:"info_findings"`
// Reason distribution
FindingsByReason map[string]int `json:"findings_by_reason"`
// Coverage metrics
TotalBlocks int `json:"total_blocks"`
DeadBlocks int `json:"dead_blocks"`
OverallDeadRatio float64 `json:"overall_dead_ratio"`
}
DeadCodeSummary represents aggregate statistics for dead code analysis
type DependencyAnalysisResult ¶
type DependencyAnalysisResult struct {
// Dependency graph information
TotalModules int // Total number of modules
TotalDependencies int // Total number of dependencies
RootModules []string // Modules with no dependencies
LeafModules []string // Modules with no dependents
// Dependency metrics
ModuleMetrics map[string]*ModuleDependencyMetrics // Per-module metrics
DependencyMatrix map[string]map[string]bool // Module -> dependencies
// Circular dependency analysis
CircularDependencies *CircularDependencyAnalysis // Circular dependency results
// Coupling analysis
CouplingAnalysis *CouplingAnalysis // Detailed coupling analysis
// Dependency chains
LongestChains []DependencyPath // Longest dependency chains
MaxDepth int // Maximum dependency depth
}
DependencyAnalysisResult contains module dependency analysis results
type DependencyEdge ¶
type DependencyEdge struct {
// From is the source module ID
From string `json:"from"`
// To is the target module ID
To string `json:"to"`
// EdgeType is the type of dependency (import/dynamic/type_only/re_export)
EdgeType DependencyEdgeType `json:"edge_type"`
// Specifiers are the individual imported items
Specifiers []string `json:"specifiers,omitempty"`
// Location is the source code location of the import statement
Location *SourceLocation `json:"location,omitempty"`
// Weight is the number of uses (for coupling calculations)
Weight int `json:"weight"`
}
DependencyEdge represents a directed edge in the dependency graph
type DependencyEdgeType ¶
type DependencyEdgeType string
DependencyEdgeType represents the type of dependency relationship
const ( // EdgeTypeImport represents static ES6/CommonJS import EdgeTypeImport DependencyEdgeType = "import" // EdgeTypeDynamic represents dynamic import() EdgeTypeDynamic DependencyEdgeType = "dynamic" // EdgeTypeTypeOnly represents TypeScript type-only import EdgeTypeTypeOnly DependencyEdgeType = "type_only" // EdgeTypeReExport represents export { } from EdgeTypeReExport DependencyEdgeType = "re_export" )
type DependencyGraph ¶
type DependencyGraph struct {
// Nodes maps module ID to ModuleNode
Nodes map[string]*ModuleNode `json:"nodes"`
// Edges maps source module ID to its outgoing edges
Edges map[string][]*DependencyEdge `json:"edges"`
// ReverseEdges maps target module ID to incoming edges (for afferent coupling)
ReverseEdges map[string][]*DependencyEdge `json:"-"`
}
DependencyGraph represents the complete dependency graph
func NewDependencyGraph ¶
func NewDependencyGraph() *DependencyGraph
NewDependencyGraph creates a new empty DependencyGraph
func (*DependencyGraph) AddEdge ¶
func (g *DependencyGraph) AddEdge(edge *DependencyEdge)
AddEdge adds an edge to the graph and updates reverse edges
func (*DependencyGraph) AddNode ¶
func (g *DependencyGraph) AddNode(node *ModuleNode)
AddNode adds a node to the graph
func (*DependencyGraph) EdgeCount ¶
func (g *DependencyGraph) EdgeCount() int
EdgeCount returns the total number of edges in the graph
func (*DependencyGraph) GetAllNodeIDs ¶
func (g *DependencyGraph) GetAllNodeIDs() []string
GetAllNodeIDs returns all node IDs in the graph
func (*DependencyGraph) GetIncomingEdges ¶
func (g *DependencyGraph) GetIncomingEdges(nodeID string) []*DependencyEdge
GetIncomingEdges returns all edges to a node (afferent)
func (*DependencyGraph) GetNode ¶
func (g *DependencyGraph) GetNode(id string) *ModuleNode
GetNode returns a node by ID
func (*DependencyGraph) GetOutgoingEdges ¶
func (g *DependencyGraph) GetOutgoingEdges(nodeID string) []*DependencyEdge
GetOutgoingEdges returns all edges from a node (efferent)
func (*DependencyGraph) NodeCount ¶
func (g *DependencyGraph) NodeCount() int
NodeCount returns the number of nodes in the graph
func (*DependencyGraph) UpdateNodeFlags ¶
func (g *DependencyGraph) UpdateNodeFlags()
UpdateNodeFlags updates IsEntryPoint and IsLeaf flags for all nodes
type DependencyGraphRequest ¶
type DependencyGraphRequest struct {
// Paths are the input files or directories to analyze
Paths []string `json:"paths"`
// OutputFormat specifies the output format
OutputFormat OutputFormat `json:"output_format"`
// OutputPath is the path to save output file
OutputPath string `json:"output_path,omitempty"`
// NoOpen prevents auto-opening HTML in browser
NoOpen bool `json:"no_open"`
// Recursive indicates whether to analyze directories recursively
Recursive *bool `json:"recursive,omitempty"`
// IncludePatterns are glob patterns for files to include
IncludePatterns []string `json:"include_patterns,omitempty"`
// ExcludePatterns are glob patterns for files to exclude
ExcludePatterns []string `json:"exclude_patterns,omitempty"`
// IncludeExternal indicates whether to include external modules (node_modules)
IncludeExternal *bool `json:"include_external,omitempty"`
// IncludeTypeImports indicates whether to include TypeScript type imports
IncludeTypeImports *bool `json:"include_type_imports,omitempty"`
// DetectCycles enables circular dependency detection
DetectCycles *bool `json:"detect_cycles,omitempty"`
// Thresholds for risk assessment
InstabilityHighThreshold float64 `json:"instability_high_threshold,omitempty"`
InstabilityLowThreshold float64 `json:"instability_low_threshold,omitempty"`
DistanceThreshold float64 `json:"distance_threshold,omitempty"`
}
DependencyGraphRequest represents a request for dependency graph analysis
func DefaultDependencyGraphRequest ¶
func DefaultDependencyGraphRequest() *DependencyGraphRequest
DefaultDependencyGraphRequest returns a DependencyGraphRequest with default values
type DependencyGraphResponse ¶
type DependencyGraphResponse struct {
// Graph is the complete dependency graph
Graph *DependencyGraph `json:"graph"`
// Analysis is the dependency analysis result
Analysis *DependencyAnalysisResult `json:"analysis"`
// Warnings contains any warnings from analysis
Warnings []string `json:"warnings,omitempty"`
// Errors contains any errors encountered during analysis
Errors []string `json:"errors,omitempty"`
// GeneratedAt is when the analysis was generated
GeneratedAt string `json:"generated_at"`
// Version is the tool version
Version string `json:"version"`
}
DependencyGraphResponse represents the response from dependency graph analysis
type DependencyPath ¶
type DependencyPath struct {
From string // Starting module
To string // Ending module
Path []string // Complete path
Length int // Path length
}
DependencyPath represents a path of dependencies
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 Export ¶
type Export struct {
// ExportType is the type of export: "named", "default", "all", "declaration"
ExportType string `json:"export_type"`
// Source is the re-export source (empty if not re-exporting)
Source string `json:"source,omitempty"`
// SourceType is the type of re-export source module
SourceType ModuleType `json:"source_type,omitempty"`
// Specifiers are the individual exported items
Specifiers []ExportSpecifier `json:"specifiers,omitempty"`
// Declaration is the declaration type (function, class, const, etc.)
Declaration string `json:"declaration,omitempty"`
// Name is the exported name
Name string `json:"name,omitempty"`
// IsTypeOnly indicates TypeScript type-only exports
IsTypeOnly bool `json:"is_type_only,omitempty"`
// Location is the source code location
Location SourceLocation `json:"location"`
}
Export represents a single export statement in JavaScript/TypeScript
type ExportSpecifier ¶
type ExportSpecifier struct {
// Local is the local name
Local string `json:"local"`
// Exported is the exported name (or same as Local if no alias)
Exported string `json:"exported"`
// IsType indicates TypeScript type-only specifier
IsType bool `json:"is_type,omitempty"`
}
ExportSpecifier represents an individual exported item
type FileDeadCode ¶
type FileDeadCode struct {
// File identification
FilePath string `json:"file_path"`
// Functions analyzed
Functions []FunctionDeadCode `json:"functions"`
// File-level findings (unused imports/exports, not scoped to a function)
FileLevelFindings []DeadCodeFinding `json:"file_level_findings,omitempty"`
// File-level summary
TotalFindings int `json:"total_findings"`
TotalFunctions int `json:"total_functions"`
AffectedFunctions int `json:"affected_functions"`
DeadCodeRatio float64 `json:"dead_code_ratio"`
}
FileDeadCode represents dead code analysis result for a single file
type FileReader ¶
type FileReader interface {
// CollectPythonFiles recursively finds all JavaScript/TypeScript 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 JavaScript/TypeScript 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 legacy interface for reading and collecting files. NOTE: Historical Python-style method names are kept for API compatibility.
type FunctionComplexity ¶
type FunctionComplexity struct {
// Function identification
Name string `json:"name" yaml:"name"`
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 complexity analysis result for a single function
type FunctionDeadCode ¶
type FunctionDeadCode struct {
// Function identification
Name string `json:"name"`
FilePath string `json:"file_path"`
// Dead code findings
Findings []DeadCodeFinding `json:"findings"`
// Function metrics
TotalBlocks int `json:"total_blocks"`
DeadBlocks int `json:"dead_blocks"`
ReachableRatio float64 `json:"reachable_ratio"`
// Summary by severity
CriticalCount int `json:"critical_count"`
WarningCount int `json:"warning_count"`
InfoCount int `json:"info_count"`
}
FunctionDeadCode represents dead code analysis result for a single function
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
type Import ¶
type Import struct {
// Source is the module specifier (e.g., 'lodash', './utils')
Source string `json:"source"`
// SourceType is the type of module source (relative, package, builtin, etc.)
SourceType ModuleType `json:"source_type"`
// ImportType is the type of import (default, named, namespace, etc.)
ImportType ImportType `json:"import_type"`
// Specifiers are the individual imported items
Specifiers []ImportSpecifier `json:"specifiers,omitempty"`
// IsTypeOnly indicates TypeScript type-only imports
IsTypeOnly bool `json:"is_type_only,omitempty"`
// IsDynamic indicates dynamic import() expressions
IsDynamic bool `json:"is_dynamic,omitempty"`
// Location is the source code location
Location SourceLocation `json:"location"`
}
Import represents a single import statement in JavaScript/TypeScript
type ImportSpecifier ¶
type ImportSpecifier struct {
// Imported is the original name from the module
Imported string `json:"imported"`
// Local is the local alias (or same as Imported if no alias)
Local string `json:"local"`
// IsType indicates TypeScript type-only specifier
IsType bool `json:"is_type,omitempty"`
}
ImportSpecifier represents an individual imported item
type ImportType ¶
type ImportType string
ImportType represents the type of import statement
const ( // ImportTypeDefault represents default imports: import x from 'y' ImportTypeDefault ImportType = "default" // ImportTypeNamed represents named imports: import { x } from 'y' ImportTypeNamed ImportType = "named" // ImportTypeNamespace represents namespace imports: import * as x from 'y' ImportTypeNamespace ImportType = "namespace" // ImportTypeSideEffect represents side-effect imports: import 'y' ImportTypeSideEffect ImportType = "side_effect" // ImportTypeDynamic represents dynamic imports: import('y') ImportTypeDynamic ImportType = "dynamic" // ImportTypeRequire represents CommonJS require: require('y') ImportTypeRequire ImportType = "require" // ImportTypeTypeOnly represents TypeScript type imports: import type { x } from 'y' ImportTypeTypeOnly ImportType = "type_only" )
type IssueSeverity ¶
type IssueSeverity string
IssueSeverity represents issue severity
const ( IssueSeverityLow IssueSeverity = "low" IssueSeverityMedium IssueSeverity = "medium" IssueSeverityHigh IssueSeverity = "high" IssueSeverityCritical IssueSeverity = "critical" )
type JSFileReader ¶ added in v0.4.0
type JSFileReader interface {
CollectJSFiles(paths []string, recursive bool, includePatterns, excludePatterns []string) ([]string, error)
ReadFile(path string) ([]byte, error)
IsValidJSFile(path string) bool
FileExists(path string) (bool, error)
}
JSFileReader defines JavaScript/TypeScript-specific file operations.
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 // Number of layers analyzed
LayerViolations []LayerViolation // Layer rule violations
LayerCoupling map[string]map[string]int // Layer -> Layer -> dependency count
LayerCohesion map[string]float64 // Layer -> cohesion score
ProblematicLayers []string // 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"`
}
LayerRule defines a dependency rule between layers
type LayerViolation ¶
type LayerViolation struct {
FromModule string // Module causing violation
ToModule string // Target module
FromLayer string // Source layer
ToLayer string // Target layer
Rule string // Rule that was violated
Severity ViolationSeverity // Severity of violation
Description string // Description of violation
Suggestion string // Suggested fix
}
LayerViolation represents a layer architecture rule violation
type ModuleAnalysisRequest ¶
type ModuleAnalysisRequest struct {
// Paths are the input files or directories to analyze
Paths []string `json:"paths"`
// Recursive indicates whether to analyze directories recursively
Recursive bool `json:"recursive"`
// IncludeBuiltins indicates whether to include Node.js builtins
IncludeBuiltins bool `json:"include_builtins"`
// IncludeTypeImports indicates whether to include TypeScript type imports
IncludeTypeImports bool `json:"include_type_imports"`
// ResolveRelative indicates whether to resolve relative import paths
ResolveRelative bool `json:"resolve_relative"`
// AliasPatterns are path alias patterns to recognize (@/, ~/, etc.)
AliasPatterns []string `json:"alias_patterns,omitempty"`
}
ModuleAnalysisRequest represents a request for module analysis
type ModuleAnalysisResponse ¶
type ModuleAnalysisResponse struct {
// Result contains the analysis result
Result *ModuleAnalysisResult `json:"result"`
// Errors contains any errors encountered during analysis
Errors []string `json:"errors,omitempty"`
// Warnings contains any warnings from analysis
Warnings []string `json:"warnings,omitempty"`
}
ModuleAnalysisResponse represents the response from module analysis
type ModuleAnalysisResult ¶
type ModuleAnalysisResult struct {
// Files maps file paths to their module info
Files map[string]*ModuleInfo `json:"files"`
// DependencyGraph maps modules to their dependencies
DependencyGraph map[string][]string `json:"dependency_graph"`
// PackageDeps lists all npm package dependencies found
PackageDeps []string `json:"package_deps"`
// Summary provides aggregate statistics
Summary ModuleAnalysisSummary `json:"summary"`
}
ModuleAnalysisResult is the complete result of module analysis across multiple files
type ModuleAnalysisSummary ¶
type ModuleAnalysisSummary struct {
// TotalFiles is the number of files analyzed
TotalFiles int `json:"total_files"`
// TotalImports is the total number of import statements
TotalImports int `json:"total_imports"`
// TotalExports is the total number of export statements
TotalExports int `json:"total_exports"`
// UniquePackages is the number of unique npm packages
UniquePackages int `json:"unique_packages"`
// RelativeImports is the count of relative imports
RelativeImports int `json:"relative_imports"`
// AbsoluteImports is the count of absolute imports
AbsoluteImports int `json:"absolute_imports"`
// DynamicImports is the count of dynamic imports
DynamicImports int `json:"dynamic_imports"`
// TypeOnlyImports is the count of TypeScript type-only imports
TypeOnlyImports int `json:"type_only_imports"`
// CommonJSImports is the count of CommonJS require() calls
CommonJSImports int `json:"commonjs_imports"`
}
ModuleAnalysisSummary provides aggregate statistics for module analysis
type ModuleDependency ¶
type ModuleDependency struct {
// Source is the source module path as written in the import
Source string `json:"source"`
// SourceType is the type of module (relative, package, builtin, etc.)
SourceType ModuleType `json:"source_type"`
// ResolvedPath is the resolved absolute path (if resolvable)
ResolvedPath string `json:"resolved_path,omitempty"`
// IsDevDep indicates whether this is a dev dependency
IsDevDep bool `json:"is_dev_dep,omitempty"`
// Usages lists what is imported from this module
Usages []string `json:"usages,omitempty"`
}
ModuleDependency represents a dependency relationship between modules
type ModuleDependencyMetrics ¶
type ModuleDependencyMetrics struct {
// Basic information
ModuleName string // Module name
Package string // Package name
FilePath string // File path
IsPackage bool // True if this is a package
// Size metrics
LinesOfCode int // Total lines of code
FunctionCount int // Number of functions
ClassCount int // Number of classes
PublicInterface []string // Public names exported
// Coupling metrics (Robert Martin's metrics)
AfferentCoupling int // Ca - modules that depend on this one
EfferentCoupling int // Ce - modules this one depends on
Instability float64 // I = Ce / (Ca + Ce)
Abstractness float64 // A - abstractness measure
Distance float64 // D - distance from main sequence
// Quality metrics
Maintainability float64 // Maintainability index (0-100)
TechnicalDebt float64 // Estimated technical debt in hours
RiskLevel RiskLevel // Overall risk assessment
// Dependencies
DirectDependencies []string // Modules this directly depends on
TransitiveDependencies []string // All transitive dependencies
Dependents []string // Modules that depend on this one
}
ModuleDependencyMetrics contains dependency metrics for a single module
type ModuleInfo ¶
type ModuleInfo struct {
// FilePath is the path to the analyzed file
FilePath string `json:"file_path"`
// Imports are all import statements in the file
Imports []*Import `json:"imports"`
// Exports are all export statements in the file
Exports []*Export `json:"exports"`
// Dependencies are the module dependencies extracted from imports
Dependencies []ModuleDependency `json:"dependencies"`
}
ModuleInfo contains all module analysis results for a single file
type ModuleNode ¶
type ModuleNode struct {
// ID is the unique identifier (normalized path)
ID string `json:"id"`
// Name is the module name (filename without extension)
Name string `json:"name"`
// FilePath is the full file path
FilePath string `json:"file_path"`
// ModuleType is the classification (relative, package, builtin, alias)
ModuleType ModuleType `json:"module_type"`
// IsExternal indicates if the module is not in the project (e.g., node_modules)
IsExternal bool `json:"is_external"`
// IsEntryPoint indicates if no other modules depend on this one
IsEntryPoint bool `json:"is_entry_point"`
// IsLeaf indicates if this module has no dependencies
IsLeaf bool `json:"is_leaf"`
// Exports lists the exported names from this module
Exports []string `json:"exports,omitempty"`
}
ModuleNode represents a node in the dependency graph
type ModuleType ¶
type ModuleType string
ModuleType represents the type of module source
const ( // ModuleTypeRelative represents relative imports: ./foo, ../bar ModuleTypeRelative ModuleType = "relative" // ModuleTypeAbsolute represents absolute imports: /foo/bar ModuleTypeAbsolute ModuleType = "absolute" // ModuleTypePackage represents package imports: lodash, react ModuleTypePackage ModuleType = "package" // ModuleTypeBuiltin represents Node.js builtins: node:fs, fs (when builtin) ModuleTypeBuiltin ModuleType = "builtin" // ModuleTypeAlias represents aliased imports: @/components, ~/utils ModuleTypeAlias ModuleType = "alias" )
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 {
// StartTask creates a new progress task with a description and total count
StartTask(description string, total int) TaskProgress
// IsInteractive returns true if progress bars should be shown
IsInteractive() bool
// Close cleans up all tasks
Close()
}
ProgressManager manages progress tracking for analysis
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 // SRP violations detected
ModuleResponsibilities map[string][]string // Module -> responsibilities
OverloadedModules []string // Modules with too many responsibilities
}
ResponsibilityAnalysis contains Single Responsibility Principle analysis
type SRPViolation ¶
type SRPViolation struct {
Module string // Module with violation
Responsibilities []string // Multiple responsibilities detected
Severity ViolationSeverity // Severity level
Suggestion string // 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 )
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 SystemAnalysisConfigurationLoader ¶
type SystemAnalysisConfigurationLoader interface {
// LoadConfig loads configuration from the specified path
LoadConfig(path string) (*SystemAnalysisRequest, error)
// LoadDefaultConfig loads the default configuration
LoadDefaultConfig() *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
// 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
// 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 // Module dependency analysis
ArchitectureAnalysis *ArchitectureAnalysisResult // Architecture validation results
// Summary information
Summary SystemAnalysisSummary // High-level summary
// Issues and recommendations
Issues []SystemIssue // Critical issues found
Recommendations []SystemRecommendation // Improvement recommendations
Warnings []string // Analysis warnings
Errors []string // Analysis errors
// Metadata
GeneratedAt time.Time // When the analysis was generated
Duration int64 // Analysis duration in milliseconds
Version string // Tool version
Config interface{} // Configuration used for analysis
}
SystemAnalysisResponse represents the complete system analysis result
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 // Total number of modules analyzed
TotalPackages int // Total number of packages
TotalDependencies int // Total dependency relationships
ProjectRoot string // Project root directory
// Quality scores (0-100, higher is better)
OverallQualityScore float64 // Composite quality score
MaintainabilityScore float64 // Average maintainability index
ArchitectureScore float64 // Architecture compliance score
ModularityScore float64 // System modularity score
TechnicalDebtHours float64 // Total estimated technical debt
// Key metrics
AverageCoupling float64 // Average module coupling
AverageInstability float64 // Average instability
CyclicDependencies int // Number of modules in cycles
ArchitectureViolations int // Number of architecture rule violations
HighRiskModules int // Number of high-risk modules
// Recommendations summary
CriticalIssues int // Number of critical issues requiring immediate attention
RefactoringCandidates int // Number of modules needing refactoring
ArchitectureImprovements int // Number of architecture improvements suggested
}
SystemAnalysisSummary provides a high-level overview of system quality
type SystemIssue ¶
type SystemIssue struct {
Type IssueType // Type of issue
Severity IssueSeverity // Severity level
Title string // Issue title
Description string // Detailed description
Impact string // Impact description
Modules []string // Affected modules
Suggestion string // Remediation suggestion
}
SystemIssue represents a critical system-level issue
type SystemRecommendation ¶
type SystemRecommendation struct {
Category RecommendationCategory // Category of recommendation
Priority RecommendationPriority // Priority level
Title string // Recommendation title
Description string // Detailed description
Rationale string // Why this is recommended
Benefits []string // Expected benefits
Steps []string // Implementation steps
Resources []string // Additional resources
Effort EstimatedEffort // Estimated effort
}
SystemRecommendation represents a system-level improvement recommendation
type TaskProgress ¶
type TaskProgress interface {
// Increment adds n to the current progress
Increment(n int)
// Describe updates the current item description
Describe(description string)
// Complete marks the task as finished
Complete()
}
TaskProgress tracks progress for a single analysis task
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 )