Ontwerp een geautomatiseerde code formatterings- en style-checker
description
Met deze prompt kan de gebruiker een geautomatiseerde tool ontwerpen die helpt om consistente codekwaliteit en stijl te waarborgen. Dit vermindert handmatig werk, verbetert samenwerking binnen teams en voorkomt stijlproblemen vroeg in het ontwikkelproces. Het biedt duidelijke architectuuradviezen en praktische voorbeelden voor implementatie en integratie, waardoor het gebruiksvriendelijker en effectiever is dan losse styleguides of handmatige reviews.
prompt
Help me een geautomatiseerde tool te ontwerpen die mijn code controleert op stijl- en formatteerregels. Beschrijf de architectuur en geef een voor ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Hier is een overzicht van een geautomatiseerde tool voor codecontrole, inclusief architectuur en een voorbeeld in Python, plus integratiesuggesties.
**Architectuur van de tool**
1. **Input Module**
- Leest broncodebestanden of projectmappen in.
- Ondersteunt meerdere talen of richt zich op één taal (bijvoorbeeld Python).
2. **Analysemodule**
- Controleert code op stijl- en formatteringsregels.
- Gebruikt bestaande linters of parser-tools (bijv. `flake8`, `pylint`, `black` voor Python).
3. **Rapportagemodule**
- Verzamelt bevindingen.
- Geeft overzicht (bijv. via console, HTML, JSON).
4. **Automatische Correctie (optioneel)**
- Past code automatisch aan volgens regels (bijv. via `black`).
5. **Configuratie**
- Gebruikers kunnen regels en stijlgidsen aanpassen via config-bestanden.
**Voorbeeldimplementatie in Python**
Hier gebruiken we `pylint` en `black` als voorbeeld:
```python
import subprocess
import os
def controleer_code(pad_naar_code, config_pybint=None, config_black=None):
# Stap 1: Controleer code met pylint
pylint_cmd = ["pylint", pad_naar_code]
if config_pybint:
pylint_cmd.extend(["--rcfile", config_pybint])
result_pylint = subprocess.run(pylint_cmd, capture_output=True, text=True)
# Stap 2: Format code met black
black_cmd = ["black"]
if config_black:
black_cmd.extend(["--config", config_black])
black_cmd.append(pad_naar_code)
subprocess.run(black_cmd)
# Output resultaten
print("Pylint rapport:\n", result_pylint.stdout)
print("Code is automatisch geformatteerd met Black.")
# Voorbeeld gebruik
if __name__ == "__main__":
project_dir = "mijn_code"
controleer_code(project_dir, config_pybint="pylint.cfg", config_black="pyproject.toml")
```
**Integratie met ontwikkeltools en workflows**
- **IDE-integratie**:
- Voeg deze tool toe als externe linter of formatter in IDE’s zoals VSCode, PyCharm.
- Gebruik VSCode Tasks of IDE-extensies om controleren en formatteren uit te voeren.
- **Pre-commit hooks**:
- Gebruik `pre-commit` framework.
- Configureer `.pre-commit-config.yaml` om pylint en black te draaien vóór commits.
- **CI/CD pipelines**:
- Integreer in Jenkins, GitHub Actions, GitLab CI.
- Laat de pipeline falen bij stijl- of formatteringsfouten.
- **Automatisering en feedback**:
- Geef directe feedback via pull request checks.
- Gebruik rapportages en dashboards voor overzicht.
Met deze architectuur en implementatie kun je een robuuste, schaalbare en gemakkelijk te integreren codecontrole-oplossing opzetten.
provider: deepseek
model: deepseek-chat
Zeker, hier is een gedetailleerd ontwerp voor een geautomatiseerde code-stijlcontroletool in Python.
### Architectuur van de Tool
**1. Gelaagde Architectuur:**
```
Input Laag → Verwerkingslaag → Analyse Laag → Output Laag
```
**2. Componenten:**
- **Configuratiemanager**: Beheert stijlregels (.ini, .toml of .json)
- **Bestandsverkenner**: Recursieve directory scanning
- **Parser/Tokenizer**: Taalspecifieke syntax parsing
- **Regelcontrolemodule**: Implementeert individuele stijlchecks
- **Rapportgenerator**: Genereert mens- en machine-leesbare rapporten
- **Integratiemodule**: Voor CI/CD en editor integratie
**3. Regeldefinitie:**
Elke stijlregel is een onafhankelijke eenheid met:
- Unieke identifier
- Beschrijving
- Severity niveau (error, warning, info)
- Configureerbare parameters
### Voorbeeldimplementatie in Python
```python
import ast
import os
import argparse
from pathlib import Path
from typing import List, Dict, Any
import json
class StyleChecker:
def __init__(self, config_path: str = None):
self.config = self._load_config(config_path)
self.violations = []
def _load_config(self, config_path: str) -> Dict[str, Any]:
"""Laad configuratiebestand"""
default_config = {
"max_line_length": 88,
"function_naming_convention": "snake_case",
"class_naming_convention": "PascalCase",
"forbid_trailing_whitespace": True,
"require_docstrings": False
}
if config_path and os.path.exists(config_path):
with open(config_path, 'r') as f:
return {**default_config, **json.load(f)}
return default_config
def check_file(self, file_path: str) -> List[Dict]:
"""Controleer een enkel bestand"""
self.violations = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
tree = ast.parse(content)
self._check_line_lengths(content, file_path)
self._check_naming_conventions(tree, file_path)
self._check_trailing_whitespace(content, file_path)
except SyntaxError as e:
self.violations.append({
'file': file_path,
'line': e.lineno,
'rule': 'SYNTAX_ERROR',
'message': f'Syntaxfout: {e.msg}',
'severity': 'error'
})
return self.violations
def _check_line_lengths(self, content: str, file_path: str):
"""Controleer maximale regelengte"""
max_length = self.config.get('max_line_length', 88)
lines = content.split('\n')
for i, line in enumerate(lines, 1):
if len(line) > max_length:
self.violations.append({
'file': file_path,
'line': i,
'rule': 'E001',
'message': f'Regel te lang ({len(line)} > {max_length} tekens)',
'severity': 'warning'
})
def _check_naming_conventions(self, tree: ast.AST, file_path: str):
"""Controleer naamgevingsconventies"""
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
self._check_function_name(node, file_path)
elif isinstance(node, ast.ClassDef):
self._check_class_name(node, file_path)
def _check_function_name(self, node: ast.FunctionDef, file_path: str):
convention = self.config.get('function_naming_convention', 'snake_case')
name = node.name
if convention == 'snake_case' and not name.islower():
self.violations.append({
'file': file_path,
'line': node.lineno,
'rule': 'E002',
'message': f'Functienaam "{name}" moet snake_case zijn',
'severity': 'error'
})
def _check_class_name(self, node: ast.ClassDef, file_path: str):
convention = self.config.get('class_naming_convention', 'PascalCase')
name = node.name
if convention == 'PascalCase' and not name[0].isupper():
self.violations.append({
'file': file_path,
'line': node.lineno,
'rule': 'E003',
'message': f'Classnaam "{name}" moet PascalCase zijn',
'severity': 'error'
})
def _check_trailing_whitespace(self, content: str, file_path: str):
"""Controleer op trailing whitespace"""
if self.config.get('forbid_trailing_whitespace', True):
lines = content.split('\n')
for i, line in enumerate(lines, 1):
if line.rstrip() != line:
self.violations.append({
'file': file_path,
'line': i,
'rule': 'E004',
'message': 'Trailing whitespace gedetecteerd',
'severity': 'warning'
})
def main():
parser = argparse.ArgumentParser(description='Python code style checker')
parser.add_argument('path', help='Bestand of directory om te controleren')
parser.add_argument('--config', '-c', help='Pad naar configuratiebestand')
parser.add_argument('--format', '-f', choices=['text', 'json'], default='text')
args = parser.parse_args()
checker = StyleChecker(args.config)
violations = []
path = Path(args.path)
if path.is_file() and path.suffix == '.py':
violations.extend(checker.check_file(str(path)))
elif path.is_dir():
for py_file in path.rglob('*.py'):
violations.extend(checker.check_file(str(py_file)))
if args.format == 'json':
print(json.dumps(violations, indent=2))
else:
for violation in violations:
print(f"{violation['file']}:{violation['line']}: {violation['severity']}: {violation['message']}")
if violations:
exit(1)
if __name__ == '__main__':
main()
```
### Integratiesuggesties
**1. Pre-commit Hook:**
```python
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: python-style-check
name: Python Style Check
entry: python style_checker.py
language: system
files: \.py$
```
**2. CI/CD Pipeline (GitHub Actions):**
```yaml
# .github/workflows/style-check.yml
name: Code Style Check
on: [push, pull_request]
jobs:
style-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
- name: Run style checker
run: python style_checker.py . --format text
```
**3. Editor Integratie:**
- **VS Code**: `.vscode/settings.json`
```json
{
"python.linting.enabled": true,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": false,
"python.linting.mypyEnabled": false,
"python.linting.styleCheckEnabled": true,
"python.linting.styleCheckPath": "style_checker.py"
}
```
**4. Makefile Integratie:**
```makefile
.PHONY: style-check
style-check:
python style_checker.py . --config .styleconfig.json
.PHONY: test
test: style-check
pytest tests/
```
### Aanbevolen Uitbreidingen
1. **Pluginsysteem**: Maak het extensibel met custom rules
2. **Auto-fix functionaliteit**: Automatisch repareren van stijlfouten
3. **Meertalige ondersteuning**: Uitbreiden naar andere programmeertalen
4. **Caching mechanisme**: Prestaties verbeteren bij grote codebases
5. **Diff-based checking**: Alleen gewijzigde code controleren
### Gebruik:
```bash
# Enkel bestand
python style_checker.py mijn_script.py
# Hele directory
python style_checker.py src/ --config .styleconfig.json
# JSON output voor CI
python style_checker.py . --format json
```
Deze tool kan worden uitgebreid met aanvullende stijlregels en geïntegreerd in je bestaande ontwikkelworkflow voor consistente codekwaliteit.
error: Generation failed [deepseek] prompt_id=1336 locale=fr err=DeepSeek connection/timeout