Skip to main content

Biblioteca Python para análise de qualidade e saúde de código

Project description

CodeHealthAnalyzer

Biblioteca Python para análise de saúde de código com foco em três frentes:

  • violações de tamanho em módulos, classes, funções e templates
  • CSS/JS inline em templates HTML
  • erros de linting coletados via Ruff

O que a biblioteca entrega hoje

  • API Python com CodeAnalyzer, ViolationsAnalyzer, TemplatesAnalyzer e ErrorsAnalyzer
  • CLI com os comandos analyze, violations, templates, errors, score, info, dashboard, format e lint
  • relatórios em json, html, markdown e csv
  • dashboard FastAPI opcional com métricas agregadas
  • contrato de relatório tipado e versão centralizada

Instalação

pip install codehealthanalyzer

Com dashboard:

pip install "codehealthanalyzer[web]"

Para desenvolvimento:

pip install -e ".[dev,web]"

Uso rápido

CLI

codehealthanalyzer analyze .
codehealthanalyzer analyze . --format all --output reports
codehealthanalyzer violations . --format csv
codehealthanalyzer templates . --config config.json
codehealthanalyzer errors . --no-json --format markdown
codehealthanalyzer dashboard .

API Python

from codehealthanalyzer import CodeAnalyzer

analyzer = CodeAnalyzer(".", config={"target_dir": ".", "templates_dir": ["templates"]})
report = analyzer.generate_full_report(output_dir="reports")
print(report["summary"]["quality_score"])

Configuração

Exemplo de config.json:

{
  "limits": {
    "python_function": { "yellow": 30, "red": 50 },
    "python_class": { "yellow": 300, "red": 500 },
    "python_module": { "yellow": 500, "red": 1000 },
    "html_template": { "yellow": 150, "red": 200 },
    "test_file": { "yellow": 400, "red": 600 }
  },
  "target_dir": ".",
  "templates_dir": ["templates", "app/templates"],
  "exclude_dirs": ["legacy", "vendor"],
  "ruff_fix": false,
  "no_default_excludes": false
}

Campos suportados:

  • limits: sobrescreve limites de tamanho
  • target_dir: diretório analisado pelo Ruff
  • templates_dir: string ou lista de diretórios de templates
  • exclude_dirs: string ou lista de diretórios extras a ignorar
  • ruff_fix: roda ruff check --fix antes da coleta
  • no_default_excludes: desabilita as exclusões padrão

Contrato de relatório

O relatório consolidado sempre contém:

{
    "metadata": {...},
    "summary": {...},
    "violations": {...},
    "templates": {...},
    "errors": {...},
    "priorities": [...],
    "quality_score": 0,
}

Os schemas tipados ficam em codehealthanalyzer/schemas.py.

Desenvolvimento

pytest -q
ruff check codehealthanalyzer tests
black --check codehealthanalyzer tests
isort --check-only codehealthanalyzer tests

Limitações atuais

  • a análise de erros depende do executável ruff estar disponível no ambiente
  • o dashboard mostra métricas agregadas, não histórico persistente completo
  • a análise de templates é baseada em heurísticas simples de HTML e regex

🔍 CodeHealthAnalyzer

A comprehensive Python library for code quality and health analysis

Python Version License Code Style

🇧🇷 Português | 🇺🇸 English

🚀 Overview

CodeHealthAnalyzer is a modern and comprehensive Python library for code quality analysis. It combines multiple analysis tools into a unified interface, providing detailed insights into your code's health.

✨ Key Features

  • 🚨 Violations Analysis: Detects functions, classes, and modules that exceed size limits
  • 🎨 Template Analysis: Identifies inline CSS/JS in HTML templates that can be extracted
  • ⚠️ Ruff Integration: Analyzes linting errors and categorizes them by priority
  • 📊 Quality Score: Calculates a 0-100 score based on overall code health
  • 🎯 Smart Prioritization: Suggests actions based on problem criticality
  • 📈 Multiple Reports: Generates reports in JSON, HTML, Markdown, and CSV
  • 🖥️ Friendly CLI: Complete and intuitive command-line interface
  • 🔧 Highly Configurable: Customize limits, rules, and categories

📦 Installation

Installation via pip (recommended)

# Basic installation
pip install codehealthanalyzer

# Installation with interactive web dashboard
pip install codehealthanalyzer[web]

# Complete installation (web + development)
pip install codehealthanalyzer[web,dev]

Development Installation

git clone https://github.com/imparcialista/codehealthanalyzer.git
cd codehealthanalyzer
pip install -e .[web,dev]

Dependencies

  • Python 3.8+
  • ruff >= 0.1.0
  • click >= 8.0.0
  • rich >= 12.0.0 (optional, for colored output)

🎯 Quick Start

🌐 Interactive Dashboard

# Start web dashboard with real-time metrics
codehealthanalyzer dashboard .

# Dashboard on specific host and port
codehealthanalyzer dashboard . --host 0.0.0.0 --port 8080

# Dashboard with auto-reload for development
codehealthanalyzer dashboard . --reload

Dashboard Features:

  • 📊 Real-time metrics with automatic updates
  • 📈 Interactive quality trend charts
  • 🎯 Violations visualization by type
  • 📋 Problem files table
  • 🔄 WebSockets for instant updates
  • 📱 Responsive and modern interface

CLI (Command Line Interface)

# Complete analysis of current project
codehealthanalyzer analyze .

# Analysis with HTML output
codehealthanalyzer analyze . --format html --output reports/

# Quality score only
codehealthanalyzer score .

# Project information
codehealthanalyzer info .

# Specific violations analysis
codehealthanalyzer violations . --output violations.json

Python API

from codehealthanalyzer import CodeAnalyzer

# Initialize analyzer
analyzer = CodeAnalyzer('/path/to/project')

# Generate complete report
report = analyzer.generate_full_report(output_dir='reports/')

# Get quality score
score = analyzer.get_quality_score()
print(f"Quality Score: {score}/100")

# Individual analyses
violations = analyzer.analyze_violations()
templates = analyzer.analyze_templates()
errors = analyzer.analyze_errors()

📊 Example Output

📊 ANALYSIS SUMMARY
==================================================
✅ Quality Score: 85/100 - Excellent!
📁 Files analyzed: 124
⚠️  Files with violations: 8
🎨 Templates: 15
🔍 Ruff Errors: 0
🔥 High priority issues: 2

🎯 ACTION PRIORITIES:
1. 🔴 High Priority Violations (2)
2. 🟡 Templates with Too Much Inline CSS/JS (3)

🔧 Configuration

JSON Configuration File

{
  "limits": {
    "python_function": {"yellow": 30, "red": 50},
    "python_class": {"yellow": 300, "red": 500},
    "python_module": {"yellow": 500, "red": 1000},
    "html_template": {"yellow": 150, "red": 200},
    "test_file": {"yellow": 400, "red": 600}
  },
  "target_dir": "src/",
  "file_rules": {
    "critical_files": ["main.py", "core.py"],
    "skip_patterns": [".git", "__pycache__", "node_modules"]
  }
}

Usage with Configuration

codehealthanalyzer analyze . --config config.json
import json
from codehealthanalyzer import CodeAnalyzer

with open('config.json') as f:
    config = json.load(f)

analyzer = CodeAnalyzer('/path/to/project', config)

📈 Analysis Types

🚨 Violations Analysis

Detects:

  • Functions too long (> 50 lines)
  • Classes too large (> 500 lines)
  • Modules too extensive (> 1000 lines)
  • HTML templates too long (> 200 lines)

🎨 Template Analysis

Identifies:

  • Inline CSS in style attributes
  • Inline JavaScript in events (onclick, etc.)
  • <style> tags with too much content
  • <script> tags with too much code

⚠️ Error Analysis

Integrates with Ruff to detect:

  • Syntax errors
  • Style issues
  • Unused imports
  • Undefined variables
  • Excessive complexity

📊 Quality Score

The score is calculated based on:

  • High priority violations: -10 points each
  • Linting errors: -2 points each
  • Problematic templates: -5 points each
  • Base: 100 points

Interpretation

  • 80-100: 🟢 Excellent
  • 60-79: 🟡 Good
  • 0-59: 🔴 Needs improvement

🌐 Internationalization

Language Support

CodeHealthAnalyzer supports multiple languages:

  • Portuguese (Brazil): Default language
  • English: Full translation available

Setting Language

from codehealthanalyzer.i18n import set_language

# Set to English
set_language('en')

# Set to Portuguese (Brazil)
set_language('pt_BR')

# Auto-detect system language
from codehealthanalyzer.i18n import auto_configure_language
auto_configure_language()

Environment Variable

# Set language via environment
export CODEHEALTHANALYZER_LANG=en
codehealthanalyzer analyze .

🛠️ Advanced API

Individual Analyzers

from codehealthanalyzer.analyzers import (
    ViolationsAnalyzer,
    TemplatesAnalyzer,
    ErrorsAnalyzer
)

# Specific violations analysis
violations_analyzer = ViolationsAnalyzer('/path/to/project')
violations_report = violations_analyzer.analyze()

# Specific templates analysis
templates_analyzer = TemplatesAnalyzer('/path/to/project')
templates_report = templates_analyzer.analyze()

# Specific errors analysis
errors_analyzer = ErrorsAnalyzer('/path/to/project')
errors_report = errors_analyzer.analyze()

Report Generation

from codehealthanalyzer.reports import ReportGenerator, ReportFormatter

generator = ReportGenerator()
formatter = ReportFormatter()

# Generate consolidated report
full_report = generator.generate_full_report(
    violations=violations_report,
    templates=templates_report,
    errors=errors_report,
    output_dir='reports/'
)

# Convert to different formats
html_content = generator.generate_html_report(full_report, 'report.html')
markdown_content = formatter.to_markdown(full_report, 'report.md')
formatter.to_csv(full_report, 'report.csv')

🧪 Testing

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=codehealthanalyzer

# Run linting
ruff check codehealthanalyzer/
black --check codehealthanalyzer/

🤝 Contributing

  1. Fork the project
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Contribution Guidelines

  • Follow existing code style
  • Add tests for new features
  • Update documentation when necessary
  • Use semantic commits

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Ruff - Ultra-fast Python linter
  • Click - CLI framework
  • Rich - Rich terminal formatting

📞 Support


Made with ❤️ by the Imparcialista team

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

codehealthanalyzer-1.2.0.tar.gz (67.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

codehealthanalyzer-1.2.0-py3-none-any.whl (54.9 kB view details)

Uploaded Python 3

File details

Details for the file codehealthanalyzer-1.2.0.tar.gz.

File metadata

  • Download URL: codehealthanalyzer-1.2.0.tar.gz
  • Upload date:
  • Size: 67.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.2

File hashes

Hashes for codehealthanalyzer-1.2.0.tar.gz
Algorithm Hash digest
SHA256 c8646bf5bb4e4d56970ff3e828f8583cd2131f7c96fbde24802db9a9f247f94f
MD5 ff026d4df42db3a6049e3c9d02a1a9aa
BLAKE2b-256 52fa75b9a8ce2d1ca18575c7e488bb552dea8ad42c37d0f01b4d37b4d857fccb

See more details on using hashes here.

File details

Details for the file codehealthanalyzer-1.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for codehealthanalyzer-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f33edda1706534d31a61100ab720bed806abe0a09f62b7c85ca04e7ac46ff1e2
MD5 9e070dbd0d257816789160ff69fb7d4e
BLAKE2b-256 a52e53ad8c111fb87f2bcc4b3410e81f1b33ab65649168f56e926c6760b2cd46

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page