Skip to content

tenets.core.examiner Package

Code examination and inspection package.

This package provides comprehensive code analysis capabilities including metrics calculation, complexity analysis, ownership tracking, and hotspot detection. It extracts the core examination logic from CLI commands to provide a reusable, testable API.

The examiner package works in conjunction with the analyzer package, adding higher-level insights and aggregations on top of basic file analysis.

Main components: - Examiner: Main orchestrator for code examination - MetricsCalculator: Calculate code metrics and statistics - ComplexityAnalyzer: Analyze code complexity patterns - OwnershipTracker: Track code ownership and contribution patterns - HotspotDetector: Identify frequently changed or problematic areas

Example usage

from tenets.core.examiner import Examiner from tenets.config import TenetsConfig

config = TenetsConfig() examiner = Examiner(config)

Comprehensive examination

results = examiner.examine_project( ... path=Path("./src"), ... deep=True, ... include_git=True ... )

print(f"Total files: {results.total_files}") print(f"Average complexity: {results.metrics.avg_complexity}") print(f"Top contributors: {results.ownership.top_contributors}")

Classes

ComplexityAnalyzer

Python
ComplexityAnalyzer(config: TenetsConfig)

Analyzer for code complexity metrics.

Provides comprehensive complexity analysis including cyclomatic complexity, cognitive complexity, and various other metrics to assess code maintainability and identify refactoring opportunities.

ATTRIBUTEDESCRIPTION
config

Configuration object

logger

Logger instance

complexity_cache

Cache of computed complexities

TYPE:Dict[str, Any]

Initialize complexity analyzer.

PARAMETERDESCRIPTION
config

TenetsConfig instance

TYPE:TenetsConfig

Attributes

configinstance-attribute
Python
config = config
loggerinstance-attribute
Python
logger = get_logger(__name__)
complexity_cacheinstance-attribute
Python
complexity_cache: Dict[str, Any] = {}

Functions

analyze
Python
analyze(files: List[Any], threshold: float = 10.0, deep: bool = False) -> ComplexityReport

Analyze complexity for a list of files.

Performs comprehensive complexity analysis across all provided files, calculating various metrics and identifying problem areas.

PARAMETERDESCRIPTION
files

List of analyzed file objects

TYPE:List[Any]

threshold

Complexity threshold for flagging

TYPE:floatDEFAULT:10.0

deep

Whether to perform deep analysis

TYPE:boolDEFAULT:False

RETURNSDESCRIPTION
ComplexityReport

Comprehensive complexity analysis

TYPE:ComplexityReport

Example

analyzer = ComplexityAnalyzer(config) report = analyzer.analyze(files, threshold=10) print(f"Average complexity: {report.avg_complexity}")

analyze_file
Python
analyze_file(file_analysis: Any) -> Dict[str, Any]

Analyze complexity for a single file.

PARAMETERDESCRIPTION
file_analysis

Analyzed file object

TYPE:Any

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: File complexity details

ComplexityReportdataclass

Python
ComplexityReport(total_files: int = 0, total_functions: int = 0, total_classes: int = 0, avg_complexity: float = 0.0, max_complexity: int = 0, median_complexity: float = 0.0, std_dev_complexity: float = 0.0, high_complexity_count: int = 0, very_high_complexity_count: int = 0, files: List[FileComplexity] = list(), top_complex_functions: List[FunctionComplexity] = list(), top_complex_classes: List[ClassComplexity] = list(), top_complex_files: List[FileComplexity] = list(), complexity_distribution: Dict[str, int] = dict(), refactoring_candidates: List[Dict[str, Any]] = list(), technical_debt_hours: float = 0.0, trend_direction: str = 'stable', recommendations: List[str] = list(), _override_complexity_score: Optional[float] = None)

Comprehensive complexity analysis report.

Aggregates complexity analysis across an entire codebase, providing statistics, trends, and actionable insights.

ATTRIBUTEDESCRIPTION
total_files

Total files analyzed

TYPE:int

total_functions

Total functions analyzed

TYPE:int

total_classes

Total classes analyzed

TYPE:int

avg_complexity

Average cyclomatic complexity

TYPE:float

max_complexity

Maximum cyclomatic complexity found

TYPE:int

median_complexity

Median cyclomatic complexity

TYPE:float

std_dev_complexity

Standard deviation of complexity

TYPE:float

high_complexity_count

Count of high complexity items

TYPE:int

very_high_complexity_count

Count of very high complexity items

TYPE:int

files

List of file complexity analyses

TYPE:List[FileComplexity]

top_complex_functions

Most complex functions

TYPE:List[FunctionComplexity]

top_complex_classes

Most complex classes

TYPE:List[ClassComplexity]

top_complex_files

Most complex files

TYPE:List[FileComplexity]

complexity_distribution

Distribution of complexity values

TYPE:Dict[str, int]

refactoring_candidates

Items recommended for refactoring

TYPE:List[Dict[str, Any]]

technical_debt_hours

Estimated hours to address complexity

TYPE:float

trend_direction

Whether complexity is increasing/decreasing

TYPE:str

recommendations

List of actionable recommendations

TYPE:List[str]

Attributes

total_filesclass-attributeinstance-attribute
Python
total_files: int = 0
total_functionsclass-attributeinstance-attribute
Python
total_functions: int = 0
total_classesclass-attributeinstance-attribute
Python
total_classes: int = 0
avg_complexityclass-attributeinstance-attribute
Python
avg_complexity: float = 0.0
max_complexityclass-attributeinstance-attribute
Python
max_complexity: int = 0
median_complexityclass-attributeinstance-attribute
Python
median_complexity: float = 0.0
std_dev_complexityclass-attributeinstance-attribute
Python
std_dev_complexity: float = 0.0
high_complexity_countclass-attributeinstance-attribute
Python
high_complexity_count: int = 0
very_high_complexity_countclass-attributeinstance-attribute
Python
very_high_complexity_count: int = 0
filesclass-attributeinstance-attribute
Python
files: List[FileComplexity] = field(default_factory=list)
top_complex_functionsclass-attributeinstance-attribute
Python
top_complex_functions: List[FunctionComplexity] = field(default_factory=list)
top_complex_classesclass-attributeinstance-attribute
Python
top_complex_classes: List[ClassComplexity] = field(default_factory=list)
top_complex_filesclass-attributeinstance-attribute
Python
top_complex_files: List[FileComplexity] = field(default_factory=list)
complexity_distributionclass-attributeinstance-attribute
Python
complexity_distribution: Dict[str, int] = field(default_factory=dict)
refactoring_candidatesclass-attributeinstance-attribute
Python
refactoring_candidates: List[Dict[str, Any]] = field(default_factory=list)
technical_debt_hoursclass-attributeinstance-attribute
Python
technical_debt_hours: float = 0.0
trend_directionclass-attributeinstance-attribute
Python
trend_direction: str = 'stable'
recommendationsclass-attributeinstance-attribute
Python
recommendations: List[str] = field(default_factory=list)
complexity_scoreproperty
Python
complexity_score: float

Calculate overall complexity score (0-100).

Lower scores indicate better (less complex) code.

RETURNSDESCRIPTION
float

Complexity score

TYPE:float

Functions

to_dict
Python
to_dict() -> Dict[str, Any]

Convert report to dictionary.

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dictionary representation

ExaminationResultdataclass

Python
ExaminationResult(root_path: Path, total_files: int = 0, total_lines: int = 0, languages: List[str] = list(), files: List[Any] = list(), metrics: Optional[MetricsReport] = None, complexity: Optional[ComplexityReport] = None, ownership: Optional[OwnershipReport] = None, hotspots: Optional[HotspotReport] = None, git_analysis: Optional[Any] = None, summary: Dict[str, Any] = dict(), timestamp: datetime = datetime.now(), duration: float = 0.0, config: Optional[TenetsConfig] = None, errors: List[str] = list(), excluded_files: List[str] = list(), excluded_count: int = 0, ignored_patterns: List[str] = list())

Comprehensive examination results for a codebase.

This dataclass aggregates all examination findings including metrics, complexity analysis, ownership patterns, and detected hotspots. It provides a complete picture of codebase health and structure.

ATTRIBUTEDESCRIPTION
root_path

Root directory that was examined

TYPE:Path

total_files

Total number of files analyzed

TYPE:int

total_lines

Total lines of code across all files

TYPE:int

languages

List of programming languages detected

TYPE:List[str]

files

List of analyzed file objects

TYPE:List[Any]

metrics

Detailed metrics report

TYPE:Optional[MetricsReport]

complexity

Complexity analysis report

TYPE:Optional[ComplexityReport]

ownership

Code ownership report

TYPE:Optional[OwnershipReport]

hotspots

Detected hotspot report

TYPE:Optional[HotspotReport]

git_analysis

Git repository analysis if available

TYPE:Optional[Any]

summary

High-level summary statistics

TYPE:Dict[str, Any]

timestamp

When examination was performed

TYPE:datetime

duration

How long examination took in seconds

TYPE:float

config

Configuration used for examination

TYPE:Optional[TenetsConfig]

errors

Any errors encountered during examination

TYPE:List[str]

Attributes

root_pathinstance-attribute
Python
root_path: Path
total_filesclass-attributeinstance-attribute
Python
total_files: int = 0
total_linesclass-attributeinstance-attribute
Python
total_lines: int = 0
languagesclass-attributeinstance-attribute
Python
languages: List[str] = field(default_factory=list)
filesclass-attributeinstance-attribute
Python
files: List[Any] = field(default_factory=list)
metricsclass-attributeinstance-attribute
Python
metrics: Optional[MetricsReport] = None
complexityclass-attributeinstance-attribute
Python
complexity: Optional[ComplexityReport] = None
ownershipclass-attributeinstance-attribute
Python
ownership: Optional[OwnershipReport] = None
hotspotsclass-attributeinstance-attribute
Python
hotspots: Optional[HotspotReport] = None
git_analysisclass-attributeinstance-attribute
Python
git_analysis: Optional[Any] = None
summaryclass-attributeinstance-attribute
Python
summary: Dict[str, Any] = field(default_factory=dict)
timestampclass-attributeinstance-attribute
Python
timestamp: datetime = field(default_factory=now)
durationclass-attributeinstance-attribute
Python
duration: float = 0.0
configclass-attributeinstance-attribute
Python
config: Optional[TenetsConfig] = None
errorsclass-attributeinstance-attribute
Python
errors: List[str] = field(default_factory=list)
excluded_filesclass-attributeinstance-attribute
Python
excluded_files: List[str] = field(default_factory=list)
excluded_countclass-attributeinstance-attribute
Python
excluded_count: int = 0
ignored_patternsclass-attributeinstance-attribute
Python
ignored_patterns: List[str] = field(default_factory=list)
has_issuesproperty
Python
has_issues: bool

Check if examination found any issues.

RETURNSDESCRIPTION
bool

True if any issues were detected

TYPE:bool

health_scoreproperty
Python
health_score: float

Calculate overall codebase health score.

Computes a health score from 0-100 based on various metrics including complexity, test coverage, documentation, and hotspots.

RETURNSDESCRIPTION
float

Health score between 0 and 100

TYPE:float

Functions

to_dict
Python
to_dict() -> Dict[str, Any]

Convert examination results to dictionary.

Serializes all examination data into a dictionary format suitable for JSON export or further processing. Handles nested objects and datetime serialization.

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dictionary representation of examination results

to_json
Python
to_json(indent: int = 2) -> str

Convert examination results to JSON string.

PARAMETERDESCRIPTION
indent

Number of spaces for JSON indentation

TYPE:intDEFAULT:2

RETURNSDESCRIPTION
str

JSON representation of examination results

TYPE:str

Examiner

Python
Examiner(config: TenetsConfig)

Main orchestrator for code examination operations.

The Examiner class coordinates all examination activities, managing the analysis pipeline from file discovery through final reporting. It integrates various analyzers and trackers to provide comprehensive codebase insights.

This class serves as the primary API for examination functionality, handling configuration, error recovery, and result aggregation.

ATTRIBUTEDESCRIPTION
config

Configuration object

logger

Logger instance

analyzer

Code analyzer instance

TYPE:CodeAnalyzer

scanner

File scanner instance

metrics_calculator

Metrics calculation instance

complexity_analyzer

Complexity analysis instance

ownership_tracker

Ownership tracking instance

hotspot_detector

Hotspot detection instance

Initialize the Examiner with configuration.

Sets up all required components for examination including analyzers, scanners, and specialized examination modules.

PARAMETERDESCRIPTION
config

TenetsConfig instance with examination settings

TYPE:TenetsConfig

Attributes

analyzerpropertywritable
Python
analyzer: CodeAnalyzer
configinstance-attribute
Python
config = config
loggerinstance-attribute
Python
logger = get_logger(__name__)
scannerinstance-attribute
Python
scanner = FileScanner(config)
metrics_calculatorinstance-attribute
Python
metrics_calculator = MetricsCalculator(config)
complexity_analyzerinstance-attribute
Python
complexity_analyzer = ComplexityAnalyzer(config)
ownership_trackerinstance-attribute
Python
ownership_tracker = OwnershipTracker(config)
hotspot_detectorinstance-attribute
Python
hotspot_detector = HotspotDetector(config)
cacheinstance-attribute
Python
cache = CacheManager(config)

Functions

examine_project
Python
examine_project(path: Path, deep: bool = False, include_git: bool = True, include_metrics: bool = True, include_complexity: bool = True, include_ownership: bool = True, include_hotspots: bool = True, include_patterns: Optional[List[str]] = None, exclude_patterns: Optional[List[str]] = None, max_files: Optional[int] = None) -> ExaminationResult

Perform comprehensive project examination.

Conducts a full examination of the specified project, running all requested analysis types and aggregating results into a comprehensive report.

PARAMETERDESCRIPTION
path

Path to project directory

TYPE:Path

deep

Whether to perform deep AST-based analysis

TYPE:boolDEFAULT:False

include_git

Whether to include git repository analysis

TYPE:boolDEFAULT:True

include_metrics

Whether to calculate code metrics

TYPE:boolDEFAULT:True

include_complexity

Whether to analyze code complexity

TYPE:boolDEFAULT:True

include_ownership

Whether to track code ownership

TYPE:boolDEFAULT:True

include_hotspots

Whether to detect code hotspots

TYPE:boolDEFAULT:True

include_patterns

File patterns to include (e.g., ['*.py'])

TYPE:Optional[List[str]]DEFAULT:None

exclude_patterns

File patterns to exclude (e.g., ['test_*'])

TYPE:Optional[List[str]]DEFAULT:None

max_files

Maximum number of files to analyze

TYPE:Optional[int]DEFAULT:None

RETURNSDESCRIPTION
ExaminationResult

Comprehensive examination findings

TYPE:ExaminationResult

RAISESDESCRIPTION
ValueError

If path doesn't exist or isn't a directory

Example

examiner = Examiner(config) result = examiner.examine_project( ... Path("./src"), ... deep=True, ... include_git=True ... ) print(f"Health score: {result.health_score}")

examine_file
Python
examine_file(file_path: Path, deep: bool = False) -> Dict[str, Any]

Examine a single file in detail.

Performs focused analysis on a single file, extracting all available metrics, complexity measures, and structural information.

PARAMETERDESCRIPTION
file_path

Path to the file to examine

TYPE:Path

deep

Whether to perform deep AST-based analysis

TYPE:boolDEFAULT:False

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: Detailed file examination results

RAISESDESCRIPTION
ValueError

If file doesn't exist or isn't a file

Example

examiner = Examiner(config) result = examiner.examine_file(Path("main.py"), deep=True) print(f"Complexity: {result['complexity']}")

HotspotDetector

Python
HotspotDetector(config: TenetsConfig)

Detector for code hotspots.

Analyzes code repository to identify hotspots - areas that change frequently, have high complexity, or show other problematic patterns.

ATTRIBUTEDESCRIPTION
config

Configuration object

logger

Logger instance

git_analyzer

Git analyzer instance

TYPE:Optional[GitAnalyzer]

Initialize hotspot detector.

PARAMETERDESCRIPTION
config

TenetsConfig instance

TYPE:TenetsConfig

Attributes

configinstance-attribute
Python
config = config
loggerinstance-attribute
Python
logger = get_logger(__name__)
git_analyzerinstance-attribute
Python
git_analyzer: Optional[GitAnalyzer] = None

Functions

detect
Python
detect(repo_path: Path, files: Optional[List[Any]] = None, since_days: int = 90, threshold: int = 10, include_stable: bool = False) -> HotspotReport

Detect hotspots in a repository.

Analyzes git history and code metrics to identify problematic areas that need attention or refactoring.

PARAMETERDESCRIPTION
repo_path

Path to git repository

TYPE:Path

files

Optional list of analyzed file objects

TYPE:Optional[List[Any]]DEFAULT:None

since_days

Days of history to analyze

TYPE:intDEFAULT:90

threshold

Minimum score to consider as hotspot

TYPE:intDEFAULT:10

include_stable

Whether to include stable files in report

TYPE:boolDEFAULT:False

RETURNSDESCRIPTION
HotspotReport

Comprehensive hotspot analysis

TYPE:HotspotReport

Example

detector = HotspotDetector(config) report = detector.detect(Path("."), since_days=30) print(f"Found {report.total_hotspots} hotspots")

HotspotReportdataclass

Python
HotspotReport(total_files_analyzed: int = 0, total_hotspots: int = 0, critical_count: int = 0, high_count: int = 0, file_hotspots: List[FileHotspot] = list(), module_hotspots: List[ModuleHotspot] = list(), coupling_clusters: List[List[str]] = list(), temporal_patterns: Dict[str, Any] = dict(), hotspot_trends: Dict[str, Any] = dict(), top_problems: List[Tuple[str, int]] = list(), estimated_effort: float = 0.0, recommendations: List[str] = list(), risk_matrix: Dict[str, List[str]] = dict(), _health_score_override: Optional[float] = None)

Comprehensive hotspot analysis report.

Provides detailed insights into code hotspots, including problematic files, modules, trends, and recommendations for improvement.

ATTRIBUTEDESCRIPTION
total_files_analyzed

Total files analyzed

TYPE:int

total_hotspots

Total hotspots detected

TYPE:int

critical_count

Number of critical hotspots

TYPE:int

high_count

Number of high-risk hotspots

TYPE:int

file_hotspots

List of file-level hotspots

TYPE:List[FileHotspot]

module_hotspots

List of module-level hotspots

TYPE:List[ModuleHotspot]

coupling_clusters

Groups of tightly coupled files

TYPE:List[List[str]]

temporal_patterns

Time-based patterns detected

TYPE:Dict[str, Any]

hotspot_trends

Trends in hotspot evolution

TYPE:Dict[str, Any]

top_problems

Most common problem types

TYPE:List[Tuple[str, int]]

estimated_effort

Estimated effort to address hotspots

TYPE:float

recommendations

Actionable recommendations

TYPE:List[str]

risk_matrix

Risk assessment matrix

TYPE:Dict[str, List[str]]

Attributes

total_files_analyzedclass-attributeinstance-attribute
Python
total_files_analyzed: int = 0
total_hotspotsclass-attributeinstance-attribute
Python
total_hotspots: int = 0
critical_countclass-attributeinstance-attribute
Python
critical_count: int = 0
high_countclass-attributeinstance-attribute
Python
high_count: int = 0
file_hotspotsclass-attributeinstance-attribute
Python
file_hotspots: List[FileHotspot] = field(default_factory=list)
module_hotspotsclass-attributeinstance-attribute
Python
module_hotspots: List[ModuleHotspot] = field(default_factory=list)
coupling_clustersclass-attributeinstance-attribute
Python
coupling_clusters: List[List[str]] = field(default_factory=list)
temporal_patternsclass-attributeinstance-attribute
Python
temporal_patterns: Dict[str, Any] = field(default_factory=dict)
Python
hotspot_trends: Dict[str, Any] = field(default_factory=dict)
top_problemsclass-attributeinstance-attribute
Python
top_problems: List[Tuple[str, int]] = field(default_factory=list)
estimated_effortclass-attributeinstance-attribute
Python
estimated_effort: float = 0.0
recommendationsclass-attributeinstance-attribute
Python
recommendations: List[str] = field(default_factory=list)
risk_matrixclass-attributeinstance-attribute
Python
risk_matrix: Dict[str, List[str]] = field(default_factory=dict)
total_countproperty
Python
total_count: int

Get total hotspot count.

RETURNSDESCRIPTION
int

Total number of hotspots

TYPE:int

health_scorepropertywritable
Python
health_score: float

Calculate overall codebase health score.

Lower scores indicate more hotspots and problems.

RETURNSDESCRIPTION
float

Health score (0-100)

TYPE:float

Functions

to_dict
Python
to_dict() -> Dict[str, Any]

Convert report to dictionary.

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dictionary representation

MetricsCalculator

Python
MetricsCalculator(config: TenetsConfig)

Calculator for code metrics extraction and aggregation.

Processes analyzed files to compute comprehensive metrics including size measurements, complexity statistics, quality indicators, and distributional analysis.

ATTRIBUTEDESCRIPTION
config

Configuration object

logger

Logger instance

Initialize metrics calculator with configuration.

PARAMETERDESCRIPTION
config

TenetsConfig instance with metrics settings

TYPE:TenetsConfig

Attributes

configinstance-attribute
Python
config = config
loggerinstance-attribute
Python
logger = get_logger(__name__)

Functions

calculate
Python
calculate(files: List[Any]) -> MetricsReport

Calculate comprehensive metrics for analyzed files.

Processes a list of analyzed file objects to extract and aggregate various code metrics, producing a complete metrics report.

PARAMETERDESCRIPTION
files

List of analyzed file objects

TYPE:List[Any]

RETURNSDESCRIPTION
MetricsReport

Comprehensive metrics analysis

TYPE:MetricsReport

Example

calculator = MetricsCalculator(config) report = calculator.calculate(analyzed_files) print(f"Average complexity: {report.avg_complexity}")

calculate_file_metrics
Python
calculate_file_metrics(file_analysis: Any) -> Dict[str, Any]

Calculate metrics for a single file.

Extracts detailed metrics from a single file analysis object, providing file-specific measurements and statistics.

PARAMETERDESCRIPTION
file_analysis

Analyzed file object

TYPE:Any

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: File-specific metrics

Example

metrics = calculator.calculate_file_metrics(file_analysis) print(f"File complexity: {metrics['complexity']}")

MetricsReportdataclass

Python
MetricsReport(total_files: int = 0, total_lines: int = 0, total_blank_lines: int = 0, total_comment_lines: int = 0, total_code_lines: int = 0, total_functions: int = 0, total_classes: int = 0, total_imports: int = 0, avg_file_size: float = 0.0, avg_complexity: float = 0.0, max_complexity: float = 0.0, min_complexity: float = float('inf'), complexity_std_dev: float = 0.0, documentation_ratio: float = 0.0, test_coverage: float = 0.0, code_duplication_ratio: float = 0.0, technical_debt_score: float = 0.0, maintainability_index: float = 0.0, languages: Dict[str, Dict[str, Any]] = dict(), file_types: Dict[str, int] = dict(), size_distribution: Dict[str, int] = dict(), complexity_distribution: Dict[str, int] = dict(), largest_files: List[Dict[str, Any]] = list(), most_complex_files: List[Dict[str, Any]] = list(), most_imported_modules: List[Tuple[str, int]] = list())

Comprehensive metrics report for analyzed code.

Aggregates various code metrics to provide quantitative insights into codebase characteristics, including size, complexity, documentation, and quality indicators.

ATTRIBUTEDESCRIPTION
total_files

Total number of files analyzed

TYPE:int

total_lines

Total lines of code across all files

TYPE:int

total_blank_lines

Total blank lines

TYPE:int

total_comment_lines

Total comment lines

TYPE:int

total_code_lines

Total actual code lines (excluding blanks/comments)

TYPE:int

total_functions

Total number of functions/methods

TYPE:int

total_classes

Total number of classes

TYPE:int

total_imports

Total number of import statements

TYPE:int

avg_file_size

Average file size in lines

TYPE:float

avg_complexity

Average cyclomatic complexity

TYPE:float

max_complexity

Maximum cyclomatic complexity found

TYPE:float

min_complexity

Minimum cyclomatic complexity found

TYPE:float

complexity_std_dev

Standard deviation of complexity

TYPE:float

documentation_ratio

Ratio of comment lines to code lines

TYPE:float

test_coverage

Estimated test coverage (if test files found)

TYPE:float

languages

Dictionary of language-specific metrics

TYPE:Dict[str, Dict[str, Any]]

file_types

Distribution of file types

TYPE:Dict[str, int]

size_distribution

File size distribution buckets

TYPE:Dict[str, int]

complexity_distribution

Complexity distribution buckets

TYPE:Dict[str, int]

largest_files

List of largest files by line count

TYPE:List[Dict[str, Any]]

most_complex_files

List of files with highest complexity

TYPE:List[Dict[str, Any]]

most_imported_modules

Most frequently imported modules

TYPE:List[Tuple[str, int]]

code_duplication_ratio

Estimated code duplication ratio

TYPE:float

technical_debt_score

Calculated technical debt score

TYPE:float

maintainability_index

Overall maintainability index

TYPE:float

Attributes

total_filesclass-attributeinstance-attribute
Python
total_files: int = 0
total_linesclass-attributeinstance-attribute
Python
total_lines: int = 0
total_blank_linesclass-attributeinstance-attribute
Python
total_blank_lines: int = 0
total_comment_linesclass-attributeinstance-attribute
Python
total_comment_lines: int = 0
total_code_linesclass-attributeinstance-attribute
Python
total_code_lines: int = 0
total_functionsclass-attributeinstance-attribute
Python
total_functions: int = 0
total_classesclass-attributeinstance-attribute
Python
total_classes: int = 0
total_importsclass-attributeinstance-attribute
Python
total_imports: int = 0
avg_file_sizeclass-attributeinstance-attribute
Python
avg_file_size: float = 0.0
avg_complexityclass-attributeinstance-attribute
Python
avg_complexity: float = 0.0
max_complexityclass-attributeinstance-attribute
Python
max_complexity: float = 0.0
min_complexityclass-attributeinstance-attribute
Python
min_complexity: float = float('inf')
complexity_std_devclass-attributeinstance-attribute
Python
complexity_std_dev: float = 0.0
documentation_ratioclass-attributeinstance-attribute
Python
documentation_ratio: float = 0.0
code_duplication_ratioclass-attributeinstance-attribute
Python
code_duplication_ratio: float = 0.0
technical_debt_scoreclass-attributeinstance-attribute
Python
technical_debt_score: float = 0.0
maintainability_indexclass-attributeinstance-attribute
Python
maintainability_index: float = 0.0
languagesclass-attributeinstance-attribute
Python
languages: Dict[str, Dict[str, Any]] = field(default_factory=dict)
file_typesclass-attributeinstance-attribute
Python
file_types: Dict[str, int] = field(default_factory=dict)
size_distributionclass-attributeinstance-attribute
Python
size_distribution: Dict[str, int] = field(default_factory=dict)
complexity_distributionclass-attributeinstance-attribute
Python
complexity_distribution: Dict[str, int] = field(default_factory=dict)
largest_filesclass-attributeinstance-attribute
Python
largest_files: List[Dict[str, Any]] = field(default_factory=list)
most_complex_filesclass-attributeinstance-attribute
Python
most_complex_files: List[Dict[str, Any]] = field(default_factory=list)
most_imported_modulesclass-attributeinstance-attribute
Python
most_imported_modules: List[Tuple[str, int]] = field(default_factory=list)
code_to_comment_ratioproperty
Python
code_to_comment_ratio: float

Calculate code to comment ratio.

RETURNSDESCRIPTION
float

Ratio of code lines to comment lines

TYPE:float

avg_file_complexityproperty
Python
avg_file_complexity: float

Calculate average complexity per file.

RETURNSDESCRIPTION
float

Average complexity across all files

TYPE:float

quality_scoreproperty
Python
quality_score: float

Calculate overall code quality score (0-100).

Combines various metrics to produce a single quality indicator.

RETURNSDESCRIPTION
float

Quality score between 0 and 100

TYPE:float

Functions

to_dict
Python
to_dict() -> Dict[str, Any]

Convert metrics report to dictionary.

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dictionary representation of metrics

OwnershipReportdataclass

Python
OwnershipReport(total_contributors: int = 0, total_files_analyzed: int = 0, active_contributors: int = 0, contributors: List[ContributorInfo] = list(), file_ownership: Dict[str, FileOwnership] = dict(), orphaned_files: List[str] = list(), high_risk_files: List[Dict[str, Any]] = list(), knowledge_silos: List[Dict[str, Any]] = list(), bus_factor: int = 0, team_ownership: Optional[TeamOwnership] = None, ownership_distribution: Dict[str, float] = dict(), collaboration_graph: Dict[Tuple[str, str], int] = dict(), expertise_map: Dict[str, List[str]] = dict(), recommendations: List[str] = list(), risk_score: float = 0.0)

Comprehensive code ownership analysis report.

Provides detailed insights into code ownership patterns, knowledge distribution, bus factor risks, and team dynamics.

ATTRIBUTEDESCRIPTION
total_contributors

Total number of contributors

TYPE:int

active_contributors

Currently active contributors

TYPE:int

contributors

List of contributor information

TYPE:List[ContributorInfo]

file_ownership

Ownership by file

TYPE:Dict[str, FileOwnership]

orphaned_files

Files without active maintainers

TYPE:List[str]

high_risk_files

Files with bus factor risks

TYPE:List[Dict[str, Any]]

knowledge_silos

Areas with concentrated knowledge

TYPE:List[Dict[str, Any]]

bus_factor

Overall project bus factor

TYPE:int

team_ownership

Team-level ownership patterns

TYPE:Optional[TeamOwnership]

ownership_distribution

Distribution of ownership

TYPE:Dict[str, float]

collaboration_graph

Collaboration relationships

TYPE:Dict[Tuple[str, str], int]

expertise_map

Map of expertise areas

TYPE:Dict[str, List[str]]

recommendations

Actionable recommendations

TYPE:List[str]

risk_score

Overall ownership risk score

TYPE:float

Attributes

total_contributorsclass-attributeinstance-attribute
Python
total_contributors: int = 0
total_files_analyzedclass-attributeinstance-attribute
Python
total_files_analyzed: int = 0
active_contributorsclass-attributeinstance-attribute
Python
active_contributors: int = 0
contributorsclass-attributeinstance-attribute
Python
contributors: List[ContributorInfo] = field(default_factory=list)
file_ownershipclass-attributeinstance-attribute
Python
file_ownership: Dict[str, FileOwnership] = field(default_factory=dict)
orphaned_filesclass-attributeinstance-attribute
Python
orphaned_files: List[str] = field(default_factory=list)
high_risk_filesclass-attributeinstance-attribute
Python
high_risk_files: List[Dict[str, Any]] = field(default_factory=list)
knowledge_silosclass-attributeinstance-attribute
Python
knowledge_silos: List[Dict[str, Any]] = field(default_factory=list)
bus_factorclass-attributeinstance-attribute
Python
bus_factor: int = 0
team_ownershipclass-attributeinstance-attribute
Python
team_ownership: Optional[TeamOwnership] = None
ownership_distributionclass-attributeinstance-attribute
Python
ownership_distribution: Dict[str, float] = field(default_factory=dict)
collaboration_graphclass-attributeinstance-attribute
Python
collaboration_graph: Dict[Tuple[str, str], int] = field(default_factory=dict)
expertise_mapclass-attributeinstance-attribute
Python
expertise_map: Dict[str, List[str]] = field(default_factory=dict)
recommendationsclass-attributeinstance-attribute
Python
recommendations: List[str] = field(default_factory=list)
risk_scoreclass-attributeinstance-attribute
Python
risk_score: float = 0.0
health_scoreproperty
Python
health_score: float

Calculate ownership health score.

Higher scores indicate better knowledge distribution.

RETURNSDESCRIPTION
float

Health score (0-100)

TYPE:float

Functions

to_dict
Python
to_dict() -> Dict[str, Any]

Convert report to dictionary.

RETURNSDESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dictionary representation

OwnershipTracker

Python
OwnershipTracker(config: TenetsConfig)

Tracker for code ownership patterns.

Analyzes git history to understand code ownership, knowledge distribution, and collaboration patterns within a codebase.

ATTRIBUTEDESCRIPTION
config

Configuration object

logger

Logger instance

git_analyzer

Git analyzer instance

TYPE:Optional[GitAnalyzer]

Initialize ownership tracker.

PARAMETERDESCRIPTION
config

TenetsConfig instance

TYPE:TenetsConfig

Attributes

configinstance-attribute
Python
config = config
loggerinstance-attribute
Python
logger = get_logger(__name__)
git_analyzerinstance-attribute
Python
git_analyzer: Optional[GitAnalyzer] = None

Functions

track
Python
track(repo_path: Path, since_days: int = 365, include_tests: bool = True, team_mapping: Optional[Dict[str, List[str]]] = None) -> OwnershipReport

Track code ownership for a repository.

Analyzes git history to determine ownership patterns, identify risks, and provide insights into knowledge distribution.

PARAMETERDESCRIPTION
repo_path

Path to git repository

TYPE:Path

since_days

Days of history to analyze

TYPE:intDEFAULT:365

include_tests

Whether to include test files

TYPE:boolDEFAULT:True

team_mapping

Optional mapping of team names to members

TYPE:Optional[Dict[str, List[str]]]DEFAULT:None

RETURNSDESCRIPTION
OwnershipReport

Comprehensive ownership analysis

TYPE:OwnershipReport

Example

tracker = OwnershipTracker(config) report = tracker.track(Path("."), since_days=90) print(f"Bus factor: {report.bus_factor}")

analyze_ownership
Python
analyze_ownership(repo_path: Path, **kwargs: Any) -> OwnershipReport

Analyze ownership for a repository path.

This is an alias for the track() method to maintain backward compatibility.

PARAMETERDESCRIPTION
repo_path

Path to repository

TYPE:Path

**kwargs

Additional arguments passed to track()

TYPE:AnyDEFAULT:{}

RETURNSDESCRIPTION
OwnershipReport

Comprehensive ownership analysis

TYPE:OwnershipReport

Functions

examine_project

Python
examine_project(path: Path, deep: bool = False, include_git: bool = True, include_metrics: bool = True, include_complexity: bool = True, include_ownership: bool = True, include_hotspots: bool = True, config: Optional[Any] = None) -> ExaminationResult

Examine a project comprehensively.

This is a convenience function that creates an Examiner instance and performs a full examination of the specified project.

PARAMETERDESCRIPTION
path

Path to project directory

TYPE:Path

deep

Whether to perform deep analysis with AST parsing

TYPE:boolDEFAULT:False

include_git

Whether to include git analysis

TYPE:boolDEFAULT:True

include_metrics

Whether to calculate detailed metrics

TYPE:boolDEFAULT:True

include_complexity

Whether to analyze complexity

TYPE:boolDEFAULT:True

include_ownership

Whether to track code ownership

TYPE:boolDEFAULT:True

include_hotspots

Whether to detect hotspots

TYPE:boolDEFAULT:True

config

Optional TenetsConfig instance

TYPE:Optional[Any]DEFAULT:None

RETURNSDESCRIPTION
ExaminationResult

ExaminationResult with comprehensive analysis

Example

from tenets.core.examiner import examine_project

results = examine_project( ... Path("./my_project"), ... deep=True, ... include_git=True ... )

Access various reports

print(f"Files analyzed: {results.total_files}") print(f"Languages: {results.languages}") print(f"Top complex files: {results.complexity.top_files}")

examine_file

Python
examine_file(file_path: Path, deep: bool = False, config: Optional[Any] = None) -> Dict[str, Any]

Examine a single file.

Performs detailed analysis on a single file including complexity, metrics, and structure analysis.

PARAMETERDESCRIPTION
file_path

Path to file

TYPE:Path

deep

Whether to perform deep analysis

TYPE:boolDEFAULT:False

config

Optional TenetsConfig instance

TYPE:Optional[Any]DEFAULT:None

RETURNSDESCRIPTION
Dict[str, Any]

Dictionary with file examination results

Example

from tenets.core.examiner import examine_file

results = examine_file(Path("main.py"), deep=True) print(f"Complexity: {results['complexity']}") print(f"Lines: {results['lines']}")

calculate_metrics

Python
calculate_metrics(files: List[Any], config: Optional[Any] = None) -> MetricsReport

Calculate metrics for a list of files.

PARAMETERDESCRIPTION
files

List of FileAnalysis objects

TYPE:List[Any]

config

Optional TenetsConfig instance

TYPE:Optional[Any]DEFAULT:None

RETURNSDESCRIPTION
MetricsReport

MetricsReport with calculated metrics

Example

from tenets.core.examiner import calculate_metrics

metrics = calculate_metrics(analyzed_files) print(f"Total lines: {metrics.total_lines}") print(f"Average complexity: {metrics.avg_complexity}")

analyze_complexity

Python
analyze_complexity(files: List[Any], threshold: int = 10, config: Optional[Any] = None) -> ComplexityReport

Analyze complexity patterns in files.

PARAMETERDESCRIPTION
files

List of FileAnalysis objects

TYPE:List[Any]

threshold

Minimum complexity threshold

TYPE:intDEFAULT:10

config

Optional TenetsConfig instance

TYPE:Optional[Any]DEFAULT:None

RETURNSDESCRIPTION
ComplexityReport

ComplexityReport with analysis results

Example

from tenets.core.examiner import analyze_complexity

complexity = analyze_complexity(files, threshold=10) for file in complexity.high_complexity_files: print(f"{file.path}: {file.complexity}")

track_ownership

Python
track_ownership(repo_path: Path, since_days: int = 90, config: Optional[Any] = None) -> OwnershipReport

Track code ownership patterns.

PARAMETERDESCRIPTION
repo_path

Path to git repository

TYPE:Path

since_days

Days to look back

TYPE:intDEFAULT:90

config

Optional TenetsConfig instance

TYPE:Optional[Any]DEFAULT:None

RETURNSDESCRIPTION
OwnershipReport

OwnershipReport with ownership data

Example

from tenets.core.examiner import track_ownership

ownership = track_ownership(Path("."), since_days=30) for author in ownership.top_contributors: print(f"{author.name}: {author.commits}")

detect_hotspots

Python
detect_hotspots(repo_path: Path, files: Optional[List[Any]] = None, threshold: int = 5, config: Optional[Any] = None) -> HotspotReport

Detect code hotspots (frequently changed areas).

PARAMETERDESCRIPTION
repo_path

Path to git repository

TYPE:Path

files

Optional list of FileAnalysis objects

TYPE:Optional[List[Any]]DEFAULT:None

threshold

Minimum change count for hotspot

TYPE:intDEFAULT:5

config

Optional TenetsConfig instance

TYPE:Optional[Any]DEFAULT:None

RETURNSDESCRIPTION
HotspotReport

HotspotReport with detected hotspots

Example

from tenets.core.examiner import detect_hotspots

hotspots = detect_hotspots(Path("."), threshold=10) for hotspot in hotspots.files: print(f"{hotspot.path}: {hotspot.change_count} changes")

Modules