codehealthanalyzer


Namecodehealthanalyzer JSON
Version 1.1.9 PyPI version JSON
download
home_pagehttps://github.com/imparcialista/codehealthanalyzer
SummaryBiblioteca Python para análise de qualidade e saúde de código
upload_time2025-10-11 12:50:53
maintainerNone
docs_urlNone
authorLuarco Team
requires_python>=3.8
licenseNone
keywords code-quality static-analysis code-health linting python html css javascript ruff analysis metrics reporting
VCS
bugtrack_url
requirements ruff click rich fastapi uvicorn jinja2 python-multipart websockets
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 🔍 CodeHealthAnalyzer

> Uma biblioteca Python completa para análise de qualidade e saúde de código

🇧🇷 Português | [🇺🇸 English](README_EN.md)

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

## 🚀 Visão Geral

CodeHealthAnalyzer é uma biblioteca Python moderna e abrangente para análise de qualidade de código. Ela combina múltiplas ferramentas de análise em uma interface unificada, fornecendo insights detalhados sobre a saúde do seu código.

### ✨ Principais Funcionalidades

- **🚨 Análise de Violações**: Detecta funções, classes e módulos que excedem limites de tamanho
- **🎨 Análise de Templates**: Identifica CSS/JS inline em templates HTML que podem ser extraídos
- **⚠️ Integração com Ruff**: Analisa erros de linting e os categoriza por prioridade
- **📊 Score de Qualidade**: Calcula um score de 0-100 baseado na saúde geral do código
- **🎯 Priorização Inteligente**: Sugere ações baseadas na criticidade dos problemas
- **📈 Relatórios Múltiplos**: Gera relatórios em JSON, HTML, Markdown e CSV
- **🖥️ CLI Amigável**: Interface de linha de comando completa e intuitiva
- **🔧 Altamente Configurável**: Personalize limites, regras e categorias

## 📦 Instalação

### Instalação via pip (recomendado)

```bash
# Instalação básica
pip install codehealthanalyzer

# Instalação com dashboard web interativo
pip install codehealthanalyzer[web]

# Instalação completa (web + desenvolvimento)
pip install codehealthanalyzer[web,dev]
```

### Instalação para desenvolvimento

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

### Dependências

- Python 3.8+
- ruff >= 0.1.0
- click >= 8.0.0
- rich >= 12.0.0 (opcional, para saída colorida)

## 🎯 Uso Rápido

### 🌐 Dashboard Interativo

```bash
# Iniciar dashboard web com métricas em tempo real
codehealthanalyzer dashboard

# Dashboard em host e porta específicos
codehealthanalyzer dashboard --host 0.0.0.0 --port 8080

# Dashboard com reload automático para desenvolvimento
codehealthanalyzer dashboard --reload
```

**Funcionalidades do Dashboard:**
- 📊 Métricas em tempo real com atualizações automáticas
- 📈 Gráficos interativos de tendência de qualidade
- 🎯 Visualização de violações por tipo
- 📋 Tabela de arquivos com problemas
- 🔄 WebSockets para atualizações instantâneas
- 📱 Interface responsiva e moderna

### CLI (Interface de Linha de Comando)

```bash
# Análise completa do projeto atual (o diretório padrão é '.')
codehealthanalyzer analyze

# Por padrão, um JSON é gerado em ./reports/full_report.json
# Formatos adicionais (HTML, Markdown ou todos):
codehealthanalyzer analyze --format html
codehealthanalyzer analyze --format markdown
codehealthanalyzer analyze --format all

# Desativar JSON padrão
codehealthanalyzer analyze --format html --no-json

# Definir diretório de saída (padrão: ./reports)
codehealthanalyzer analyze --format all --output out/

# Apenas score de qualidade
codehealthanalyzer score

# Informações do projeto
codehealthanalyzer info

# Análise específica de violações
codehealthanalyzer violations --format all

# Análise específica de templates
codehealthanalyzer templates --format all

# Análise específica de erros (Ruff)
codehealthanalyzer errors --format all

## Comandos disponíveis

- `analyze [PROJECT_PATH]` (padrão: `.`): análise completa (violations, templates, errors) e geração de relatórios.
- `violations [PROJECT_PATH]`: apenas violações de tamanho/linhas.
- `templates [PROJECT_PATH]`: apenas templates HTML com CSS/JS inline.
- `errors [PROJECT_PATH]`: apenas erros Ruff.
- `score [PROJECT_PATH]`: exibe apenas o score de qualidade.
- `info [PROJECT_PATH]`: informações básicas do projeto.
- `dashboard [PROJECT_PATH]`: inicia a UI web (FastAPI) com métricas ao vivo.
- `format [PROJECT_PATH]`: aplica auto-fixes e formatação (isort + black + ruff --fix).
- `lint [PROJECT_PATH]`: executa checagens (ruff, isort --check, black --check, bandit).

### Opções comuns úteis

- `--output`, `-o`: diretório de saída dos relatórios. Padrão: `./reports`.
- `--format`, `-f`: formato adicional do relatório: `html`, `markdown` ou `all`.
- `--no-json`: por padrão, sempre é gerado um JSON. Use esta flag para NÃO gerar o JSON.
- `--config`, `-c`: caminho para um `config.json` com suas preferências.
- `--no-default-excludes`: não aplicar as exclusões padrão (tests, scripts, reports, venv etc.).

Exemplos por comando

```bash
# analyze: JSON + HTML + MD em ./reports
codehealthanalyzer analyze --format all

# analyze: HTML apenas, sem JSON
codehealthanalyzer analyze --format html --no-json

# violations: JSON por padrão + HTML/MD
codehealthanalyzer violations --format all

# templates: JSON por padrão + HTML/MD
codehealthanalyzer templates --format all

# errors (Ruff): JSON por padrão + HTML/MD
codehealthanalyzer errors --format all

# desativar exclusões padrão e usar config.json
codehealthanalyzer analyze --no-default-excludes --config config.json

# format: aplicar auto-fixes e formatação
codehealthanalyzer format
codehealthanalyzer format --no-ruff   # p.ex., só isort + black

# lint: checar qualidade e segurança
codehealthanalyzer lint
```
```

### API Python

```python
from codehealthanalyzer import CodeAnalyzer

# Inicializa o analisador
analyzer = CodeAnalyzer('/path/to/project')

# Gera relatório completo
report = analyzer.generate_full_report(output_dir='reports/')

# Obtém score de qualidade
score = analyzer.get_quality_score()
print(f"Score de Qualidade: {score}/100")

# Análises individuais
violations = analyzer.analyze_violations()
templates = analyzer.analyze_templates()
errors = analyzer.analyze_errors()
```

## 📊 Exemplo de Saída

```
📊 RESUMO DA ANÁLISE
==================================================
✅ Score de Qualidade: 85/100 - Excelente!
📁 Arquivos analisados: 124
⚠️  Arquivos com violações: 8
🎨 Templates: 15
🔍 Erros Ruff: 0
🔥 Issues de alta prioridade: 2

🎯 PRIORIDADES DE AÇÃO:
1. 🔴 Violações de Alta Prioridade (2)
2. 🟡 Templates com Muito CSS/JS Inline (3)
```

## 🔧 Configuração

### Arquivo de Configuração JSON

```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": "src/",
  "ruff_fix": true,
  "templates_dir": ["templates/", "app/templates/"],
  "file_rules": {
    "critical_files": ["main.py", "core.py"],
    "skip_patterns": [".git", "__pycache__", "node_modules"]
  },
  "exclude_dirs": ["legacy/", "playground/"]
}
```

### Uso com Configuração

```bash
codehealthanalyzer analyze . --config config.json
```

```python
import json
from codehealthanalyzer import CodeAnalyzer

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

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

### Novas opções de configuração

- `templates_dir`:
  - Define um ou mais diretórios onde os templates HTML serão buscados.
  - Aceita string (ex.: `"templates/"`) ou lista de strings (ex.: `["templates/", "app/templates/"]`).
  - Padrões automáticos: `templates/` e `luarco/templates/` (se existirem no projeto).

- `target_dir` (ErrorsAnalyzer/Ruff):
  - Diretório raiz analisado pelo Ruff. Padrão agora é `"."` (raiz do projeto).

- `ruff_fix` (ErrorsAnalyzer):
  - Quando `true`, executa `ruff check --fix` antes de coletar os erros.
  - Padrão: `false`.

- Exclusões de diretórios (padrão e personalizadas):
  - Por padrão, os analisadores ignoram diretórios não relacionados a código-fonte:
    - `.git`, `__pycache__`, `.pytest_cache`, `node_modules`, `.ruff_cache`
    - `tests`, `scripts`, `reports`, `dist`, `build`, `site-packages`
    - `.tox`, `.nox`, `.venv`, `venv`, `.env`, `migrations`
  - Para desativar as exclusões padrão: use a flag `--no-default-excludes` nos comandos `analyze`, `violations`, `templates`, `errors`.
  - Para definir exclusões personalizadas via config:
    ```json
    {
      "exclude_dirs": ["legacy/", "playground/"]
    }
    ```

### Observação para Windows (encoding do console)

Para evitar problemas de encoding (CP1252) no console do Windows, a CLI usa apenas caracteres ASCII.
Se desejar usar emojis/Unicode, configure o terminal para UTF-8. Exemplo no PowerShell:

```powershell
$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
```

## 🌍 Traduções

- Arquivos compilados `.mo` agora são incluídos no pacote distribuído.
- Para compilar localmente, use `scripts/compile_translations.py` (requer `gettext` ou fallback Python embutido).

## 🔁 Integração Contínua (CI)

  - Lint com Ruff (`ruff check`).
  - Testes com `pytest`.
  - Matriz Python: 3.8 a 3.12.
  - (Opcional) Build de documentação Sphinx.

## 📈 Tipos de Análise

### 🚨 Análise de Violações

Detecta:
- Funções muito longas (> 50 linhas)
- Classes muito grandes (> 500 linhas)
- Módulos muito extensos (> 1000 linhas)
- Templates HTML muito longos (> 200 linhas)

### 🎨 Análise de Templates

Identifica:
- CSS inline em atributos `style`
- JavaScript inline em eventos (`onclick`, etc.)
- Tags `<style>` com muito conteúdo
- Tags `<script>` com muito código

### ⚠️ Análise de Erros

Integra com Ruff para detectar:
- Erros de sintaxe
- Problemas de estilo
- Imports não utilizados
- Variáveis não definidas
- Complexidade excessiva

## 📊 Score de Qualidade

O score é calculado baseado em:
- **Violações de alta prioridade**: -10 pontos cada
- **Erros de linting**: -2 pontos cada
- **Templates problemáticos**: -5 pontos cada
- **Base**: 100 pontos

### Interpretação
- **80-100**: 🟢 Excelente
- **60-79**: 🟡 Bom
- **0-59**: 🔴 Precisa melhorar

## 🎯 Categorização Inteligente

### Arquivos
- **Arquivo Crítico**: Arquivos essenciais do sistema
- **Views Admin**: Interfaces administrativas
- **Blueprint Crítico**: Rotas críticas da aplicação
- **Template Base**: Templates fundamentais

### Prioridades
- **Alta**: Problemas que afetam funcionalidade
- **Média**: Problemas de manutenibilidade
- **Baixa**: Melhorias recomendadas

## 📋 Formatos de Relatório

### JSON
```json
{
  "metadata": {
    "generated_at": "2024-01-15T10:30:00",
    "generator": "CodeHealthAnalyzer v1.0.0"
  },
  "summary": {
    "quality_score": 85,
    "total_files": 124,
    "violation_files": 8
  },
  "priorities": [...],
  "violations": [...],
  "templates": [...],
  "errors": [...]
}
```

### HTML
Relatório completo e navegável, com:
- Resumo (Score, totais)
- Prioridades de ação
- Tabela de Arquivos com Violações (arquivo, prioridade, nº violações, linhas)
- Tabela de Erros (Ruff)
- Tabela de Templates (CSS/JS chars)

### Markdown
Relatório rico em Markdown com:
- Resumo em tabela
- Prioridades
- Tabelas para Violações, Erros e Templates

### CSV
Dados tabulares para análise em planilhas.

## 🛠️ API Avançada

### Analisadores Individuais

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

# Análise específica de violações
violations_analyzer = ViolationsAnalyzer('/path/to/project')
violations_report = violations_analyzer.analyze()

# Análise específica de templates
templates_analyzer = TemplatesAnalyzer('/path/to/project')
templates_report = templates_analyzer.analyze()

# Análise específica de erros
errors_analyzer = ErrorsAnalyzer('/path/to/project')
errors_report = errors_analyzer.analyze()
```

### Geração de Relatórios

```python
from codehealthanalyzer.reports import ReportGenerator, ReportFormatter

generator = ReportGenerator()
formatter = ReportFormatter()

# Gera relatório consolidado
full_report = generator.generate_full_report(
    violations=violations_report,
    templates=templates_report,
    errors=errors_report,
    output_dir='reports/'
)

# Converte para diferentes formatos
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')
```

### Utilitários

```python
from codehealthanalyzer.utils import (
    Categorizer,
    PathValidator,
    FileHelper,
    ColorHelper
)

# Categorização
categorizer = Categorizer()
category = categorizer.categorize_file(Path('src/main.py'))
priority = categorizer.determine_priority('file', {'lines': 150, 'type': 'python'})

# Validação
validator = PathValidator()
is_valid = validator.is_python_project('/path/to/project')
project_info = validator.get_project_info('/path/to/project')

# Helpers
file_helper = FileHelper()
data = file_helper.read_json('config.json')
file_helper.write_json(data, 'output.json')

# Cores para terminal
print(ColorHelper.success("Sucesso!"))
print(ColorHelper.error("Erro!"))
print(ColorHelper.warning("Aviso!"))
```

## 🧪 Testes

```bash
# Instala dependências de desenvolvimento
pip install -e ".[dev]"

# Executa testes
pytest

# Executa testes com cobertura
pytest --cov=codehealthanalyzer

# Executa linting
ruff check codehealthanalyzer/
black --check codehealthanalyzer/
```

## 🧰 Ferramentas de Qualidade e Segurança (para seu projeto)

Além de usar o CodeHealthAnalyzer, recomendamos rodar as seguintes ferramentas diretamente no seu projeto (exemplos a seguir). Substitua `luarco/` pelo diretório do seu projeto.

### Ruff (Linter & Auto-fix)

```bash
# Verificar erros com ruff
ruff check luarco/

# Corrigir erros automaticamente (quando possível)
ruff check luarco/ --fix

# Ver apenas erros críticos
ruff check luarco/ --select=F821,F841,E9
```

### Black (Formatação automática)

```bash
# Black - Formatação automática
black .
```

### isort (Organização de imports)

```bash
# isort - Organização de imports
isort .
```

### Bandit (Segurança)

```bash
# bandit - Segurança (gera relatório JSON)
bandit -r luarco/ -f json -o bandit-report.json
```

Observações:
- É comum rodar `ruff check --fix`, depois `isort .` e `black .` para padronizar o código.
- Você pode integrar essas ferramentas no seu CI, semelhante ao nosso workflow em `.github/workflows/ci.yml`.

## 🤝 Contribuição

1. Fork o projeto
2. Crie uma branch para sua feature (`git checkout -b feature/AmazingFeature`)
3. Commit suas mudanças (`git commit -m 'Add some AmazingFeature'`)
4. Push para a branch (`git push origin feature/AmazingFeature`)
5. Abra um Pull Request

### Diretrizes de Contribuição

- Siga o estilo de código existente
- Adicione testes para novas funcionalidades
- Atualize a documentação quando necessário
- Use commits semânticos

## 📄 Licença

Este projeto está licenciado sob a Licença MIT - veja o arquivo [LICENSE](LICENSE) para detalhes.

## 🙏 Agradecimentos

- [Ruff](https://github.com/astral-sh/ruff) - Linter Python ultrarrápido
- [Click](https://click.palletsprojects.com/) - Framework para CLI
- [Rich](https://github.com/Textualize/rich) - Formatação rica para terminal

## 📞 Suporte

- 📧 Email: contato@luarco.com.br
- 🐛 Issues: [GitHub Issues](https://github.com/imparcialista/codehealthanalyzer/issues)
- 📖 Documentação: [ReadTheDocs](https://codehealthanalyzer.readthedocs.io/)

---

**Feito com ❤️ pela equipe Imparcialista**

---

# 🔍 CodeHealthAnalyzer

> A comprehensive Python library for code quality and health analysis

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

[🇧🇷 Português](README.md) | 🇺🇸 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)

```bash
# 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

```bash
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

```bash
# 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)

```bash
# 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

```python
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

```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": "src/",
  "file_rules": {
    "critical_files": ["main.py", "core.py"],
    "skip_patterns": [".git", "__pycache__", "node_modules"]
  }
}
```

### Usage with Configuration

```bash
codehealthanalyzer analyze . --config config.json
```

```python
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

```python
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

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

## 🛠️ Advanced API

### Individual Analyzers

```python
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

```python
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

```bash
# 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](LICENSE) file for details.

## 🙏 Acknowledgments

- [Ruff](https://github.com/astral-sh/ruff) - Ultra-fast Python linter
- [Click](https://click.palletsprojects.com/) - CLI framework
- [Rich](https://github.com/Textualize/rich) - Rich terminal formatting

## 📞 Support

- 📧 Email: contato@luarco.com.br
- 🐛 Issues: [GitHub Issues](https://github.com/imparcialista/codehealthanalyzer/issues)
- 📖 Documentation: [ReadTheDocs](https://codehealthanalyzer.readthedocs.io/)

---

**Made with ❤️ by the Imparcialista team**

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/imparcialista/codehealthanalyzer",
    "name": "codehealthanalyzer",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "code-quality, static-analysis, code-health, linting, python, html, css, javascript, ruff, analysis, metrics, reporting",
    "author": "Luarco Team",
    "author_email": "contato@luarco.com.br",
    "download_url": "https://files.pythonhosted.org/packages/0f/2d/6fb716fc3c7c016a00056fa3ce371cfedccc5bf3ac245a15da13dcb86e61/codehealthanalyzer-1.1.9.tar.gz",
    "platform": null,
    "description": "# \ud83d\udd0d CodeHealthAnalyzer\r\n\r\n> Uma biblioteca Python completa para an\u00e1lise de qualidade e sa\u00fade de c\u00f3digo\r\n\r\n\ud83c\udde7\ud83c\uddf7 Portugu\u00eas | [\ud83c\uddfa\ud83c\uddf8 English](README_EN.md)\r\n\r\n[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)\r\n[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)\r\n[![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\r\n\r\n## \ud83d\ude80 Vis\u00e3o Geral\r\n\r\nCodeHealthAnalyzer \u00e9 uma biblioteca Python moderna e abrangente para an\u00e1lise de qualidade de c\u00f3digo. Ela combina m\u00faltiplas ferramentas de an\u00e1lise em uma interface unificada, fornecendo insights detalhados sobre a sa\u00fade do seu c\u00f3digo.\r\n\r\n### \u2728 Principais Funcionalidades\r\n\r\n- **\ud83d\udea8 An\u00e1lise de Viola\u00e7\u00f5es**: Detecta fun\u00e7\u00f5es, classes e m\u00f3dulos que excedem limites de tamanho\r\n- **\ud83c\udfa8 An\u00e1lise de Templates**: Identifica CSS/JS inline em templates HTML que podem ser extra\u00eddos\r\n- **\u26a0\ufe0f Integra\u00e7\u00e3o com Ruff**: Analisa erros de linting e os categoriza por prioridade\r\n- **\ud83d\udcca Score de Qualidade**: Calcula um score de 0-100 baseado na sa\u00fade geral do c\u00f3digo\r\n- **\ud83c\udfaf Prioriza\u00e7\u00e3o Inteligente**: Sugere a\u00e7\u00f5es baseadas na criticidade dos problemas\r\n- **\ud83d\udcc8 Relat\u00f3rios M\u00faltiplos**: Gera relat\u00f3rios em JSON, HTML, Markdown e CSV\r\n- **\ud83d\udda5\ufe0f CLI Amig\u00e1vel**: Interface de linha de comando completa e intuitiva\r\n- **\ud83d\udd27 Altamente Configur\u00e1vel**: Personalize limites, regras e categorias\r\n\r\n## \ud83d\udce6 Instala\u00e7\u00e3o\r\n\r\n### Instala\u00e7\u00e3o via pip (recomendado)\r\n\r\n```bash\r\n# Instala\u00e7\u00e3o b\u00e1sica\r\npip install codehealthanalyzer\r\n\r\n# Instala\u00e7\u00e3o com dashboard web interativo\r\npip install codehealthanalyzer[web]\r\n\r\n# Instala\u00e7\u00e3o completa (web + desenvolvimento)\r\npip install codehealthanalyzer[web,dev]\r\n```\r\n\r\n### Instala\u00e7\u00e3o para desenvolvimento\r\n\r\n```bash\r\ngit clone https://github.com/imparcialista/codehealthanalyzer.git\r\ncd codehealthanalyzer\r\npip install -e .[web,dev]\r\n```\r\n\r\n### Depend\u00eancias\r\n\r\n- Python 3.8+\r\n- ruff >= 0.1.0\r\n- click >= 8.0.0\r\n- rich >= 12.0.0 (opcional, para sa\u00edda colorida)\r\n\r\n## \ud83c\udfaf Uso R\u00e1pido\r\n\r\n### \ud83c\udf10 Dashboard Interativo\r\n\r\n```bash\r\n# Iniciar dashboard web com m\u00e9tricas em tempo real\r\ncodehealthanalyzer dashboard\r\n\r\n# Dashboard em host e porta espec\u00edficos\r\ncodehealthanalyzer dashboard --host 0.0.0.0 --port 8080\r\n\r\n# Dashboard com reload autom\u00e1tico para desenvolvimento\r\ncodehealthanalyzer dashboard --reload\r\n```\r\n\r\n**Funcionalidades do Dashboard:**\r\n- \ud83d\udcca M\u00e9tricas em tempo real com atualiza\u00e7\u00f5es autom\u00e1ticas\r\n- \ud83d\udcc8 Gr\u00e1ficos interativos de tend\u00eancia de qualidade\r\n- \ud83c\udfaf Visualiza\u00e7\u00e3o de viola\u00e7\u00f5es por tipo\r\n- \ud83d\udccb Tabela de arquivos com problemas\r\n- \ud83d\udd04 WebSockets para atualiza\u00e7\u00f5es instant\u00e2neas\r\n- \ud83d\udcf1 Interface responsiva e moderna\r\n\r\n### CLI (Interface de Linha de Comando)\r\n\r\n```bash\r\n# An\u00e1lise completa do projeto atual (o diret\u00f3rio padr\u00e3o \u00e9 '.')\r\ncodehealthanalyzer analyze\r\n\r\n# Por padr\u00e3o, um JSON \u00e9 gerado em ./reports/full_report.json\r\n# Formatos adicionais (HTML, Markdown ou todos):\r\ncodehealthanalyzer analyze --format html\r\ncodehealthanalyzer analyze --format markdown\r\ncodehealthanalyzer analyze --format all\r\n\r\n# Desativar JSON padr\u00e3o\r\ncodehealthanalyzer analyze --format html --no-json\r\n\r\n# Definir diret\u00f3rio de sa\u00edda (padr\u00e3o: ./reports)\r\ncodehealthanalyzer analyze --format all --output out/\r\n\r\n# Apenas score de qualidade\r\ncodehealthanalyzer score\r\n\r\n# Informa\u00e7\u00f5es do projeto\r\ncodehealthanalyzer info\r\n\r\n# An\u00e1lise espec\u00edfica de viola\u00e7\u00f5es\r\ncodehealthanalyzer violations --format all\r\n\r\n# An\u00e1lise espec\u00edfica de templates\r\ncodehealthanalyzer templates --format all\r\n\r\n# An\u00e1lise espec\u00edfica de erros (Ruff)\r\ncodehealthanalyzer errors --format all\r\n\r\n## Comandos dispon\u00edveis\r\n\r\n- `analyze [PROJECT_PATH]` (padr\u00e3o: `.`): an\u00e1lise completa (violations, templates, errors) e gera\u00e7\u00e3o de relat\u00f3rios.\r\n- `violations [PROJECT_PATH]`: apenas viola\u00e7\u00f5es de tamanho/linhas.\r\n- `templates [PROJECT_PATH]`: apenas templates HTML com CSS/JS inline.\r\n- `errors [PROJECT_PATH]`: apenas erros Ruff.\r\n- `score [PROJECT_PATH]`: exibe apenas o score de qualidade.\r\n- `info [PROJECT_PATH]`: informa\u00e7\u00f5es b\u00e1sicas do projeto.\r\n- `dashboard [PROJECT_PATH]`: inicia a UI web (FastAPI) com m\u00e9tricas ao vivo.\r\n- `format [PROJECT_PATH]`: aplica auto-fixes e formata\u00e7\u00e3o (isort + black + ruff --fix).\r\n- `lint [PROJECT_PATH]`: executa checagens (ruff, isort --check, black --check, bandit).\r\n\r\n### Op\u00e7\u00f5es comuns \u00fateis\r\n\r\n- `--output`, `-o`: diret\u00f3rio de sa\u00edda dos relat\u00f3rios. Padr\u00e3o: `./reports`.\r\n- `--format`, `-f`: formato adicional do relat\u00f3rio: `html`, `markdown` ou `all`.\r\n- `--no-json`: por padr\u00e3o, sempre \u00e9 gerado um JSON. Use esta flag para N\u00c3O gerar o JSON.\r\n- `--config`, `-c`: caminho para um `config.json` com suas prefer\u00eancias.\r\n- `--no-default-excludes`: n\u00e3o aplicar as exclus\u00f5es padr\u00e3o (tests, scripts, reports, venv etc.).\r\n\r\nExemplos por comando\r\n\r\n```bash\r\n# analyze: JSON + HTML + MD em ./reports\r\ncodehealthanalyzer analyze --format all\r\n\r\n# analyze: HTML apenas, sem JSON\r\ncodehealthanalyzer analyze --format html --no-json\r\n\r\n# violations: JSON por padr\u00e3o + HTML/MD\r\ncodehealthanalyzer violations --format all\r\n\r\n# templates: JSON por padr\u00e3o + HTML/MD\r\ncodehealthanalyzer templates --format all\r\n\r\n# errors (Ruff): JSON por padr\u00e3o + HTML/MD\r\ncodehealthanalyzer errors --format all\r\n\r\n# desativar exclus\u00f5es padr\u00e3o e usar config.json\r\ncodehealthanalyzer analyze --no-default-excludes --config config.json\r\n\r\n# format: aplicar auto-fixes e formata\u00e7\u00e3o\r\ncodehealthanalyzer format\r\ncodehealthanalyzer format --no-ruff   # p.ex., s\u00f3 isort + black\r\n\r\n# lint: checar qualidade e seguran\u00e7a\r\ncodehealthanalyzer lint\r\n```\r\n```\r\n\r\n### API Python\r\n\r\n```python\r\nfrom codehealthanalyzer import CodeAnalyzer\r\n\r\n# Inicializa o analisador\r\nanalyzer = CodeAnalyzer('/path/to/project')\r\n\r\n# Gera relat\u00f3rio completo\r\nreport = analyzer.generate_full_report(output_dir='reports/')\r\n\r\n# Obt\u00e9m score de qualidade\r\nscore = analyzer.get_quality_score()\r\nprint(f\"Score de Qualidade: {score}/100\")\r\n\r\n# An\u00e1lises individuais\r\nviolations = analyzer.analyze_violations()\r\ntemplates = analyzer.analyze_templates()\r\nerrors = analyzer.analyze_errors()\r\n```\r\n\r\n## \ud83d\udcca Exemplo de Sa\u00edda\r\n\r\n```\r\n\ud83d\udcca RESUMO DA AN\u00c1LISE\r\n==================================================\r\n\u2705 Score de Qualidade: 85/100 - Excelente!\r\n\ud83d\udcc1 Arquivos analisados: 124\r\n\u26a0\ufe0f  Arquivos com viola\u00e7\u00f5es: 8\r\n\ud83c\udfa8 Templates: 15\r\n\ud83d\udd0d Erros Ruff: 0\r\n\ud83d\udd25 Issues de alta prioridade: 2\r\n\r\n\ud83c\udfaf PRIORIDADES DE A\u00c7\u00c3O:\r\n1. \ud83d\udd34 Viola\u00e7\u00f5es de Alta Prioridade (2)\r\n2. \ud83d\udfe1 Templates com Muito CSS/JS Inline (3)\r\n```\r\n\r\n## \ud83d\udd27 Configura\u00e7\u00e3o\r\n\r\n### Arquivo de Configura\u00e7\u00e3o JSON\r\n\r\n```json\r\n{\r\n  \"limits\": {\r\n    \"python_function\": {\"yellow\": 30, \"red\": 50},\r\n    \"python_class\": {\"yellow\": 300, \"red\": 500},\r\n    \"python_module\": {\"yellow\": 500, \"red\": 1000},\r\n    \"html_template\": {\"yellow\": 150, \"red\": 200},\r\n    \"test_file\": {\"yellow\": 400, \"red\": 600}\r\n  },\r\n  \"target_dir\": \"src/\",\r\n  \"ruff_fix\": true,\r\n  \"templates_dir\": [\"templates/\", \"app/templates/\"],\r\n  \"file_rules\": {\r\n    \"critical_files\": [\"main.py\", \"core.py\"],\r\n    \"skip_patterns\": [\".git\", \"__pycache__\", \"node_modules\"]\r\n  },\r\n  \"exclude_dirs\": [\"legacy/\", \"playground/\"]\r\n}\r\n```\r\n\r\n### Uso com Configura\u00e7\u00e3o\r\n\r\n```bash\r\ncodehealthanalyzer analyze . --config config.json\r\n```\r\n\r\n```python\r\nimport json\r\nfrom codehealthanalyzer import CodeAnalyzer\r\n\r\nwith open('config.json') as f:\r\n    config = json.load(f)\r\n\r\nanalyzer = CodeAnalyzer('/path/to/project', config)\r\n```\r\n\r\n### Novas op\u00e7\u00f5es de configura\u00e7\u00e3o\r\n\r\n- `templates_dir`:\r\n  - Define um ou mais diret\u00f3rios onde os templates HTML ser\u00e3o buscados.\r\n  - Aceita string (ex.: `\"templates/\"`) ou lista de strings (ex.: `[\"templates/\", \"app/templates/\"]`).\r\n  - Padr\u00f5es autom\u00e1ticos: `templates/` e `luarco/templates/` (se existirem no projeto).\r\n\r\n- `target_dir` (ErrorsAnalyzer/Ruff):\r\n  - Diret\u00f3rio raiz analisado pelo Ruff. Padr\u00e3o agora \u00e9 `\".\"` (raiz do projeto).\r\n\r\n- `ruff_fix` (ErrorsAnalyzer):\r\n  - Quando `true`, executa `ruff check --fix` antes de coletar os erros.\r\n  - Padr\u00e3o: `false`.\r\n\r\n- Exclus\u00f5es de diret\u00f3rios (padr\u00e3o e personalizadas):\r\n  - Por padr\u00e3o, os analisadores ignoram diret\u00f3rios n\u00e3o relacionados a c\u00f3digo-fonte:\r\n    - `.git`, `__pycache__`, `.pytest_cache`, `node_modules`, `.ruff_cache`\r\n    - `tests`, `scripts`, `reports`, `dist`, `build`, `site-packages`\r\n    - `.tox`, `.nox`, `.venv`, `venv`, `.env`, `migrations`\r\n  - Para desativar as exclus\u00f5es padr\u00e3o: use a flag `--no-default-excludes` nos comandos `analyze`, `violations`, `templates`, `errors`.\r\n  - Para definir exclus\u00f5es personalizadas via config:\r\n    ```json\r\n    {\r\n      \"exclude_dirs\": [\"legacy/\", \"playground/\"]\r\n    }\r\n    ```\r\n\r\n### Observa\u00e7\u00e3o para Windows (encoding do console)\r\n\r\nPara evitar problemas de encoding (CP1252) no console do Windows, a CLI usa apenas caracteres ASCII.\r\nSe desejar usar emojis/Unicode, configure o terminal para UTF-8. Exemplo no PowerShell:\r\n\r\n```powershell\r\n$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()\r\n```\r\n\r\n## \ud83c\udf0d Tradu\u00e7\u00f5es\r\n\r\n- Arquivos compilados `.mo` agora s\u00e3o inclu\u00eddos no pacote distribu\u00eddo.\r\n- Para compilar localmente, use `scripts/compile_translations.py` (requer `gettext` ou fallback Python embutido).\r\n\r\n## \ud83d\udd01 Integra\u00e7\u00e3o Cont\u00ednua (CI)\r\n\r\n  - Lint com Ruff (`ruff check`).\r\n  - Testes com `pytest`.\r\n  - Matriz Python: 3.8 a 3.12.\r\n  - (Opcional) Build de documenta\u00e7\u00e3o Sphinx.\r\n\r\n## \ud83d\udcc8 Tipos de An\u00e1lise\r\n\r\n### \ud83d\udea8 An\u00e1lise de Viola\u00e7\u00f5es\r\n\r\nDetecta:\r\n- Fun\u00e7\u00f5es muito longas (> 50 linhas)\r\n- Classes muito grandes (> 500 linhas)\r\n- M\u00f3dulos muito extensos (> 1000 linhas)\r\n- Templates HTML muito longos (> 200 linhas)\r\n\r\n### \ud83c\udfa8 An\u00e1lise de Templates\r\n\r\nIdentifica:\r\n- CSS inline em atributos `style`\r\n- JavaScript inline em eventos (`onclick`, etc.)\r\n- Tags `<style>` com muito conte\u00fado\r\n- Tags `<script>` com muito c\u00f3digo\r\n\r\n### \u26a0\ufe0f An\u00e1lise de Erros\r\n\r\nIntegra com Ruff para detectar:\r\n- Erros de sintaxe\r\n- Problemas de estilo\r\n- Imports n\u00e3o utilizados\r\n- Vari\u00e1veis n\u00e3o definidas\r\n- Complexidade excessiva\r\n\r\n## \ud83d\udcca Score de Qualidade\r\n\r\nO score \u00e9 calculado baseado em:\r\n- **Viola\u00e7\u00f5es de alta prioridade**: -10 pontos cada\r\n- **Erros de linting**: -2 pontos cada\r\n- **Templates problem\u00e1ticos**: -5 pontos cada\r\n- **Base**: 100 pontos\r\n\r\n### Interpreta\u00e7\u00e3o\r\n- **80-100**: \ud83d\udfe2 Excelente\r\n- **60-79**: \ud83d\udfe1 Bom\r\n- **0-59**: \ud83d\udd34 Precisa melhorar\r\n\r\n## \ud83c\udfaf Categoriza\u00e7\u00e3o Inteligente\r\n\r\n### Arquivos\r\n- **Arquivo Cr\u00edtico**: Arquivos essenciais do sistema\r\n- **Views Admin**: Interfaces administrativas\r\n- **Blueprint Cr\u00edtico**: Rotas cr\u00edticas da aplica\u00e7\u00e3o\r\n- **Template Base**: Templates fundamentais\r\n\r\n### Prioridades\r\n- **Alta**: Problemas que afetam funcionalidade\r\n- **M\u00e9dia**: Problemas de manutenibilidade\r\n- **Baixa**: Melhorias recomendadas\r\n\r\n## \ud83d\udccb Formatos de Relat\u00f3rio\r\n\r\n### JSON\r\n```json\r\n{\r\n  \"metadata\": {\r\n    \"generated_at\": \"2024-01-15T10:30:00\",\r\n    \"generator\": \"CodeHealthAnalyzer v1.0.0\"\r\n  },\r\n  \"summary\": {\r\n    \"quality_score\": 85,\r\n    \"total_files\": 124,\r\n    \"violation_files\": 8\r\n  },\r\n  \"priorities\": [...],\r\n  \"violations\": [...],\r\n  \"templates\": [...],\r\n  \"errors\": [...]\r\n}\r\n```\r\n\r\n### HTML\r\nRelat\u00f3rio completo e naveg\u00e1vel, com:\r\n- Resumo (Score, totais)\r\n- Prioridades de a\u00e7\u00e3o\r\n- Tabela de Arquivos com Viola\u00e7\u00f5es (arquivo, prioridade, n\u00ba viola\u00e7\u00f5es, linhas)\r\n- Tabela de Erros (Ruff)\r\n- Tabela de Templates (CSS/JS chars)\r\n\r\n### Markdown\r\nRelat\u00f3rio rico em Markdown com:\r\n- Resumo em tabela\r\n- Prioridades\r\n- Tabelas para Viola\u00e7\u00f5es, Erros e Templates\r\n\r\n### CSV\r\nDados tabulares para an\u00e1lise em planilhas.\r\n\r\n## \ud83d\udee0\ufe0f API Avan\u00e7ada\r\n\r\n### Analisadores Individuais\r\n\r\n```python\r\nfrom codehealthanalyzer.analyzers import (\r\n    ViolationsAnalyzer,\r\n    TemplatesAnalyzer,\r\n    ErrorsAnalyzer\r\n)\r\n\r\n# An\u00e1lise espec\u00edfica de viola\u00e7\u00f5es\r\nviolations_analyzer = ViolationsAnalyzer('/path/to/project')\r\nviolations_report = violations_analyzer.analyze()\r\n\r\n# An\u00e1lise espec\u00edfica de templates\r\ntemplates_analyzer = TemplatesAnalyzer('/path/to/project')\r\ntemplates_report = templates_analyzer.analyze()\r\n\r\n# An\u00e1lise espec\u00edfica de erros\r\nerrors_analyzer = ErrorsAnalyzer('/path/to/project')\r\nerrors_report = errors_analyzer.analyze()\r\n```\r\n\r\n### Gera\u00e7\u00e3o de Relat\u00f3rios\r\n\r\n```python\r\nfrom codehealthanalyzer.reports import ReportGenerator, ReportFormatter\r\n\r\ngenerator = ReportGenerator()\r\nformatter = ReportFormatter()\r\n\r\n# Gera relat\u00f3rio consolidado\r\nfull_report = generator.generate_full_report(\r\n    violations=violations_report,\r\n    templates=templates_report,\r\n    errors=errors_report,\r\n    output_dir='reports/'\r\n)\r\n\r\n# Converte para diferentes formatos\r\nhtml_content = generator.generate_html_report(full_report, 'report.html')\r\nmarkdown_content = formatter.to_markdown(full_report, 'report.md')\r\nformatter.to_csv(full_report, 'report.csv')\r\n```\r\n\r\n### Utilit\u00e1rios\r\n\r\n```python\r\nfrom codehealthanalyzer.utils import (\r\n    Categorizer,\r\n    PathValidator,\r\n    FileHelper,\r\n    ColorHelper\r\n)\r\n\r\n# Categoriza\u00e7\u00e3o\r\ncategorizer = Categorizer()\r\ncategory = categorizer.categorize_file(Path('src/main.py'))\r\npriority = categorizer.determine_priority('file', {'lines': 150, 'type': 'python'})\r\n\r\n# Valida\u00e7\u00e3o\r\nvalidator = PathValidator()\r\nis_valid = validator.is_python_project('/path/to/project')\r\nproject_info = validator.get_project_info('/path/to/project')\r\n\r\n# Helpers\r\nfile_helper = FileHelper()\r\ndata = file_helper.read_json('config.json')\r\nfile_helper.write_json(data, 'output.json')\r\n\r\n# Cores para terminal\r\nprint(ColorHelper.success(\"Sucesso!\"))\r\nprint(ColorHelper.error(\"Erro!\"))\r\nprint(ColorHelper.warning(\"Aviso!\"))\r\n```\r\n\r\n## \ud83e\uddea Testes\r\n\r\n```bash\r\n# Instala depend\u00eancias de desenvolvimento\r\npip install -e \".[dev]\"\r\n\r\n# Executa testes\r\npytest\r\n\r\n# Executa testes com cobertura\r\npytest --cov=codehealthanalyzer\r\n\r\n# Executa linting\r\nruff check codehealthanalyzer/\r\nblack --check codehealthanalyzer/\r\n```\r\n\r\n## \ud83e\uddf0 Ferramentas de Qualidade e Seguran\u00e7a (para seu projeto)\r\n\r\nAl\u00e9m de usar o CodeHealthAnalyzer, recomendamos rodar as seguintes ferramentas diretamente no seu projeto (exemplos a seguir). Substitua `luarco/` pelo diret\u00f3rio do seu projeto.\r\n\r\n### Ruff (Linter & Auto-fix)\r\n\r\n```bash\r\n# Verificar erros com ruff\r\nruff check luarco/\r\n\r\n# Corrigir erros automaticamente (quando poss\u00edvel)\r\nruff check luarco/ --fix\r\n\r\n# Ver apenas erros cr\u00edticos\r\nruff check luarco/ --select=F821,F841,E9\r\n```\r\n\r\n### Black (Formata\u00e7\u00e3o autom\u00e1tica)\r\n\r\n```bash\r\n# Black - Formata\u00e7\u00e3o autom\u00e1tica\r\nblack .\r\n```\r\n\r\n### isort (Organiza\u00e7\u00e3o de imports)\r\n\r\n```bash\r\n# isort - Organiza\u00e7\u00e3o de imports\r\nisort .\r\n```\r\n\r\n### Bandit (Seguran\u00e7a)\r\n\r\n```bash\r\n# bandit - Seguran\u00e7a (gera relat\u00f3rio JSON)\r\nbandit -r luarco/ -f json -o bandit-report.json\r\n```\r\n\r\nObserva\u00e7\u00f5es:\r\n- \u00c9 comum rodar `ruff check --fix`, depois `isort .` e `black .` para padronizar o c\u00f3digo.\r\n- Voc\u00ea pode integrar essas ferramentas no seu CI, semelhante ao nosso workflow em `.github/workflows/ci.yml`.\r\n\r\n## \ud83e\udd1d Contribui\u00e7\u00e3o\r\n\r\n1. Fork o projeto\r\n2. Crie uma branch para sua feature (`git checkout -b feature/AmazingFeature`)\r\n3. Commit suas mudan\u00e7as (`git commit -m 'Add some AmazingFeature'`)\r\n4. Push para a branch (`git push origin feature/AmazingFeature`)\r\n5. Abra um Pull Request\r\n\r\n### Diretrizes de Contribui\u00e7\u00e3o\r\n\r\n- Siga o estilo de c\u00f3digo existente\r\n- Adicione testes para novas funcionalidades\r\n- Atualize a documenta\u00e7\u00e3o quando necess\u00e1rio\r\n- Use commits sem\u00e2nticos\r\n\r\n## \ud83d\udcc4 Licen\u00e7a\r\n\r\nEste projeto est\u00e1 licenciado sob a Licen\u00e7a MIT - veja o arquivo [LICENSE](LICENSE) para detalhes.\r\n\r\n## \ud83d\ude4f Agradecimentos\r\n\r\n- [Ruff](https://github.com/astral-sh/ruff) - Linter Python ultrarr\u00e1pido\r\n- [Click](https://click.palletsprojects.com/) - Framework para CLI\r\n- [Rich](https://github.com/Textualize/rich) - Formata\u00e7\u00e3o rica para terminal\r\n\r\n## \ud83d\udcde Suporte\r\n\r\n- \ud83d\udce7 Email: contato@luarco.com.br\r\n- \ud83d\udc1b Issues: [GitHub Issues](https://github.com/imparcialista/codehealthanalyzer/issues)\r\n- \ud83d\udcd6 Documenta\u00e7\u00e3o: [ReadTheDocs](https://codehealthanalyzer.readthedocs.io/)\r\n\r\n---\r\n\r\n**Feito com \u2764\ufe0f pela equipe Imparcialista**\r\n\r\n---\r\n\r\n# \ud83d\udd0d CodeHealthAnalyzer\r\n\r\n> A comprehensive Python library for code quality and health analysis\r\n\r\n[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)\r\n[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)\r\n[![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\r\n\r\n[\ud83c\udde7\ud83c\uddf7 Portugu\u00eas](README.md) | \ud83c\uddfa\ud83c\uddf8 English\r\n\r\n## \ud83d\ude80 Overview\r\n\r\nCodeHealthAnalyzer 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.\r\n\r\n### \u2728 Key Features\r\n\r\n- **\ud83d\udea8 Violations Analysis**: Detects functions, classes, and modules that exceed size limits\r\n- **\ud83c\udfa8 Template Analysis**: Identifies inline CSS/JS in HTML templates that can be extracted\r\n- **\u26a0\ufe0f Ruff Integration**: Analyzes linting errors and categorizes them by priority\r\n- **\ud83d\udcca Quality Score**: Calculates a 0-100 score based on overall code health\r\n- **\ud83c\udfaf Smart Prioritization**: Suggests actions based on problem criticality\r\n- **\ud83d\udcc8 Multiple Reports**: Generates reports in JSON, HTML, Markdown, and CSV\r\n- **\ud83d\udda5\ufe0f Friendly CLI**: Complete and intuitive command-line interface\r\n- **\ud83d\udd27 Highly Configurable**: Customize limits, rules, and categories\r\n\r\n## \ud83d\udce6 Installation\r\n\r\n### Installation via pip (recommended)\r\n\r\n```bash\r\n# Basic installation\r\npip install codehealthanalyzer\r\n\r\n# Installation with interactive web dashboard\r\npip install codehealthanalyzer[web]\r\n\r\n# Complete installation (web + development)\r\npip install codehealthanalyzer[web,dev]\r\n```\r\n\r\n### Development Installation\r\n\r\n```bash\r\ngit clone https://github.com/imparcialista/codehealthanalyzer.git\r\ncd codehealthanalyzer\r\npip install -e .[web,dev]\r\n```\r\n\r\n### Dependencies\r\n\r\n- Python 3.8+\r\n- ruff >= 0.1.0\r\n- click >= 8.0.0\r\n- rich >= 12.0.0 (optional, for colored output)\r\n\r\n## \ud83c\udfaf Quick Start\r\n\r\n### \ud83c\udf10 Interactive Dashboard\r\n\r\n```bash\r\n# Start web dashboard with real-time metrics\r\ncodehealthanalyzer dashboard .\r\n\r\n# Dashboard on specific host and port\r\ncodehealthanalyzer dashboard . --host 0.0.0.0 --port 8080\r\n\r\n# Dashboard with auto-reload for development\r\ncodehealthanalyzer dashboard . --reload\r\n```\r\n\r\n**Dashboard Features:**\r\n- \ud83d\udcca Real-time metrics with automatic updates\r\n- \ud83d\udcc8 Interactive quality trend charts\r\n- \ud83c\udfaf Violations visualization by type\r\n- \ud83d\udccb Problem files table\r\n- \ud83d\udd04 WebSockets for instant updates\r\n- \ud83d\udcf1 Responsive and modern interface\r\n\r\n### CLI (Command Line Interface)\r\n\r\n```bash\r\n# Complete analysis of current project\r\ncodehealthanalyzer analyze .\r\n\r\n# Analysis with HTML output\r\ncodehealthanalyzer analyze . --format html --output reports/\r\n\r\n# Quality score only\r\ncodehealthanalyzer score .\r\n\r\n# Project information\r\ncodehealthanalyzer info .\r\n\r\n# Specific violations analysis\r\ncodehealthanalyzer violations . --output violations.json\r\n```\r\n\r\n### Python API\r\n\r\n```python\r\nfrom codehealthanalyzer import CodeAnalyzer\r\n\r\n# Initialize analyzer\r\nanalyzer = CodeAnalyzer('/path/to/project')\r\n\r\n# Generate complete report\r\nreport = analyzer.generate_full_report(output_dir='reports/')\r\n\r\n# Get quality score\r\nscore = analyzer.get_quality_score()\r\nprint(f\"Quality Score: {score}/100\")\r\n\r\n# Individual analyses\r\nviolations = analyzer.analyze_violations()\r\ntemplates = analyzer.analyze_templates()\r\nerrors = analyzer.analyze_errors()\r\n```\r\n\r\n## \ud83d\udcca Example Output\r\n\r\n```\r\n\ud83d\udcca ANALYSIS SUMMARY\r\n==================================================\r\n\u2705 Quality Score: 85/100 - Excellent!\r\n\ud83d\udcc1 Files analyzed: 124\r\n\u26a0\ufe0f  Files with violations: 8\r\n\ud83c\udfa8 Templates: 15\r\n\ud83d\udd0d Ruff Errors: 0\r\n\ud83d\udd25 High priority issues: 2\r\n\r\n\ud83c\udfaf ACTION PRIORITIES:\r\n1. \ud83d\udd34 High Priority Violations (2)\r\n2. \ud83d\udfe1 Templates with Too Much Inline CSS/JS (3)\r\n```\r\n\r\n## \ud83d\udd27 Configuration\r\n\r\n### JSON Configuration File\r\n\r\n```json\r\n{\r\n  \"limits\": {\r\n    \"python_function\": {\"yellow\": 30, \"red\": 50},\r\n    \"python_class\": {\"yellow\": 300, \"red\": 500},\r\n    \"python_module\": {\"yellow\": 500, \"red\": 1000},\r\n    \"html_template\": {\"yellow\": 150, \"red\": 200},\r\n    \"test_file\": {\"yellow\": 400, \"red\": 600}\r\n  },\r\n  \"target_dir\": \"src/\",\r\n  \"file_rules\": {\r\n    \"critical_files\": [\"main.py\", \"core.py\"],\r\n    \"skip_patterns\": [\".git\", \"__pycache__\", \"node_modules\"]\r\n  }\r\n}\r\n```\r\n\r\n### Usage with Configuration\r\n\r\n```bash\r\ncodehealthanalyzer analyze . --config config.json\r\n```\r\n\r\n```python\r\nimport json\r\nfrom codehealthanalyzer import CodeAnalyzer\r\n\r\nwith open('config.json') as f:\r\n    config = json.load(f)\r\n\r\nanalyzer = CodeAnalyzer('/path/to/project', config)\r\n```\r\n\r\n## \ud83d\udcc8 Analysis Types\r\n\r\n### \ud83d\udea8 Violations Analysis\r\n\r\nDetects:\r\n- Functions too long (> 50 lines)\r\n- Classes too large (> 500 lines)\r\n- Modules too extensive (> 1000 lines)\r\n- HTML templates too long (> 200 lines)\r\n\r\n### \ud83c\udfa8 Template Analysis\r\n\r\nIdentifies:\r\n- Inline CSS in `style` attributes\r\n- Inline JavaScript in events (`onclick`, etc.)\r\n- `<style>` tags with too much content\r\n- `<script>` tags with too much code\r\n\r\n### \u26a0\ufe0f Error Analysis\r\n\r\nIntegrates with Ruff to detect:\r\n- Syntax errors\r\n- Style issues\r\n- Unused imports\r\n- Undefined variables\r\n- Excessive complexity\r\n\r\n## \ud83d\udcca Quality Score\r\n\r\nThe score is calculated based on:\r\n- **High priority violations**: -10 points each\r\n- **Linting errors**: -2 points each\r\n- **Problematic templates**: -5 points each\r\n- **Base**: 100 points\r\n\r\n### Interpretation\r\n- **80-100**: \ud83d\udfe2 Excellent\r\n- **60-79**: \ud83d\udfe1 Good\r\n- **0-59**: \ud83d\udd34 Needs improvement\r\n\r\n## \ud83c\udf10 Internationalization\r\n\r\n### Language Support\r\n\r\nCodeHealthAnalyzer supports multiple languages:\r\n- **Portuguese (Brazil)**: Default language\r\n- **English**: Full translation available\r\n\r\n### Setting Language\r\n\r\n```python\r\nfrom codehealthanalyzer.i18n import set_language\r\n\r\n# Set to English\r\nset_language('en')\r\n\r\n# Set to Portuguese (Brazil)\r\nset_language('pt_BR')\r\n\r\n# Auto-detect system language\r\nfrom codehealthanalyzer.i18n import auto_configure_language\r\nauto_configure_language()\r\n```\r\n\r\n### Environment Variable\r\n\r\n```bash\r\n# Set language via environment\r\nexport CODEHEALTHANALYZER_LANG=en\r\ncodehealthanalyzer analyze .\r\n```\r\n\r\n## \ud83d\udee0\ufe0f Advanced API\r\n\r\n### Individual Analyzers\r\n\r\n```python\r\nfrom codehealthanalyzer.analyzers import (\r\n    ViolationsAnalyzer,\r\n    TemplatesAnalyzer,\r\n    ErrorsAnalyzer\r\n)\r\n\r\n# Specific violations analysis\r\nviolations_analyzer = ViolationsAnalyzer('/path/to/project')\r\nviolations_report = violations_analyzer.analyze()\r\n\r\n# Specific templates analysis\r\ntemplates_analyzer = TemplatesAnalyzer('/path/to/project')\r\ntemplates_report = templates_analyzer.analyze()\r\n\r\n# Specific errors analysis\r\nerrors_analyzer = ErrorsAnalyzer('/path/to/project')\r\nerrors_report = errors_analyzer.analyze()\r\n```\r\n\r\n### Report Generation\r\n\r\n```python\r\nfrom codehealthanalyzer.reports import ReportGenerator, ReportFormatter\r\n\r\ngenerator = ReportGenerator()\r\nformatter = ReportFormatter()\r\n\r\n# Generate consolidated report\r\nfull_report = generator.generate_full_report(\r\n    violations=violations_report,\r\n    templates=templates_report,\r\n    errors=errors_report,\r\n    output_dir='reports/'\r\n)\r\n\r\n# Convert to different formats\r\nhtml_content = generator.generate_html_report(full_report, 'report.html')\r\nmarkdown_content = formatter.to_markdown(full_report, 'report.md')\r\nformatter.to_csv(full_report, 'report.csv')\r\n```\r\n\r\n## \ud83e\uddea Testing\r\n\r\n```bash\r\n# Install development dependencies\r\npip install -e \".[dev]\"\r\n\r\n# Run tests\r\npytest\r\n\r\n# Run tests with coverage\r\npytest --cov=codehealthanalyzer\r\n\r\n# Run linting\r\nruff check codehealthanalyzer/\r\nblack --check codehealthanalyzer/\r\n```\r\n\r\n## \ud83e\udd1d Contributing\r\n\r\n1. Fork the project\r\n2. Create a feature branch (`git checkout -b feature/AmazingFeature`)\r\n3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)\r\n4. Push to the branch (`git push origin feature/AmazingFeature`)\r\n5. Open a Pull Request\r\n\r\n### Contribution Guidelines\r\n\r\n- Follow existing code style\r\n- Add tests for new features\r\n- Update documentation when necessary\r\n- Use semantic commits\r\n\r\n## \ud83d\udcc4 License\r\n\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n## \ud83d\ude4f Acknowledgments\r\n\r\n- [Ruff](https://github.com/astral-sh/ruff) - Ultra-fast Python linter\r\n- [Click](https://click.palletsprojects.com/) - CLI framework\r\n- [Rich](https://github.com/Textualize/rich) - Rich terminal formatting\r\n\r\n## \ud83d\udcde Support\r\n\r\n- \ud83d\udce7 Email: contato@luarco.com.br\r\n- \ud83d\udc1b Issues: [GitHub Issues](https://github.com/imparcialista/codehealthanalyzer/issues)\r\n- \ud83d\udcd6 Documentation: [ReadTheDocs](https://codehealthanalyzer.readthedocs.io/)\r\n\r\n---\r\n\r\n**Made with \u2764\ufe0f by the Imparcialista team**\r\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Biblioteca Python para an\u00e1lise de qualidade e sa\u00fade de c\u00f3digo",
    "version": "1.1.9",
    "project_urls": {
        "Bug Reports": "https://github.com/imparcialista/codehealthanalyzer/issues",
        "Documentation": "https://codehealthanalyzer.readthedocs.io/",
        "Homepage": "https://github.com/imparcialista/codehealthanalyzer",
        "Source": "https://github.com/imparcialista/codehealthanalyzer"
    },
    "split_keywords": [
        "code-quality",
        " static-analysis",
        " code-health",
        " linting",
        " python",
        " html",
        " css",
        " javascript",
        " ruff",
        " analysis",
        " metrics",
        " reporting"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "862511b22103aadb14986cadbc1431722d30e2192542bd8880f57f91be67fcf0",
                "md5": "f540f8f4fb68996ec10bf21298c9a8c8",
                "sha256": "3c72116e7bac2ac008f63ba45606e4c32475444146ca6e9cb20da87139e7d44c"
            },
            "downloads": -1,
            "filename": "codehealthanalyzer-1.1.9-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f540f8f4fb68996ec10bf21298c9a8c8",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 53116,
            "upload_time": "2025-10-11T12:50:52",
            "upload_time_iso_8601": "2025-10-11T12:50:52.473400Z",
            "url": "https://files.pythonhosted.org/packages/86/25/11b22103aadb14986cadbc1431722d30e2192542bd8880f57f91be67fcf0/codehealthanalyzer-1.1.9-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0f2d6fb716fc3c7c016a00056fa3ce371cfedccc5bf3ac245a15da13dcb86e61",
                "md5": "796b001aa56d6c93658ee96872675ea6",
                "sha256": "3126c3c2df55c273fcbae53b513c22098a40fce006fa000eaa1cff1397f43c3e"
            },
            "downloads": -1,
            "filename": "codehealthanalyzer-1.1.9.tar.gz",
            "has_sig": false,
            "md5_digest": "796b001aa56d6c93658ee96872675ea6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 59752,
            "upload_time": "2025-10-11T12:50:53",
            "upload_time_iso_8601": "2025-10-11T12:50:53.636385Z",
            "url": "https://files.pythonhosted.org/packages/0f/2d/6fb716fc3c7c016a00056fa3ce371cfedccc5bf3ac245a15da13dcb86e61/codehealthanalyzer-1.1.9.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-11 12:50:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "imparcialista",
    "github_project": "codehealthanalyzer",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "ruff",
            "specs": [
                [
                    ">=",
                    "0.1.0"
                ]
            ]
        },
        {
            "name": "click",
            "specs": [
                [
                    ">=",
                    "8.0.0"
                ]
            ]
        },
        {
            "name": "rich",
            "specs": [
                [
                    ">=",
                    "12.0.0"
                ]
            ]
        },
        {
            "name": "fastapi",
            "specs": [
                [
                    ">=",
                    "0.104.0"
                ]
            ]
        },
        {
            "name": "uvicorn",
            "specs": [
                [
                    ">=",
                    "0.24.0"
                ]
            ]
        },
        {
            "name": "jinja2",
            "specs": [
                [
                    ">=",
                    "3.1.0"
                ]
            ]
        },
        {
            "name": "python-multipart",
            "specs": [
                [
                    ">=",
                    "0.0.6"
                ]
            ]
        },
        {
            "name": "websockets",
            "specs": [
                [
                    ">=",
                    "12.0"
                ]
            ]
        }
    ],
    "lcname": "codehealthanalyzer"
}
        
Elapsed time: 4.00309s