Documentation
¶
Overview ¶
Package git provides git integration for analyzing code changes. This file contains types for change frequency analysis, collision detection, and anti-pattern identification.
Package git provides git integration for analyzing code changes. It supports analyzing staged changes, work-in-progress, specific commits, and commit ranges for duplicate detection and naming consistency analysis.
Index ¶
- Variables
- func CacheKey(filePath string, window TimeWindow, granularity FrequencyGranularity) string
- func CacheKeyFile(filePath string, window TimeWindow) string
- func CacheKeyPattern(pattern string, window TimeWindow) string
- func CacheKeySymbol(filePath string, symbolName string, window TimeWindow) string
- func CalculateCollisionScore(contributors []ContributorActivity, recentChanges int) float64
- func CalculateRiskScore(duplicates []DuplicateFinding, namingIssues []NamingFinding, ...) float64
- func CalculateVolatilityScore(changeCount, linesChanged, uniqueAuthors int, windowDays float64) float64
- func CountFileLines(content []byte) int
- func GenerateTopRecommendation(duplicates []DuplicateFinding, namingIssues []NamingFinding, ...) string
- func GetPatternRecommendations(patternType AntiPatternType) []string
- func IsValidCaseStyle(lang Language, kind SymbolKind, style CaseStyle) bool
- func TimeWindowToDuration(tw TimeWindow) time.Duration
- type AnalysisParams
- type AnalysisReport
- type AnalysisScope
- type Analyzer
- type AntiPattern
- type AntiPatternSeverity
- type AntiPatternType
- type CacheStats
- type CaseStyle
- type ChangeFrequencyMetadata
- type ChangeFrequencyParams
- type ChangeFrequencyReport
- type ChangeFrequencySummary
- type ChangedFile
- type ChurnFilterConfig
- type CodeLocation
- type CollisionSeverity
- type CollisionZone
- type CommitInfo
- type ContributorActivity
- type DiffSize
- type DiffStats
- type DuplicateFinding
- type FileChange
- type FileChangeFrequency
- type FileChangeStatus
- type FindingSeverity
- func DetermineCollisionSeverity(score float64) FindingSeverity
- func DetermineDuplicateSeverity(similarity float64, lineCount int) FindingSeverity
- func DetermineMetricsSeverity(issueType MetricsIssueType, metrics SymbolMetrics, ...) FindingSeverity
- func DetermineNamingSeverity(issueType NamingIssueType, similarity float64) FindingSeverity
- type FrequencyAnalyzer
- func (a *FrequencyAnalyzer) Analyze(ctx context.Context, params ChangeFrequencyParams) (*ChangeFrequencyReport, error)
- func (a *FrequencyAnalyzer) AnalyzeFile(ctx context.Context, filePath string, window TimeWindow) (*FileChangeFrequency, error)
- func (a *FrequencyAnalyzer) GetCollisionRisk(ctx context.Context, filePath string) (*CollisionZone, error)
- type FrequencyCache
- func (c *FrequencyCache) Clear()
- func (c *FrequencyCache) Delete(key string)
- func (c *FrequencyCache) Get(key string) (interface{}, bool)
- func (c *FrequencyCache) GetFileFrequency(filePath string, window TimeWindow) (*FileChangeFrequency, bool)
- func (c *FrequencyCache) GetOrCompute(key string, compute func() (interface{}, error)) (interface{}, error)
- func (c *FrequencyCache) GetReport(pattern string, window TimeWindow) (*ChangeFrequencyReport, bool)
- func (c *FrequencyCache) InvalidateFile(filePath string)
- func (c *FrequencyCache) InvalidatePattern(pattern string)
- func (c *FrequencyCache) Set(key string, data interface{})
- func (c *FrequencyCache) SetFileFrequency(filePath string, window TimeWindow, freq *FileChangeFrequency)
- func (c *FrequencyCache) SetReport(pattern string, window TimeWindow, report *ChangeFrequencyReport)
- func (c *FrequencyCache) SetWithTTL(key string, data interface{}, ttl time.Duration)
- func (c *FrequencyCache) Stats() CacheStats
- func (c *FrequencyCache) Warm(entries map[string]interface{})
- type FrequencyFocus
- type FrequencyGranularity
- type FrequencyMetrics
- type HistoryProvider
- func (h *HistoryProvider) AggregateFileStats(commits []CommitInfo, filePath string, window TimeWindow) *FileChangeFrequency
- func (h *HistoryProvider) GetCommitHistory(ctx context.Context, since time.Time, paths ...string) ([]CommitInfo, error)
- func (h *HistoryProvider) GetCurrentAuthor(ctx context.Context) (name, email string, err error)
- func (h *HistoryProvider) GetFileContributors(ctx context.Context, filePath string, since time.Time) ([]ContributorActivity, error)
- func (h *HistoryProvider) GetFileHistory(ctx context.Context, filePath string, since time.Time) ([]CommitInfo, error)
- func (h *HistoryProvider) GetRecentCommitCount(ctx context.Context, filePath string, window time.Duration) (int, error)
- func (h *HistoryProvider) GetRepoHistory(ctx context.Context, since time.Time, pattern string) ([]CommitInfo, error)
- func (h *HistoryProvider) GetSymbolHistory(ctx context.Context, filePath string, startLine, endLine int, since time.Time) ([]CommitInfo, error)
- type Language
- type MetricsFinding
- type MetricsIssueType
- type MetricsThresholds
- type ModuleOwnership
- type NamingConvention
- type NamingFinding
- type NamingIssueType
- type PatternDetector
- func (d *PatternDetector) AnalyzeFileForPatterns(content []byte, filePath string, contributors []ContributorActivity) []AntiPattern
- func (d *PatternDetector) DetectPatterns(content []byte, filePath string) []AntiPattern
- func (d *PatternDetector) DetectPatternsFromReader(content []byte, filePath string) []AntiPattern
- func (d *PatternDetector) QuickScan(content []byte, filePath string) *AntiPattern
- type Provider
- func (p *Provider) GetBaseRef(ctx context.Context, params AnalysisParams) (string, error)
- func (p *Provider) GetChangedFiles(ctx context.Context, params AnalysisParams) ([]ChangedFile, error)
- func (p *Provider) GetCommitHash(ctx context.Context, ref string) (string, error)
- func (p *Provider) GetCurrentBranch(ctx context.Context) (string, error)
- func (p *Provider) GetDiffStats(ctx context.Context, params AnalysisParams) (DiffStats, error)
- func (p *Provider) GetFileContent(ctx context.Context, ref, path string) ([]byte, error)
- func (p *Provider) GetRepoRoot() string
- func (p *Provider) GetTargetRef(params AnalysisParams) string
- func (p *Provider) IsGitRepo() bool
- func (p *Provider) ListAllFiles(ctx context.Context) ([]string, error)
- type ReportMetadata
- type ReportSummary
- type SymbolChangeFrequency
- type SymbolDiff
- type SymbolInfo
- type SymbolKind
- type SymbolMetrics
- type TimeWindow
Constants ¶
This section is empty.
Variables ¶
var LanguageNamingConventions = map[Language]NamingConvention{ LangGo: { Description: "Go uses PascalCase for exported, camelCase for unexported", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStylePascalCase, CaseStyleCamelCase}, KindMethod: {CaseStylePascalCase, CaseStyleCamelCase}, KindClass: {CaseStylePascalCase, CaseStyleCamelCase}, KindInterface: {CaseStylePascalCase, CaseStyleCamelCase}, KindStruct: {CaseStylePascalCase, CaseStyleCamelCase}, KindType: {CaseStylePascalCase, CaseStyleCamelCase}, KindConstant: {CaseStylePascalCase, CaseStyleCamelCase}, KindVariable: {CaseStylePascalCase, CaseStyleCamelCase}, KindField: {CaseStylePascalCase, CaseStyleCamelCase}, KindEnum: {CaseStylePascalCase, CaseStyleCamelCase}, KindEnumMember: {CaseStylePascalCase, CaseStyleCamelCase}, }, }, LangJavaScript: { Description: "JavaScript uses camelCase for functions/variables, PascalCase for classes", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleCamelCase}, KindMethod: {CaseStyleCamelCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindConstant: {CaseStyleCamelCase, CaseStyleSnakeCase}, KindVariable: {CaseStyleCamelCase}, KindField: {CaseStyleCamelCase}, KindProperty: {CaseStyleCamelCase}, }, }, LangTypeScript: { Description: "TypeScript uses camelCase for functions/variables, PascalCase for types/classes", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleCamelCase}, KindMethod: {CaseStyleCamelCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindType: {CaseStylePascalCase}, KindConstant: {CaseStyleCamelCase, CaseStyleSnakeCase}, KindVariable: {CaseStyleCamelCase}, KindField: {CaseStyleCamelCase}, KindProperty: {CaseStyleCamelCase}, KindEnum: {CaseStylePascalCase}, KindEnumMember: {CaseStylePascalCase, CaseStyleSnakeCase}, }, }, LangPython: { Description: "Python uses snake_case for functions/variables, PascalCase for classes", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleSnakeCase}, KindMethod: {CaseStyleSnakeCase}, KindClass: {CaseStylePascalCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleSnakeCase}, KindField: {CaseStyleSnakeCase}, KindProperty: {CaseStyleSnakeCase}, KindModule: {CaseStyleSnakeCase}, }, }, LangRust: { Description: "Rust uses snake_case for functions/variables, PascalCase for types", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleSnakeCase}, KindMethod: {CaseStyleSnakeCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindStruct: {CaseStylePascalCase}, KindType: {CaseStylePascalCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleSnakeCase}, KindField: {CaseStyleSnakeCase}, KindEnum: {CaseStylePascalCase}, KindEnumMember: {CaseStylePascalCase}, KindModule: {CaseStyleSnakeCase}, }, }, LangJava: { Description: "Java uses camelCase for methods/variables, PascalCase for classes", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleCamelCase}, KindMethod: {CaseStyleCamelCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleCamelCase}, KindField: {CaseStyleCamelCase}, KindEnum: {CaseStylePascalCase}, KindEnumMember: {CaseStyleSnakeCase}, }, }, LangCSharp: { Description: "C# uses PascalCase for public members, camelCase for private", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStylePascalCase}, KindMethod: {CaseStylePascalCase, CaseStyleCamelCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindStruct: {CaseStylePascalCase}, KindConstant: {CaseStylePascalCase}, KindVariable: {CaseStyleCamelCase}, KindField: {CaseStyleCamelCase, CaseStylePascalCase}, KindProperty: {CaseStylePascalCase}, KindEnum: {CaseStylePascalCase}, KindEnumMember: {CaseStylePascalCase}, KindNamespace: {CaseStylePascalCase}, }, }, LangCpp: { Description: "C++ conventions vary, commonly snake_case or camelCase for functions", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleSnakeCase, CaseStyleCamelCase, CaseStylePascalCase}, KindMethod: {CaseStyleSnakeCase, CaseStyleCamelCase, CaseStylePascalCase}, KindClass: {CaseStylePascalCase}, KindStruct: {CaseStylePascalCase, CaseStyleSnakeCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleSnakeCase, CaseStyleCamelCase}, KindField: {CaseStyleSnakeCase, CaseStyleCamelCase}, KindNamespace: {CaseStyleSnakeCase, CaseStylePascalCase}, }, }, LangC: { Description: "C uses snake_case for functions/variables", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleSnakeCase}, KindStruct: {CaseStyleSnakeCase, CaseStylePascalCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleSnakeCase}, KindField: {CaseStyleSnakeCase}, }, }, LangRuby: { Description: "Ruby uses snake_case for methods/variables, PascalCase for classes", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleSnakeCase}, KindMethod: {CaseStyleSnakeCase}, KindClass: {CaseStylePascalCase}, KindModule: {CaseStylePascalCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleSnakeCase}, KindField: {CaseStyleSnakeCase}, }, }, LangSwift: { Description: "Swift uses camelCase for functions/properties, PascalCase for types", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleCamelCase}, KindMethod: {CaseStyleCamelCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindStruct: {CaseStylePascalCase}, KindType: {CaseStylePascalCase}, KindConstant: {CaseStyleCamelCase}, KindVariable: {CaseStyleCamelCase}, KindProperty: {CaseStyleCamelCase}, KindEnum: {CaseStylePascalCase}, KindEnumMember: {CaseStyleCamelCase}, }, }, LangKotlin: { Description: "Kotlin uses camelCase for functions/properties, PascalCase for classes", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleCamelCase}, KindMethod: {CaseStyleCamelCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleCamelCase}, KindProperty: {CaseStyleCamelCase}, KindEnum: {CaseStylePascalCase}, KindEnumMember: {CaseStyleSnakeCase}, }, }, LangScala: { Description: "Scala uses camelCase for methods/values, PascalCase for types", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleCamelCase}, KindMethod: {CaseStyleCamelCase}, KindClass: {CaseStylePascalCase}, KindInterface: {CaseStylePascalCase}, KindType: {CaseStylePascalCase}, KindConstant: {CaseStylePascalCase}, KindVariable: {CaseStyleCamelCase}, }, }, LangZig: { Description: "Zig uses camelCase for functions, PascalCase for types", ExpectedStyles: map[SymbolKind][]CaseStyle{ KindFunction: {CaseStyleCamelCase}, KindStruct: {CaseStylePascalCase}, KindType: {CaseStylePascalCase}, KindConstant: {CaseStyleSnakeCase}, KindVariable: {CaseStyleSnakeCase, CaseStyleCamelCase}, }, }, }
LanguageNamingConventions maps languages to their naming conventions
Functions ¶
func CacheKey ¶
func CacheKey(filePath string, window TimeWindow, granularity FrequencyGranularity) string
CacheKey generates a cache key for frequency analysis
func CacheKeyFile ¶
func CacheKeyFile(filePath string, window TimeWindow) string
CacheKeyFile generates a cache key for file-level analysis
func CacheKeyPattern ¶
func CacheKeyPattern(pattern string, window TimeWindow) string
CacheKeyPattern generates a cache key for pattern analysis
func CacheKeySymbol ¶
func CacheKeySymbol(filePath string, symbolName string, window TimeWindow) string
CacheKeySymbol generates a cache key for symbol-level analysis
func CalculateCollisionScore ¶
func CalculateCollisionScore(contributors []ContributorActivity, recentChanges int) float64
CalculateCollisionScore computes a collision risk score
func CalculateRiskScore ¶
func CalculateRiskScore(duplicates []DuplicateFinding, namingIssues []NamingFinding, metricsIssues []MetricsFinding) float64
CalculateRiskScore computes an overall risk score based on findings
func CalculateVolatilityScore ¶
func CalculateVolatilityScore(changeCount, linesChanged, uniqueAuthors int, windowDays float64) float64
CalculateVolatilityScore computes a volatility score from metrics
func CountFileLines ¶
CountFileLines returns the line count of content
func GenerateTopRecommendation ¶
func GenerateTopRecommendation(duplicates []DuplicateFinding, namingIssues []NamingFinding, metricsIssues []MetricsFinding) string
GenerateTopRecommendation creates the highest-priority recommendation
func GetPatternRecommendations ¶
func GetPatternRecommendations(patternType AntiPatternType) []string
GetPatternRecommendations returns detailed recommendations for a pattern type
func IsValidCaseStyle ¶
func IsValidCaseStyle(lang Language, kind SymbolKind, style CaseStyle) bool
IsValidCaseStyle checks if a case style is valid for a symbol in a language
func TimeWindowToDuration ¶
func TimeWindowToDuration(tw TimeWindow) time.Duration
TimeWindowToDuration converts a TimeWindow to a time.Duration
Types ¶
type AnalysisParams ¶
type AnalysisParams struct {
// Scope determines what changes to analyze
Scope AnalysisScope `json:"scope"`
// BaseRef is the reference for the base index (default depends on scope)
// For staged/wip: HEAD
// For commit: parent commit
// For range: specified base
BaseRef string `json:"base_ref,omitempty"`
// TargetRef is the reference for the working index
// For range mode, this is the target commit
TargetRef string `json:"target_ref,omitempty"`
// Focus specifies which analyses to perform
// Options: "duplicates", "naming"
// Default: both
Focus []string `json:"focus,omitempty"`
// SimilarityThreshold for duplicate/naming detection (0.0-1.0)
// Default: 0.8
SimilarityThreshold float64 `json:"similarity_threshold,omitempty"`
// MaxFindings limits findings per category
// Default: 20
MaxFindings int `json:"max_findings,omitempty"`
}
AnalysisParams configures the git change analysis
func DefaultAnalysisParams ¶
func DefaultAnalysisParams() AnalysisParams
DefaultAnalysisParams returns default analysis parameters
func (*AnalysisParams) HasFocus ¶
func (p *AnalysisParams) HasFocus(focus string) bool
HasFocus checks if a specific focus area is enabled
type AnalysisReport ¶
type AnalysisReport struct {
// Summary provides high-level statistics
Summary ReportSummary `json:"summary"`
// Duplicates contains duplicate code findings
Duplicates []DuplicateFinding `json:"duplicates,omitempty"`
// NamingIssues contains naming consistency findings
NamingIssues []NamingFinding `json:"naming_issues,omitempty"`
// MetricsIssues contains function metrics findings
MetricsIssues []MetricsFinding `json:"metrics_issues,omitempty"`
// Metadata provides analysis context
Metadata ReportMetadata `json:"metadata"`
}
AnalysisReport is the complete output of git change analysis
type AnalysisScope ¶
type AnalysisScope string
AnalysisScope defines what changes to analyze
const ( // ScopeStaged analyzes only staged changes (git diff --cached) ScopeStaged AnalysisScope = "staged" // ScopeWIP analyzes all uncommitted changes (staged + unstaged) ScopeWIP AnalysisScope = "wip" // ScopeCommit analyzes a specific commit vs its parent ScopeCommit AnalysisScope = "commit" // ScopeRange analyzes a commit range (base..target) ScopeRange AnalysisScope = "range" )
type Analyzer ¶
type Analyzer struct {
// contains filtered or unexported fields
}
Analyzer performs git change analysis comparing new code against existing index
func NewAnalyzer ¶
func NewAnalyzer(provider *Provider, index *indexing.MasterIndex) *Analyzer
NewAnalyzer creates a new git change analyzer
func (*Analyzer) Analyze ¶
func (a *Analyzer) Analyze(ctx context.Context, params AnalysisParams) (*AnalysisReport, error)
Analyze performs complete change analysis
type AntiPattern ¶
type AntiPattern struct {
// Type categorizes the anti-pattern
Type AntiPatternType `json:"type"`
// Description explains what was detected
Description string `json:"description"`
// Location identifies where in the file (line range or function name)
Location string `json:"location"`
// Severity indicates how problematic this is
Severity AntiPatternSeverity `json:"severity"`
// Suggestion provides a decoupling recommendation
Suggestion string `json:"suggestion"`
// Metrics provides supporting data
Metrics map[string]int `json:"metrics,omitempty"`
}
AntiPattern represents a detected conflict-prone code pattern
type AntiPatternSeverity ¶
type AntiPatternSeverity string
AntiPatternSeverity indicates how problematic a pattern is
const ( // AntiPatternSeverityHigh indicates a pattern causing frequent conflicts AntiPatternSeverityHigh AntiPatternSeverity = "high" // AntiPatternSeverityMedium indicates a pattern that may cause conflicts AntiPatternSeverityMedium AntiPatternSeverity = "medium" // AntiPatternSeverityLow indicates a minor concern AntiPatternSeverityLow AntiPatternSeverity = "low" )
type AntiPatternType ¶
type AntiPatternType string
AntiPatternType categorizes conflict-prone code patterns
const ( // PatternRegistrationFunction is a large function with many sequential registrations PatternRegistrationFunction AntiPatternType = "registration_function" // PatternEnumAggregation is a file with many enum/const definitions PatternEnumAggregation AntiPatternType = "enum_aggregation" // PatternGodObject is a large file/class with high contributor count PatternGodObject AntiPatternType = "god_object" // PatternBarrelFile is an index/re-export file PatternBarrelFile AntiPatternType = "barrel_file" // PatternSwitchFactory is a large switch/case statement PatternSwitchFactory AntiPatternType = "switch_factory" // PatternConfigAggregation is a config struct/file with many fields PatternConfigAggregation AntiPatternType = "config_aggregation" )
type CacheStats ¶
type CacheStats struct {
Hits uint64 `json:"hits"`
Misses uint64 `json:"misses"`
HitRate float64 `json:"hit_rate"`
EntryCount int `json:"entry_count"`
TTL time.Duration `json:"ttl_seconds"`
}
CacheStats holds cache statistics
type CaseStyle ¶
type CaseStyle string
CaseStyle represents a naming convention style
func DetectCaseStyle ¶
DetectCaseStyle determines the case style of a name
func GetExpectedStyles ¶
func GetExpectedStyles(lang Language, kind SymbolKind) []CaseStyle
GetExpectedStyles returns the expected case styles for a symbol kind in a language
type ChangeFrequencyMetadata ¶
type ChangeFrequencyMetadata struct {
// AnalyzedAt is when the analysis was performed
AnalyzedAt time.Time `json:"analyzed_at"`
// TimeWindow is the analysis period
TimeWindow string `json:"time_window"`
// WindowStart is the start of the analysis period
WindowStart time.Time `json:"window_start"`
// WindowEnd is the end of the analysis period
WindowEnd time.Time `json:"window_end"`
// CommitRange describes the analyzed commits
CommitRange string `json:"commit_range,omitempty"`
// ComputeTimeMs is how long the analysis took
ComputeTimeMs int64 `json:"compute_time_ms"`
// FromCache indicates if results were served from cache
FromCache bool `json:"from_cache"`
}
ChangeFrequencyMetadata contains analysis context
type ChangeFrequencyParams ¶
type ChangeFrequencyParams struct {
// TimeWindow specifies the analysis period (default: "30d")
TimeWindow string `json:"time_window,omitempty"`
// Granularity specifies analysis level: "file" or "symbol" (default: "file")
Granularity string `json:"granularity,omitempty"`
// Focus specifies what to analyze: "hotspots", "collisions", "patterns", "ownership", "all"
Focus []string `json:"focus,omitempty"`
// FilePattern is a glob pattern to filter files (e.g., "internal/**/*.go")
FilePattern string `json:"file_pattern,omitempty"`
// FilePath is a specific file to analyze
FilePath string `json:"file_path,omitempty"`
// SymbolName is a specific symbol to analyze (requires FilePath)
SymbolName string `json:"symbol_name,omitempty"`
// MinChanges filters out entities with fewer changes (default: 2)
MinChanges int `json:"min_changes,omitempty"`
// MinContributors filters for collision detection (default: 2)
MinContributors int `json:"min_contributors,omitempty"`
// TopN limits the number of results (default: 50)
TopN int `json:"top_n,omitempty"`
// IncludePatterns is a list of glob patterns to include (overrides default exclusions)
// If set, only files matching these patterns will be analyzed
// Example: ["*.go", "*.py", "src/**/*"]
IncludePatterns []string `json:"include_patterns,omitempty"`
// ExcludePatterns is a list of additional glob patterns to exclude
// These are added to the default exclusion list (docs, generated files, etc.)
// Example: ["*_test.go", "mocks/*", "testdata/*"]
ExcludePatterns []string `json:"exclude_patterns,omitempty"`
// SkipDefaultExclusions disables the default file exclusions
// (CHANGELOG, *.min.js, lock files, vendor/node_modules, etc.)
// Set to true to analyze all files including generated/documentation
SkipDefaultExclusions bool `json:"skip_default_exclusions,omitempty"`
}
ChangeFrequencyParams configures an on-demand frequency analysis
func DefaultChangeFrequencyParams ¶
func DefaultChangeFrequencyParams() ChangeFrequencyParams
DefaultChangeFrequencyParams returns default parameters
func (*ChangeFrequencyParams) GetGranularity ¶
func (p *ChangeFrequencyParams) GetGranularity() FrequencyGranularity
GetGranularity returns the parsed granularity
func (*ChangeFrequencyParams) GetTimeWindow ¶
func (p *ChangeFrequencyParams) GetTimeWindow() TimeWindow
GetTimeWindow returns the parsed time window
func (*ChangeFrequencyParams) HasFocus ¶
func (p *ChangeFrequencyParams) HasFocus(focus FrequencyFocus) bool
HasFocus checks if a specific focus area is enabled
type ChangeFrequencyReport ¶
type ChangeFrequencyReport struct {
// Summary provides high-level statistics
Summary ChangeFrequencySummary `json:"summary"`
// Hotspots lists the most frequently changed files/symbols
Hotspots []FileChangeFrequency `json:"hotspots,omitempty"`
// Collisions lists areas with multiple active developers
Collisions []CollisionZone `json:"collisions,omitempty"`
// AntiPatterns lists detected conflict-prone patterns
AntiPatterns []AntiPattern `json:"anti_patterns,omitempty"`
// SymbolDetails provides symbol-level analysis when requested
SymbolDetails []SymbolChangeFrequency `json:"symbol_details,omitempty"`
// Ownership provides module-level ownership information
Ownership []ModuleOwnership `json:"ownership,omitempty"`
// Metadata contains analysis context
Metadata ChangeFrequencyMetadata `json:"metadata"`
}
ChangeFrequencyReport contains the analysis results
type ChangeFrequencySummary ¶
type ChangeFrequencySummary struct {
// TotalFilesAnalyzed is the number of files examined
TotalFilesAnalyzed int `json:"total_files_analyzed"`
// TotalCommitsAnalyzed is the number of commits in the window
TotalCommitsAnalyzed int `json:"total_commits_analyzed"`
// HotspotsFound is the number of high-activity areas found
HotspotsFound int `json:"hotspots_found"`
// CollisionZones is the number of multi-developer areas found
CollisionZones int `json:"collision_zones"`
// AntiPatternsFound is the number of conflict-prone patterns detected
AntiPatternsFound int `json:"anti_patterns_found"`
// HighestChurn identifies the most volatile file
HighestChurn string `json:"highest_churn,omitempty"`
// MostActiveContributor identifies the top contributor
MostActiveContributor string `json:"most_active_contributor,omitempty"`
}
ChangeFrequencySummary provides high-level statistics
type ChangedFile ¶
type ChangedFile struct {
// Path is the current file path
Path string `json:"path"`
// OldPath is the previous path (for renames)
OldPath string `json:"old_path,omitempty"`
// Status indicates the type of change
Status FileChangeStatus `json:"status"`
// LinesAdded is the number of lines added
LinesAdded int `json:"lines_added"`
// LinesDeleted is the number of lines deleted
LinesDeleted int `json:"lines_deleted"`
}
ChangedFile represents a file affected by git changes
type ChurnFilterConfig ¶
type ChurnFilterConfig struct {
IncludePatterns []string
ExcludePatterns []string
SkipDefaultExclusions bool
}
ChurnFilterConfig holds configuration for file filtering in churn analysis
type CodeLocation ¶
type CodeLocation struct {
// FilePath is the file path
FilePath string `json:"file_path"`
// StartLine is the starting line number
StartLine int `json:"start_line"`
// EndLine is the ending line number
EndLine int `json:"end_line"`
// SymbolName is the name of the containing symbol (if applicable)
SymbolName string `json:"symbol_name,omitempty"`
// Snippet is a code snippet for context
Snippet string `json:"snippet,omitempty"`
}
CodeLocation identifies a specific location in code
type CollisionSeverity ¶
type CollisionSeverity = FindingSeverity
CollisionSeverity is an alias for FindingSeverity to maintain consistent naming Uses the same values as FindingSeverity: "critical", "warning", "info"
type CollisionZone ¶
type CollisionZone struct {
// EntityType is "file" or "symbol"
EntityType string `json:"entity_type"`
// Path is the file path
Path string `json:"path"`
// SymbolName is the symbol name (if EntityType is "symbol")
SymbolName string `json:"symbol_name,omitempty"`
// Contributors lists the developers working on this area
Contributors []ContributorActivity `json:"contributors"`
// CollisionScore is a 0-1 score indicating collision risk
CollisionScore float64 `json:"collision_score"`
// Severity categorizes the risk level
Severity CollisionSeverity `json:"severity"`
// Recommendation provides actionable guidance
Recommendation string `json:"recommendation"`
// RecentChanges is the number of changes in the last 7 days
RecentChanges int `json:"recent_changes"`
}
CollisionZone identifies areas where multiple developers are working
type CommitInfo ¶
type CommitInfo struct {
// Hash is the commit SHA
Hash string `json:"hash"`
// AuthorName is the commit author name
AuthorName string `json:"author_name"`
// AuthorEmail is the commit author email
AuthorEmail string `json:"author_email"`
// Timestamp is when the commit was made
Timestamp time.Time `json:"timestamp"`
// Message is the commit message (first line)
Message string `json:"message,omitempty"`
// FileChanges lists files changed in this commit
FileChanges []FileChange `json:"file_changes,omitempty"`
}
CommitInfo represents a parsed git commit
type ContributorActivity ¶
type ContributorActivity struct {
// AuthorName is the git author name
AuthorName string `json:"author_name"`
// AuthorEmail is the git author email
AuthorEmail string `json:"author_email"`
// ChangeCount is the number of commits by this author
ChangeCount int `json:"change_count"`
// LinesAdded is total lines added by this author
LinesAdded int `json:"lines_added"`
// LinesDeleted is total lines deleted by this author
LinesDeleted int `json:"lines_deleted"`
OwnershipShare float64 `json:"ownership_share"`
// LastChangeAt is when this author last modified the entity
LastChangeAt time.Time `json:"last_change_at"`
}
ContributorActivity tracks an author's contributions to an entity
type DiffSize ¶
type DiffSize string
DiffSize categorizes the size of a diff for report pagination
func CategorizeDiffSize ¶
func CategorizeDiffSize(files []ChangedFile) DiffSize
CategorizeDiffSize determines the diff size category
type DiffStats ¶
type DiffStats struct {
FilesAdded int `json:"files_added"`
FilesModified int `json:"files_modified"`
FilesDeleted int `json:"files_deleted"`
FilesRenamed int `json:"files_renamed"`
TotalAdded int `json:"total_lines_added"`
TotalDeleted int `json:"total_lines_deleted"`
}
DiffStats provides summary statistics for a diff
type DuplicateFinding ¶
type DuplicateFinding struct {
// Severity indicates the importance
Severity FindingSeverity `json:"severity"`
// Description provides a human-readable summary
Description string `json:"description"`
// NewCode is the location in the changed code
NewCode CodeLocation `json:"new_code"`
// ExistingCode is the location in the existing codebase
ExistingCode CodeLocation `json:"existing_code"`
// Similarity is the similarity score (0.0-1.0)
Similarity float64 `json:"similarity"`
// Type indicates exact, structural, or semantic duplicate
Type string `json:"type"`
// Suggestion provides actionable advice
Suggestion string `json:"suggestion"`
}
DuplicateFinding represents detected duplicate code
type FileChange ¶
type FileChange struct {
// Path is the file path
Path string `json:"path"`
// OldPath is the previous path (for renames)
OldPath string `json:"old_path,omitempty"`
// LinesAdded is the number of lines added
LinesAdded int `json:"lines_added"`
// LinesDeleted is the number of lines deleted
LinesDeleted int `json:"lines_deleted"`
// Status is the change type (A/M/D/R)
Status string `json:"status"`
}
FileChange represents a file modification in a commit
type FileChangeFrequency ¶
type FileChangeFrequency struct {
// FilePath is the path to the file
FilePath string `json:"file_path"`
// Metrics contains frequency data per time window
Metrics map[TimeWindow]*FrequencyMetrics `json:"metrics"`
// Contributors lists authors and their activity
Contributors []ContributorActivity `json:"contributors"`
// AntiPatterns lists detected conflict-prone patterns
AntiPatterns []AntiPattern `json:"anti_patterns,omitempty"`
// LineCount is the current line count of the file
LineCount int `json:"line_count,omitempty"`
}
FileChangeFrequency tracks how often a file changes over time
type FileChangeStatus ¶
type FileChangeStatus string
FileChangeStatus indicates the type of change to a file
const ( FileStatusAdded FileChangeStatus = "added" FileStatusModified FileChangeStatus = "modified" FileStatusDeleted FileChangeStatus = "deleted" FileStatusRenamed FileChangeStatus = "renamed" FileStatusCopied FileChangeStatus = "copied" )
type FindingSeverity ¶
type FindingSeverity string
FindingSeverity indicates the importance of a finding
const ( // SeverityCritical indicates a must-fix issue SeverityCritical FindingSeverity = "critical" // SeverityWarning indicates a should-consider issue SeverityWarning FindingSeverity = "warning" // SeverityInfo indicates a nice-to-know item SeverityInfo FindingSeverity = "info" )
func DetermineCollisionSeverity ¶
func DetermineCollisionSeverity(score float64) FindingSeverity
DetermineCollisionSeverity maps a collision score to severity
func DetermineDuplicateSeverity ¶
func DetermineDuplicateSeverity(similarity float64, lineCount int) FindingSeverity
DetermineDuplicateSeverity determines severity based on similarity and size
func DetermineMetricsSeverity ¶ added in v0.4.0
func DetermineMetricsSeverity(issueType MetricsIssueType, metrics SymbolMetrics, thresholds MetricsThresholds) FindingSeverity
DetermineMetricsSeverity determines severity based on metrics thresholds
func DetermineNamingSeverity ¶
func DetermineNamingSeverity(issueType NamingIssueType, similarity float64) FindingSeverity
DetermineNamingSeverity determines severity based on issue type and context
type FrequencyAnalyzer ¶
type FrequencyAnalyzer struct {
// contains filtered or unexported fields
}
FrequencyAnalyzer performs change frequency analysis
func NewFrequencyAnalyzer ¶
func NewFrequencyAnalyzer(provider *Provider) *FrequencyAnalyzer
NewFrequencyAnalyzer creates a new frequency analyzer
func (*FrequencyAnalyzer) Analyze ¶
func (a *FrequencyAnalyzer) Analyze(ctx context.Context, params ChangeFrequencyParams) (*ChangeFrequencyReport, error)
Analyze performs change frequency analysis based on parameters
func (*FrequencyAnalyzer) AnalyzeFile ¶
func (a *FrequencyAnalyzer) AnalyzeFile(ctx context.Context, filePath string, window TimeWindow) (*FileChangeFrequency, error)
AnalyzeFile performs focused analysis on a single file
func (*FrequencyAnalyzer) GetCollisionRisk ¶
func (a *FrequencyAnalyzer) GetCollisionRisk(ctx context.Context, filePath string) (*CollisionZone, error)
GetCollisionRisk checks collision risk for a specific file
type FrequencyCache ¶
type FrequencyCache struct {
// contains filtered or unexported fields
}
FrequencyCache provides lightweight in-memory caching for frequency analysis Uses sync.Map for lock-free concurrent access
func NewFrequencyCache ¶
func NewFrequencyCache(ttl time.Duration) *FrequencyCache
NewFrequencyCache creates a new cache with the specified TTL
func (*FrequencyCache) Clear ¶
func (c *FrequencyCache) Clear()
Clear removes all entries from the cache
func (*FrequencyCache) Delete ¶
func (c *FrequencyCache) Delete(key string)
Delete removes a value from the cache
func (*FrequencyCache) Get ¶
func (c *FrequencyCache) Get(key string) (interface{}, bool)
Get retrieves a value from the cache
func (*FrequencyCache) GetFileFrequency ¶
func (c *FrequencyCache) GetFileFrequency(filePath string, window TimeWindow) (*FileChangeFrequency, bool)
GetFileFrequency retrieves cached file frequency data
func (*FrequencyCache) GetOrCompute ¶
func (c *FrequencyCache) GetOrCompute(key string, compute func() (interface{}, error)) (interface{}, error)
GetOrCompute retrieves from cache or computes and caches the result
func (*FrequencyCache) GetReport ¶
func (c *FrequencyCache) GetReport(pattern string, window TimeWindow) (*ChangeFrequencyReport, bool)
GetReport retrieves a cached analysis report
func (*FrequencyCache) InvalidateFile ¶
func (c *FrequencyCache) InvalidateFile(filePath string)
InvalidateFile removes all cached data for a file
func (*FrequencyCache) InvalidatePattern ¶
func (c *FrequencyCache) InvalidatePattern(pattern string)
InvalidatePattern removes cached data for a pattern
func (*FrequencyCache) Set ¶
func (c *FrequencyCache) Set(key string, data interface{})
Set stores a value in the cache
func (*FrequencyCache) SetFileFrequency ¶
func (c *FrequencyCache) SetFileFrequency(filePath string, window TimeWindow, freq *FileChangeFrequency)
SetFileFrequency caches file frequency data
func (*FrequencyCache) SetReport ¶
func (c *FrequencyCache) SetReport(pattern string, window TimeWindow, report *ChangeFrequencyReport)
SetReport caches an analysis report
func (*FrequencyCache) SetWithTTL ¶
func (c *FrequencyCache) SetWithTTL(key string, data interface{}, ttl time.Duration)
SetWithTTL stores a value with a custom TTL
func (*FrequencyCache) Stats ¶
func (c *FrequencyCache) Stats() CacheStats
Stats returns cache statistics
func (*FrequencyCache) Warm ¶
func (c *FrequencyCache) Warm(entries map[string]interface{})
Warm pre-populates the cache with frequently accessed data
type FrequencyFocus ¶
type FrequencyFocus string
FrequencyFocus defines what aspects to analyze
const ( // FocusHotspots identifies frequently changing areas FocusHotspots FrequencyFocus = "hotspots" // FocusCollisions identifies multi-developer edit zones FocusCollisions FrequencyFocus = "collisions" // FocusPatterns identifies conflict-prone anti-patterns FocusPatterns FrequencyFocus = "patterns" // FocusOwnership analyzes code ownership FocusOwnership FrequencyFocus = "ownership" // FocusAll enables all analysis types FocusAll FrequencyFocus = "all" )
type FrequencyGranularity ¶
type FrequencyGranularity string
FrequencyGranularity defines the level of analysis detail
const ( // GranularityFile analyzes at file level (cheapest) GranularityFile FrequencyGranularity = "file" // GranularitySymbol analyzes at symbol level (moderate cost) GranularitySymbol FrequencyGranularity = "symbol" )
type FrequencyMetrics ¶
type FrequencyMetrics struct {
// ChangeCount is the number of commits touching this entity
ChangeCount int `json:"change_count"`
// LinesAdded is the total lines added in the time window
LinesAdded int `json:"lines_added"`
// LinesDeleted is the total lines deleted in the time window
LinesDeleted int `json:"lines_deleted"`
// UniqueAuthors is the number of distinct contributors
UniqueAuthors int `json:"unique_authors"`
// FirstChangeAt is the earliest change in the window
FirstChangeAt time.Time `json:"first_change_at,omitempty"`
// LastChangeAt is the most recent change in the window
LastChangeAt time.Time `json:"last_change_at,omitempty"`
// ChangeRate is the number of changes per day
ChangeRate float64 `json:"change_rate"`
// VolatilityScore is a 0-1 score indicating how volatile this entity is
// Higher values indicate more frequent, larger changes by multiple authors
VolatilityScore float64 `json:"volatility_score"`
}
FrequencyMetrics provides change statistics for any granularity level
type HistoryProvider ¶
type HistoryProvider struct {
*Provider
}
HistoryProvider extends Provider with change frequency analysis methods
func NewHistoryProvider ¶
func NewHistoryProvider(p *Provider) *HistoryProvider
NewHistoryProvider creates a HistoryProvider from an existing Provider
func (*HistoryProvider) AggregateFileStats ¶
func (h *HistoryProvider) AggregateFileStats(commits []CommitInfo, filePath string, window TimeWindow) *FileChangeFrequency
AggregateFileStats aggregates commit data into FileChangeFrequency
func (*HistoryProvider) GetCommitHistory ¶
func (h *HistoryProvider) GetCommitHistory(ctx context.Context, since time.Time, paths ...string) ([]CommitInfo, error)
GetCommitHistory returns commits within a time window Uses: git log --numstat --format="%H|%an|%ae|%at" --since="<time>"
func (*HistoryProvider) GetCurrentAuthor ¶
func (h *HistoryProvider) GetCurrentAuthor(ctx context.Context) (name, email string, err error)
GetCurrentAuthor returns the current git user
func (*HistoryProvider) GetFileContributors ¶
func (h *HistoryProvider) GetFileContributors(ctx context.Context, filePath string, since time.Time) ([]ContributorActivity, error)
GetFileContributors returns contributor statistics for a file Uses: git shortlog -sne -- <path>
func (*HistoryProvider) GetFileHistory ¶
func (h *HistoryProvider) GetFileHistory(ctx context.Context, filePath string, since time.Time) ([]CommitInfo, error)
GetFileHistory returns commit history for a specific file
func (*HistoryProvider) GetRecentCommitCount ¶
func (h *HistoryProvider) GetRecentCommitCount(ctx context.Context, filePath string, window time.Duration) (int, error)
GetRecentCommitCount returns the number of commits in a time window
func (*HistoryProvider) GetRepoHistory ¶
func (h *HistoryProvider) GetRepoHistory(ctx context.Context, since time.Time, pattern string) ([]CommitInfo, error)
GetRepoHistory returns aggregate history for the entire repository
func (*HistoryProvider) GetSymbolHistory ¶
func (h *HistoryProvider) GetSymbolHistory(ctx context.Context, filePath string, startLine, endLine int, since time.Time) ([]CommitInfo, error)
GetSymbolHistory returns commit history for a specific line range (symbol) Uses: git log -L <start>,<end>:<path> --format="%H|%an|%ae|%at" Note: This is more expensive than file-level history
type Language ¶
type Language string
Language represents a programming language for naming conventions
const ( LangGo Language = "go" LangJavaScript Language = "javascript" LangTypeScript Language = "typescript" LangPython Language = "python" LangRust Language = "rust" LangJava Language = "java" LangCSharp Language = "csharp" LangCpp Language = "cpp" LangC Language = "c" LangPHP Language = "php" LangRuby Language = "ruby" LangSwift Language = "swift" LangKotlin Language = "kotlin" LangScala Language = "scala" LangZig Language = "zig" LangUnknown Language = "unknown" )
func GetLanguageFromPath ¶
GetLanguageFromPath returns the language based on file extension
type MetricsFinding ¶ added in v0.4.0
type MetricsFinding struct {
// Severity indicates how critical this finding is
Severity FindingSeverity `json:"severity"`
// Description is a human-readable description of the issue
Description string `json:"description"`
// Symbol is the function/method with the metrics issue
Symbol SymbolInfo `json:"symbol"`
// IssueType categorizes the metrics problem
IssueType MetricsIssueType `json:"issue_type"`
// Issue is a short issue summary
Issue string `json:"issue"`
// Suggestion provides guidance on fixing the issue
Suggestion string `json:"suggestion"`
// OldMetrics contains the previous metrics (for modified symbols)
OldMetrics *SymbolMetrics `json:"old_metrics,omitempty"`
// NewMetrics contains the current metrics
NewMetrics *SymbolMetrics `json:"new_metrics,omitempty"`
}
MetricsFinding represents a metrics-related issue in changed code
type MetricsIssueType ¶ added in v0.4.0
type MetricsIssueType string
MetricsIssueType categorizes function metrics issues
const ( // MetricsIssueHighComplexity indicates cyclomatic complexity exceeds threshold MetricsIssueHighComplexity MetricsIssueType = "high_complexity" // MetricsIssueLongFunction indicates function has too many lines MetricsIssueLongFunction MetricsIssueType = "long_function" // MetricsIssueDeepNesting indicates excessive nesting depth MetricsIssueDeepNesting MetricsIssueType = "deep_nesting" // MetricsIssueComplexityGrew indicates complexity increased significantly MetricsIssueComplexityGrew MetricsIssueType = "complexity_grew" // MetricsIssuePurityLost indicates a previously pure function became impure MetricsIssuePurityLost MetricsIssueType = "purity_lost" // MetricsIssueImpureFunction indicates a new function has side effects MetricsIssueImpureFunction MetricsIssueType = "impure_function" )
type MetricsThresholds ¶ added in v0.4.0
type MetricsThresholds struct {
// HighComplexity is the cyclomatic complexity threshold (default: 10)
HighComplexity int
// LongFunction is the lines of code threshold (default: 100)
LongFunction int
// DeepNesting is the nesting depth threshold (default: 4)
DeepNesting int
// ComplexityGrowthThreshold is the percentage increase to flag (default: 50)
ComplexityGrowthThreshold int
}
MetricsThresholds defines thresholds for metrics analysis
func DefaultMetricsThresholds ¶ added in v0.4.0
func DefaultMetricsThresholds() MetricsThresholds
DefaultMetricsThresholds returns sensible defaults for metrics analysis
type ModuleOwnership ¶
type ModuleOwnership struct {
// ModulePath is the directory path
ModulePath string `json:"module_path"`
// PrimaryOwner is the main contributor
PrimaryOwner ContributorActivity `json:"primary_owner"`
// SecondaryOwners are other significant contributors
SecondaryOwners []ContributorActivity `json:"secondary_owners,omitempty"`
// TotalChanges is the total change count in this module
TotalChanges int `json:"total_changes"`
// FileCount is the number of files in this module
FileCount int `json:"file_count"`
}
ModuleOwnership provides ownership information at directory/module level
type NamingConvention ¶
type NamingConvention struct {
// ExpectedStyles maps symbol kinds to their expected case styles
// Multiple styles means any of them is acceptable
ExpectedStyles map[SymbolKind][]CaseStyle
// Description provides human-readable explanation
Description string
}
NamingConvention defines expected case styles for a language
type NamingFinding ¶
type NamingFinding struct {
// Severity indicates the importance
Severity FindingSeverity `json:"severity"`
// Description provides a human-readable summary
Description string `json:"description"`
// NewSymbol is the symbol with the naming issue
NewSymbol SymbolInfo `json:"new_symbol"`
// SimilarNames are existing symbols with similar names
SimilarNames []SymbolInfo `json:"similar_names"`
// IssueType categorizes the naming issue
IssueType NamingIssueType `json:"issue_type"`
// Issue provides details about the problem
Issue string `json:"issue"`
// Suggestion provides the recommended name
Suggestion string `json:"suggestion"`
}
NamingFinding represents a naming consistency issue
type NamingIssueType ¶
type NamingIssueType string
NamingIssueType categorizes naming consistency issues
const ( // NamingIssueCaseMismatch indicates camelCase vs PascalCase vs snake_case mismatch NamingIssueCaseMismatch NamingIssueType = "case_mismatch" // NamingIssueSimilarExists indicates similar names already exist in codebase NamingIssueSimilarExists NamingIssueType = "similar_exists" // NamingIssueAbbreviation indicates abbreviation inconsistency (getUsr vs getUser) NamingIssueAbbreviation NamingIssueType = "abbreviation" )
type PatternDetector ¶
type PatternDetector struct {
// Configurable thresholds
RegistrationCallsThreshold int
EnumValuesThreshold int
GodObjectLinesThreshold int
SwitchCasesThreshold int
ConfigFieldsThreshold int
BarrelExportRatioThreshold float64
}
PatternDetector identifies conflict-prone code patterns
func NewPatternDetector ¶
func NewPatternDetector() *PatternDetector
NewPatternDetector creates a pattern detector with default thresholds
func (*PatternDetector) AnalyzeFileForPatterns ¶
func (d *PatternDetector) AnalyzeFileForPatterns(content []byte, filePath string, contributors []ContributorActivity) []AntiPattern
AnalyzeFileForPatterns is a convenience method to analyze a file
func (*PatternDetector) DetectPatterns ¶
func (d *PatternDetector) DetectPatterns(content []byte, filePath string) []AntiPattern
DetectPatterns analyzes file content for conflict-prone patterns
func (*PatternDetector) DetectPatternsFromReader ¶
func (d *PatternDetector) DetectPatternsFromReader(content []byte, filePath string) []AntiPattern
DetectPatternsFromReader analyzes content from a reader
func (*PatternDetector) QuickScan ¶
func (d *PatternDetector) QuickScan(content []byte, filePath string) *AntiPattern
QuickScan performs a fast scan looking only for the most impactful patterns
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider wraps git commands to extract file states at different refs
func NewProvider ¶
NewProvider creates a new git provider for the specified repository
func (*Provider) GetBaseRef ¶
GetBaseRef determines the appropriate base reference for a scope
func (*Provider) GetChangedFiles ¶
func (p *Provider) GetChangedFiles(ctx context.Context, params AnalysisParams) ([]ChangedFile, error)
GetChangedFiles returns the list of changed files based on analysis scope
func (*Provider) GetCommitHash ¶
GetCommitHash returns the full commit hash for a reference
func (*Provider) GetCurrentBranch ¶
GetCurrentBranch returns the current branch name
func (*Provider) GetDiffStats ¶
GetDiffStats returns statistics about the diff
func (*Provider) GetFileContent ¶
GetFileContent returns the content of a file at a specific ref If ref is empty, returns the working tree version
func (*Provider) GetRepoRoot ¶
GetRepoRoot returns the repository root path
func (*Provider) GetTargetRef ¶
func (p *Provider) GetTargetRef(params AnalysisParams) string
GetTargetRef determines the appropriate target reference for a scope
type ReportMetadata ¶
type ReportMetadata struct {
// BaseRef is the base reference used
BaseRef string `json:"base_ref"`
// TargetRef is the target reference used
TargetRef string `json:"target_ref"`
// Scope is the analysis scope
Scope AnalysisScope `json:"scope"`
// AnalyzedAt is when the analysis was performed
AnalyzedAt time.Time `json:"analyzed_at"`
// AnalysisTimeMs is how long the analysis took
AnalysisTimeMs int64 `json:"analysis_time_ms"`
// Truncated indicates if findings were limited
Truncated bool `json:"truncated,omitempty"`
// TotalDuplicates is the actual count before truncation
TotalDuplicates int `json:"total_duplicates,omitempty"`
// TotalNamingIssues is the actual count before truncation
TotalNamingIssues int `json:"total_naming_issues,omitempty"`
// TotalMetricsIssues is the actual count before truncation
TotalMetricsIssues int `json:"total_metrics_issues,omitempty"`
}
ReportMetadata provides context about the analysis
type ReportSummary ¶
type ReportSummary struct {
// FilesChanged is the number of files with changes
FilesChanged int `json:"files_changed"`
// SymbolsAdded is the count of new symbols
SymbolsAdded int `json:"symbols_added"`
// SymbolsModified is the count of modified symbols
SymbolsModified int `json:"symbols_modified"`
// SymbolsDeleted is the count of deleted symbols
SymbolsDeleted int `json:"symbols_deleted"`
// DuplicatesFound is the count of duplicate findings
DuplicatesFound int `json:"duplicates_found"`
// NamingIssuesFound is the count of naming issues
NamingIssuesFound int `json:"naming_issues_found"`
// MetricsIssuesFound is the count of function metrics issues
MetricsIssuesFound int `json:"metrics_issues_found"`
// RiskScore indicates overall risk (0.0 = safe, 1.0 = risky)
RiskScore float64 `json:"risk_score"`
// TopRecommendation is the highest priority suggestion
TopRecommendation string `json:"top_recommendation,omitempty"`
}
ReportSummary provides high-level statistics about the analysis
type SymbolChangeFrequency ¶
type SymbolChangeFrequency struct {
// SymbolName is the name of the function/class/etc
SymbolName string `json:"symbol_name"`
// SymbolType is the kind of symbol (function, class, method, etc)
SymbolType string `json:"symbol_type"`
// FilePath is the file containing the symbol
FilePath string `json:"file_path"`
// StartLine is the current starting line of the symbol
StartLine int `json:"start_line"`
// EndLine is the current ending line of the symbol
EndLine int `json:"end_line"`
// Metrics contains frequency data per time window
Metrics map[TimeWindow]*FrequencyMetrics `json:"metrics"`
// Contributors lists authors and their activity on this symbol
Contributors []ContributorActivity `json:"contributors"`
}
SymbolChangeFrequency tracks how often a symbol changes
type SymbolDiff ¶
type SymbolDiff struct {
Added []SymbolInfo `json:"added"`
Removed []SymbolInfo `json:"removed"`
Modified []SymbolInfo `json:"modified"`
}
SymbolDiff represents the difference in symbols between two indexes
type SymbolInfo ¶
type SymbolInfo struct {
// Name is the symbol name
Name string `json:"name"`
// Type is the symbol type (function, class, etc.) as a string
Type string `json:"type"`
// FilePath is the file containing the symbol
FilePath string `json:"file_path"`
// Line is the line number
Line int `json:"line"`
// EndLine is the ending line number
EndLine int `json:"end_line,omitempty"`
// Complexity is the cyclomatic complexity (if available)
Complexity int `json:"complexity,omitempty"`
// LinesOfCode is the number of lines in the function/method
LinesOfCode int `json:"lines_of_code,omitempty"`
// NestingDepth is the maximum nesting depth
NestingDepth int `json:"nesting_depth,omitempty"`
// IsPure indicates if the function has no side effects
IsPure bool `json:"is_pure,omitempty"`
// SideEffects lists the detected side effect categories (e.g., "param-write", "io", "global-write")
SideEffects []string `json:"side_effects,omitempty"`
// Content is the symbol's code content (for duplicate detection)
Content string `json:"-"`
}
SymbolInfo provides details about a symbol for analysis
type SymbolKind ¶
type SymbolKind string
SymbolKind categorizes symbols for naming convention purposes
const ( KindFunction SymbolKind = "function" KindMethod SymbolKind = "method" KindClass SymbolKind = "class" KindInterface SymbolKind = "interface" KindStruct SymbolKind = "struct" KindType SymbolKind = "type" KindConstant SymbolKind = "constant" KindVariable SymbolKind = "variable" KindField SymbolKind = "field" KindEnum SymbolKind = "enum" KindEnumMember SymbolKind = "enum_member" KindModule SymbolKind = "module" KindNamespace SymbolKind = "namespace" KindProperty SymbolKind = "property" KindUnknownKind SymbolKind = "unknown" )
func SymbolTypeToKind ¶
func SymbolTypeToKind(symbolType string) SymbolKind
SymbolTypeToKind converts a symbol type string to SymbolKind
type SymbolMetrics ¶ added in v0.4.0
type SymbolMetrics struct {
Complexity int `json:"complexity"`
LinesOfCode int `json:"lines_of_code"`
NestingDepth int `json:"nesting_depth"`
IsPure bool `json:"is_pure,omitempty"`
SideEffects []string `json:"side_effects,omitempty"`
}
SymbolMetrics captures metrics for a function/method
type TimeWindow ¶
type TimeWindow string
TimeWindow represents fixed analysis periods for change frequency
const ( // Window7Days analyzes the last 7 days of history Window7Days TimeWindow = "7d" // Window30Days analyzes the last 30 days of history Window30Days TimeWindow = "30d" // Window90Days analyzes the last 90 days of history Window90Days TimeWindow = "90d" // Window1Year analyzes the last year of history Window1Year TimeWindow = "1y" )
func ParseTimeWindow ¶
func ParseTimeWindow(s string) TimeWindow
ParseTimeWindow parses a string to TimeWindow