The user wants a "code climate analyzer" that correlates four specific data sources:
- Structural Metrics: Cyclomatic complexity, coupling, cohesion, code coverage, etc. (Static analysis).
- Review Friction: Time to merge, number of comments, number of revisions, PR size. (Git/PR data).
- Production Incidents: Bugs, outages, hotfixes linked to specific code changes. (Issue tracker/Observability data).
- Developer Feedback: Comments in code reviews, sentiment analysis, surveys, annotations. (Qualitative data).
This is a complex system that usually requires integration with multiple APIs (GitHub/GitLab, Jira, SonarQube, etc.) and a database to store and correlate the data.
Strategy:
I need to provide a conceptual architecture and a Python-based prototype implementation.
Step 1: Define the Architecture.
- Data Ingestion: Connectors for Git (PyDriller or GitHub API), CI/CD (Jenkins/GitHub Actions), Static Analysis (Radon/Sonarqube), and Issue Tracking (Jira).
- Data Storage: A relational database (SQLite/Postgres) or a specialized time-series/document store. For the prototype, a Pandas DataFrame is sufficient, but a SQL schema is better for explaining the "production" aspect.
- Analysis Engine: The core logic. It needs to aggregate metrics per file/module/author and calculate correlation coefficients.
- Reporting/Visualization: Outputting the results (text, JSON, or a plot).
Step 2: Develop the Python Prototype.
I will use Python because of its strong ecosystem in data science and software analysis.
-
Dependencies: pandas (for correlation), radon (for complexity), gitpython or pydriller (for git history), textblob (for sentiment analysis on comments).
-
Mock Data vs. Real Data: Since I don't have access to the user's private repos or production logs, I must create a simulation or a mock data generator. I will implement a DataGenerator class to create realistic synthetic data so the user can run the code immediately. I will also provide stubs for real integrations.
-
Key Logic - The Correlation Matrix:
- Structural Metric:
complexity
- Review Friction:
review_time_hours, num_comments
- Incidents:
bug_count
- Feedback:
sentiment_score (derived from PR comments).
I want to answer questions like:
- "Does high complexity lead to more bugs?" (Structural vs. Incidents)
- "Does high complexity slow down reviews?" (Structural vs. Review Friction)
- "Do negative comments correlate with more bugs?" (Feedback vs. Incidents)
Step 3: Refine the Code Structure.
CodeAnalyzer: The main class.
fetch_structural_metrics(file): Uses radon (if real) or mock data.
fetch_review_metrics(pr_id): Mock Git data.
fetch_incident_data(pr_id): Mock Jira data.
analyze_sentiment(text): Uses textblob or simple logic.
correlate(): Uses Pandas df.corr().
Step 4: Adding the "Code Climate" concept.
The output shouldn't just be raw numbers. It should provide a "Health Score" or specific recommendations.
- High Complexity + High Incidents -> "Technical Debt Hotspot."
- High Friction + Low Sentiment -> "Process Bottleneck."
Step 5: Drafting the Response.
- Introduction: Acknowledge the complexity. It's an Engineering Intelligence platform.
- Architecture Diagram (Mental): Explain how the pieces fit.
- The Code: A complete, runnable Python script.
- Use
radon for real static analysis if possible, but stick to a simulation approach for the multi-source aspect (Review/Incidents) since those require API keys. Actually, it's better to write a script that can analyze real code if present, but defaults to generating dummy data for the correlation demo.
- Correction: To make it truly useful, I'll implement the static analysis part using
radon on a provided directory, but mock the PR/Incident data since I can't connect to their Jira/GitHub.
- Wait, better approach: Write a "Simulation Engine" that generates a synthetic dataset based on probabilistic rules (e.g., complexity influences bug probability). This demonstrates the correlation capability effectively.
Let's refine the Python implementation plan:
- Class
MetricCollector: Generates/Fetches data.
- Fields:
file_path, complexity, cognitive_complexity, loc, maintainability_index.
- Fields:
time_to_review, iterations, comments_sentiment.
- Fields:
post_deploy_bugs.
- Class
ClimateAnalyzer:
- Ingests data into Pandas DataFrame.
- Computes Pearson correlation matrix.
- Identifies outliers (files with high complexity AND high bugs).
- Generates a report.
Self-Correction/Refinement:
The user asked for an analyzer. I should provide a framework that allows them to plug in their own adapters.
I will create an abstract base class for "Data Providers" and implement a "Mock Provider" for the demo.
I will also include a sentiment analysis component using textblob (standard library is preferred but textblob is common enough, or just a simple dictionary approach to avoid heavy deps). Let's stick to standard library + pandas + radon (optional) to keep it light, or provide a requirements.txt. I'll use pandas and numpy as they are standard for this type of math.
Output Structure:
- Conceptual Overview: How to correlate these disparate data points.
- Python Implementation:
- Data Models.
- Mock Data Generator (to simulate the 4 inputs).
- Analysis Engine (Correlation logic).
- Reporting Logic (identifying hotspots).
- Integration Guide: How to swap mocks for real GitHub/Jira APIs.
Specifics of the Code:
- Structural: Mock
complexity (0-100).
- Review: Mock
hours_to_merge (correlated to complexity).
- Incidents: Mock
bug_severity (correlated to complexity).
- Feedback: Mock
developer_sentiment (negative correlated to complexity).
- The Twist: I will introduce a
calculate_climate_score method that weights these factors.
Let's write the code mentally first.
import pandas as pd
import numpy as np
from dataclasses import dataclass
# Define the data point
@dataclass
class CodeUnit:
file: str
complexity: float
review_time: float
incident_count: int
sentiment: float # -1 to 1
# Correlation
df = pd.DataFrame(...)
corr_matrix = df.corr()
I need to ensure the mock data actually shows correlation, otherwise the tool looks broken. I will generate complexity randomly, then define review_time as complexity * X + noise and incidents as complexity * Y + noise.
Final Polish:
The prompt asks to "Develop" it. I will provide a modular Python script.
I will use radon in the example for the Structural part if the user runs it on a real folder, otherwise fallback to mock. This makes it "real."
Actually, to ensure the code runs immediately without a specific folder structure, a full simulation mode is safer and more impressive for a demo. I will clarify how to hook it up to real data.
Plan:
- Architecture: Explain the "Data Lake" approach for code metrics.
- Python Tool:
- Uses
pandas for the math.
- Uses a
SyntheticDataGenerator to create the dataset (simulating the 4 inputs).
- Implements
CodeClimateAnalyzer to find correlations.
- Implements a
ReportGenerator to output insights.
- Next Steps: How to connect to real APIs (GitHub, Jira).
Let's proceed.
This is a sophisticated engineering intelligence problem. To build a robust analyzer, you need to treat code changes as the "common key" to join disparate datasets: static analysis (Structure), version control (Reviews), issue trackers (Incidents), and text analysis (Feedback).
Below is a comprehensive Python framework. It simulates the data ingestion from these four sources, normalizes them, and performs a correlation analysis to identify "High Friction, High Risk" areas of the codebase.
Prerequisites
You will need pandas for data manipulation and numpy for calculations.
pip install pandas numpy
The Code Climate Analyzer Framework
import pandas as pd
import numpy as np
import random
from dataclasses import dataclass
from typing import List, Dict
# ==========================================
# 1. Data Models (The Schema)
# ==========================================
@dataclass
class StructuralMetric:
file_path: str
complexity: float # Cyclomatic complexity
coverage: float # 0.0 to 1.0
size_lines: int
@dataclass
class ReviewMetric:
file_path: str
pr_comments: int # Friction: Discussion intensity
rework_cycles: int # Friction: How many times rejected/updated
time_to_merge_hours: int
@dataclass
class IncidentMetric:
file_path: str
bug_count: int # Production bugs linked to this file
severity_score: float # Weighted impact (e.g., 1=low, 5=critical)
@dataclass
class FeedbackMetric:
file_path: str
sentiment: float # -1.0 (Negative) to 1.0 (Positive)
# Derived from comments like "This is legacy spaghetti", "Refactor needed"
# ==========================================
# 2. Synthetic Data Generator (Mocking APIs)
# ==========================================
class DataSimulator:
"""
Simulates fetching data from SonarQube, GitHub, Jira, and Slack/Jira comments.
In a real scenario, these would be API calls.
"""
def __init__(self, files: List[str]):
self.files = files
def generate_all_data(self) -> pd.DataFrame:
data = []
for f in self.files:
# Simulate correlations: High complexity tends to lead to more bugs and negative sentiment
base_complexity = random.randint(1, 50)
# Structural
s_metric = StructuralMetric(
file_path=f,
complexity=base_complexity,
coverage=random.uniform(0.2, 0.95),
size_lines=random.randint(50, 500)
)
# Review (Higher complexity -> slower reviews)
r_metric = ReviewMetric(
file_path=f,
pr_comments=int(base_complexity * 0.5) + random.randint(0, 10),
rework_cycles=random.randint(0, 5),
time_to_merge_hours=int(base_complexity * 1.5) + random.randint(1, 24)
)
# Incidents (High complexity/low coverage -> more bugs)
i_metric = IncidentMetric(
file_path=f,
bug_count=random.randint(0, 5) if base_complexity > 20 else 0,
severity_score=random.uniform(1, 5)
)
# Feedback (High complexity -> negative dev sentiment)
sentiment = 0.8 - (base_complexity * 0.03) + random.uniform(-0.2, 0.2)
f_metric = FeedbackMetric(
file_path=f,
sentiment=max(-1.0, min(1.0, sentiment)) # Clamp between -1 and 1
)
data.append({
"file": f,
"complexity": s_metric.complexity,
"coverage": s_metric.coverage,
"size": s_metric.size_lines,
"review_comments": r_metric.pr_comments,
"rework_cycles": r_metric.rework_cycles,
"merge_time_h": r_metric.time_to_merge_hours,
"bug_count": i_metric.bug_count,
"severity": i_metric.severity_score,
"sentiment": f_metric.sentiment
})
return pd.DataFrame(data)
# ==========================================
# 3. Analysis Engine
# ==========================================
class CodeClimateAnalyzer:
def __init__(self, df: pd.DataFrame):
self.df = df
self._calculate_composite_scores()
def _calculate_composite_scores(self):
"""
Normalizes data and creates composite indexes.
"""
# 1. Technical Debt Score (Structure)
# High complexity + Low coverage = High Debt
# Formula: (Complexity_norm * 0.7) + ((1 - Coverage) * 0.3)
self.df['complexity_norm'] = self.df['complexity'] / self.df['complexity'].max()
self.df['tech_debt_score'] = (self.df['complexity_norm'] * 0.7) + ((1 - self.df['coverage']) * 0.3)
# 2. Review Friction Score (Process)
# High comments + High rework + Slow merge = High Friction
self.df['friction_score'] = (
(self.df['review_comments'] / self.df['review_comments'].max()) +
(self.df['rework_cycles'] / self.df['rework_cycles'].max()) +
(self.df['merge_time_h'] / self.df['merge_time_h'].max())
) / 3
# 3. Risk Score (Production)
# Bug count * Severity
self.df['risk_score'] = self.df['bug_count'] * self.df['severity']
def correlate_metrics(self):
"""
Finds statistical correlations between structural metrics and outcomes.
"""
print("\n--- CORRELATION MATRIX ---")
# We want to see if Complexity correlates with Friction, Risk, or Sentiment
cols_of_interest = ['complexity', 'coverage', 'friction_score', 'risk_score', 'sentiment']
corr_matrix = self.df[cols_of_interest].corr()
# Highlight specific insights
comp_to_friction = corr_matrix.loc['complexity', 'friction_score']
comp_to_risk = corr_matrix.loc['complexity', 'risk_score']
sentiment_to_friction = corr_matrix.loc['sentiment', 'friction_score']
print(f"Complexity -> Review Friction: {comp_to_friction:.2f} (Strong positive implies complex code is hard to review)")
print(f"Complexity -> Prod Risk: {comp_to_risk:.2f} (Strong positive implies complex code breaks often)")
print(f"Sentiment -> Review Friction: {sentiment_to_friction:.2f} (Negative implies frustrated devs slow down reviews)")
return corr_matrix
def identify_hotspots(self, threshold_debt=0.7, threshold_risk=0.5):
"""
Identifies files that are structurally unsound AND causing business issues.
"""
# Normalize risk for comparison
self.df['risk_norm'] = self.df['risk_score'] / self.df['risk_score'].max()
# Filter for high debt and high risk
hotspots = self.df[
(self.df['tech_debt_score'] > threshold_debt) &
(self.df['risk_score'] > self.df['risk_score'].quantile(0.75))
].sort_values(by='risk_score', ascending=False)
return hotspots
def generate_report(self):
print("\n--- CODE CLIMATE REPORT ---")
# 1. Correlations
self.correlate_metrics()
# 2. Hotspots
hotspots = self.identify_hotspots()
print("\n--- CRITICAL HOTSPOTS (Needs Immediate Refactoring) ---")
if hotspots.empty:
print("No critical hotspots found.")
else:
for _, row in hotspots.iterrows():
print(f"File: {row['file']}")
print(f" - Tech Debt: {row['tech_debt_score']:.2f} (Complexity: {row['complexity']}, Coverage: {row['coverage']:.2f})")
print(f" - Prod Risk: {row['risk_score']:.2f} (Bugs: {row['bug_count']})")
print(f" - Dev Sentiment: {row['sentiment']:.2f} (Negative values indicate developer unhapiness)")
print("-" * 30)
# ==========================================
# 4. Execution
# ==========================================
if __name__ == "__main__":
# Define a mock file system
project_files = [
"src/auth/login.py",
"src/auth/oauth.py",
"src/db/connection.py",
"src/db/migrations.py",
"src/api/handlers.py",
"src/util/helpers.py",
"src/legacy/spaghetti_code.py" # Intentionally named to likely be high risk
]
# 1. Ingest Data (Simulated)
print("Ingesting data from mock APIs...")
simulator = DataSimulator(project_files)
raw_df = simulator.generate_all_data()
# 2. Analyze
analyzer = CodeClimateAnalyzer(raw_df)
analyzer.generate_report()
How It Works
1. The Data Model
The code normalizes four disparate sources into a single DataFrame (Table) keyed by file_path:
- Structure: Represents data from tools like SonarQube or ESLint (Complexity, Coverage).
- Review Friction: Represents Git log data (Time to merge, number of comments).
- Incidents: Represents Jira/Observability data (Bugs linked to commits).
- Feedback: Represents natural language processing (NLP) on PR comments.
2. Scoring Logic
The analyzer creates composite indices to make sense of the raw numbers:
- Tech Debt Score: Combines complexity and lack of coverage.
- Friction Score: Combines time wasted and discussion intensity.
- Risk Score: Combines frequency and severity of production incidents.
3. Correlation Analysis
Instead of looking at metrics in isolation, it calculates the Pearson correlation coefficient.
- Example Insight: If
Complexity -> Risk is high (e.g., 0.8), it proves that your technical debt is directly causing production outages.
- Example Insight: If
Sentiment -> Friction is strongly negative, it proves that developers are unhappy with the code quality, resulting in slower merge times.
4. Hotspot Detection
The final report filters for files that appear in the upper percentiles of both Technical Debt (Bad Structure) and Production Risk (Bad Outcome). These are your "Burning Fires" that need immediate refactoring.
How to Productionize This
To move this from a prototype to a real system, you would replace the DataSimulator with API clients:
- Structure: Call the SonarQube API (
/api/measures/component) to get complexity and coverage.
- Review: Call the GitHub/GitLab API to fetch Pull Requests. Calculate
time_to_merge by comparing created_at with merged_at. Count conversation threads for friction.
- Incidents: Query Jira or PagerDuty. Map incidents to code files using "Issue Keys" in commit messages.
- Feedback: Use a sentiment analysis library (like NLTK or OpenAI API) on the text content of PR comments.