Skill Code Review |
This project builds a code review Skill: after users upload code files, it automatically analyzes code quality, style issues, and potential bugs.
Objective: Master toolchain integration and generation of structured issue reports.
Project Requirements Analysis
| Feature | Supported Languages | Tools |
|---|---|---|
| Syntax checking | Python | py_compile (built-in) |
| Code style checking | Python | flake8 |
| Code complexity analysis | Python | radon |
| JavaScript checking | JS/TS | eslint (npx) |
| Comprehensive issue report | All | Custom aggregation script |
Directory Structure
code-reviewer/
βββ SKILL.md
βββ scripts/
βββ requirements.txt
βββ check_python.py
βββ check_js.py
βββ generate_report.py
Python Code Review Script
Example
# File path: scripts/check_python.py
import subprocess
import sys
import json
import os
def ensure_tools():
"""Ensure required tools are installed"""
for pkg in ["flake8", "radon"]:
try:
__import__(pkg.replace("-", "_"))
except ImportError:
subprocess.run([sys.executable, "-m", "pip", "install", pkg,
"--break-system-packages", "--quiet"])
def check_syntax(file_path: str) -> dict:
"""Check Python syntax"""
result = subprocess.run(
[sys.executable, "-m", "py_compile", file_path],
capture_output=True, text=True
)
if result.returncode == 0:
return {"passed": True, "errors": []}
return {
"passed": False,
"errors": [result.stderr.strip()]
}
def check_style(file_path: str) -> list:
"""Run flake8 to check code style; return list of issues"""
result = subprocess.run(
["python", "-m", "flake8", file_path,
"--max-line-length=100",
"--format=%(row)d:%(col)d %(code)s %(text)s"],
capture_output=True, text=True
)
issues = []
for line in result.stdout.strip().splitlines():
parts = line.split(" ", 2)
if len(parts) >= 3:
loc, code, text = parts
row, col = loc.split(":")
issues.append({
"line": int(row), "col": int(col),
"code": code, "message": text
})
return issues
def check_complexity(file_path: str) -> list:
"""Analyze function complexity using radon; return functions with high complexity"""
result = subprocess.run(
["python", "-m", "radon", "cc", file_path, "-s", "--json"],
capture_output=True, text=True
)
try:
data = json.loads(result.stdout)
functions = data.get(file_path, [])
# Only return functions with rank C or worse (complexity > 10)
return [
{"name": f, "complexity": f,
"rank": f, "line": f}
for f in functions
if f.get("rank", "A") in ("C", "D", "E", "F")
]
except Exception:
return []
def review_python(file_path: str) -> dict:
"""Perform complete Python code review"""
if not os.path.exists(file_path):
return {"status": "error", "message": f"File not found: {file_path}"}
ensure_tools()
syntax = check_syntax(file_path)
style = check_style(file_path) if syntax else []
complexity = check_complexity(file_path) if syntax else []
# Compute overall grade
error_count = len([i for i in style if i.startswith("E")])
warning_count = len([i for i in style if i.startswith("W")])
if not syntax:
grade = "F"
elif error_count > 10:
grade = "C"
elif error_count > 3:
grade = "B"
else:
grade = "A"
return {
"status": "success",
"file": os.path.basename(file_path),
"grade": grade,
"syntax_ok": syntax,
"syntax_errors": syntax,
"style_issues": style[:20], # Show up to 20 issues
"style_count": len(style),
"error_count": error_count,
"warning_count": warning_count,
"complex_functions": complexity
}
if __name__ == "__main__":
result = review_python(sys.argv if len(sys.argv) > 1 else "")
print(json.dumps(result, ensure_ascii=False, indent=2))
Output:
{ "status": "success", "file": "tutorial_app.py", "grade": "B", "syntax_ok": true, "style_issues": [ {"line": 12, "col": 1, "code": "E302", "message": "expected 2 blank lines"}, {"line": 34, "col": 80, "code": "E501", "message": "line too long (103 > 100)"} ], "style_count": 5, "error_count": 3, "warning_count": 2, "complex_functions": []}
Full Content of SKILL.md
---
name: code-reviewer
version: 1.0.0
description: >
Automatically reviews user-uploaded code files, checking for syntax errors,
style issues, and code complexity, and generates graded reports with improvement suggestions.
Triggered when users need code review, code quality checks, bug detection, or compliance evaluation.
---
# Code Review Assistant
## Execution Flow
### Step 1: Identify Code File
Get the user-uploaded code file path and identify the programming language (by extension):
- `.py` β Python review
- `.js` / `.ts` β JavaScript/TypeScript review
- Other formats β Notify user that itβs unsupported; list supported formats
### Step 2: Run Automated Checks
For Python files, run:
```bash
cd scripts/
python check_python.py <file_path>
### Step 3: Generate and Interpret Report
Present results in a user-friendly way based on the JSON output:
1. **Overall Grade**: A (Excellent) / B (Good) / C (Needs Improvement) / F (Syntax Error)
2. **Issue Summary Table**: Line number, issue code, description
3. **Top 3 Priority Fixes**: Select the 3 most severe issues, provide fix suggestions and examples
If no issues are found, provide a brief positive comment:
> Code review passed! Scanned X lines; no syntax errors or obvious style issues found.
Test Cases
Example
# File path: scripts/tests/test_sample.py (sample file for testing the review Skill)
# Intentionally includes common issues to verify review functionality
import os,sys # E401: Multiple imports on one line (style issue)
import json
def processData(data): # N802: Function name should be snake_case
x = 1 # F841: Local variable 'x' assigned but never used
result = [] # E225: Missing whitespace around assignment
for i in data:
if i > 0:
result.append(i)
elif i == 0:
pass
else:
result.append(-i)
return result
class myClass: # N801: Class name should be CamelCase
pass
Run review:
cd scripts/
python check_python.py tests/test_sample.py
Output:
{ "status": "success", "file": "test_sample.py", "grade": "B", "syntax_ok": true, "style_count": 5, "error_count": 4, "warning_count": 1, "complex_functions": []}
YouTip