File size: 9,976 Bytes
fcb2b04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""
Code quality evaluation for Stack 2.9
Assesses syntactic correctness, style compliance, complexity, and bug potential
"""

import os
import ast
import subprocess
from pathlib import Path
from typing import Dict, List, Any, Tuple
import radon
from radon.complexity import cc_visit, cc_rank
from radon.raw import analyze
from radon.metrics import h_visit, h_visit_ast

class CodeQualityEvaluator:
    def __init__(self, code_directory: str = "."):
        self.code_directory = Path(code_directory)
        self.results = {}
        self.issues = []
    
    def evaluate_directory(self) -> Dict[str, Any]:
        """Evaluate all Python files in a directory"""
        print(f"Evaluating code quality in {self.code_directory}...")
        
        python_files = list(self.code_directory.rglob("*.py"))
        print(f"Found {len(python_files)} Python files")
        
        for file_path in python_files:
            self._evaluate_file(file_path)
        
        return {
            "summary": self._generate_summary(),
            "detailed_results": self.results,
            "issues": self.issues
        }
    
    def _evaluate_file(self, file_path: Path) -> None:
        """Evaluate a single Python file"""
        print(f"Evaluating {file_path}...")
        
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
        except Exception as e:
            self._log_issue(file_path, f"Error reading file: {e}")
            return
        
        # Syntactic correctness
        syntax_result = self._check_syntax(content, file_path)
        
        # Style compliance (PEP8)
        style_result = self._check_style(file_path)
        
        # Complexity metrics
        complexity_result = self._analyze_complexity(content, file_path)
        
        # Bug potential analysis
        bug_result = self._analyze_bugs(content, file_path)
        
        self.results[str(file_path)] = {
            "syntax": syntax_result,
            "style": style_result,
            "complexity": complexity_result,
            "bug_potential": bug_result
        }
    
    def _check_syntax(self, content: str, file_path: Path) -> Dict[str, Any]:
        """Check syntactic correctness"""
        try:
            ast.parse(content)
            return {
                "valid": True,
                "errors": []
            }
        except SyntaxError as e:
            self._log_issue(file_path, f"Syntax error: {e}")
            return {
                "valid": False,
                "errors": [str(e)],
                "line": e.lineno,
                "offset": e.offset
            }
        except Exception as e:
            self._log_issue(file_path, f"Unexpected error: {e}")
            return {
                "valid": False,
                "errors": [str(e)]
            }
    
    def _check_style(self, file_path: Path) -> Dict[str, Any]:
        """Check style compliance using pycodestyle"""
        try:
            # Run pycodestyle
            result = subprocess.run([
                "pycodestyle", 
                str(file_path),
                "--ignore=E501,W503"  # Ignore line length and operator issues
            ], capture_output=True, text=True)
            
            errors = result.stdout.strip().split('\n') if result.stdout else []
            error_count = len(errors)
            
            return {
                "compliant": error_count == 0,
                "errors": errors,
                "error_count": error_count,
                "total_warnings": len([e for e in errors if 'warning' in e.lower()]),
                "total_errors": len([e for e in errors if 'error' in e.lower()])
            }
            
        except FileNotFoundError:
            self._log_issue(file_path, "pycodestyle not found")
            return {
                "compliant": False,
                "errors": ["pycodestyle not installed"],
                "error_count": 1
            }
        except Exception as e:
            self._log_issue(file_path, f"Style check error: {e}")
            return {
                "compliant": False,
                "errors": [str(e)],
                "error_count": 1
            }
    
    def _analyze_complexity(self, content: str, file_path: Path) -> Dict[str, Any]:
        """Analyze code complexity using radon"""
        try:
            # Cyclomatic complexity
            cc_results = cc_visit(content)
            
            # Halstead metrics
            h_results = h_visit(content)
            
            # Raw metrics
            raw_results = analyze(content)
            
            return {
                "cyclomatic_complexity": {
                    "average": sum(cc.rank for cc in cc_results) / len(cc_results) if cc_results else 0,
                    "max": max(cc.rank for cc in cc_results) if cc_results else 0,
                    "functions": [{
                        "name": cc.name,
                        "complexity": cc.rank,
                        "lineno": cc.lineno
                    } for cc in cc_results]
                },
                "halstead": {
                    "effort": h_results.effort,
                    "volume": h_results.volume,
                    "difficulty": h_results.difficulty
                },
                "raw": {
                    "loc": raw_results.loc,
                    "lloc": raw_results.lloc,
                    "sloc": raw_results.sloc,
                    "comments": raw_results.comments
                }
            }
            
        except Exception as e:
            self._log_issue(file_path, f"Complexity analysis error: {e}")
            return {
                "error": str(e)
            }
    
    def _analyze_bugs(self, content: str, file_path: Path) -> Dict[str, Any]:
        """Analyze potential bugs"""
        issues = []
        
        # Check for common bug patterns
        tree = ast.parse(content)
        
        # Check for bare except statements
        for node in ast.walk(tree):
            if isinstance(node, ast.ExceptHandler) and node.type is None:
                issues.append({
                    "type": "bare_except",
                    "lineno": node.lineno,
                    "message": "Bare except clause found"
                })
        
        # Check for mutable default arguments
        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                for default in node.args.defaults:
                    if isinstance(default, (ast.List, ast.Dict, ast.Set)):
                        issues.append({
                            "type": "mutable_default",
                            "lineno": default.lineno,
                            "message": "Mutable default argument found"
                        })
        
        return {
            "potential_issues": issues,
            "issue_count": len(issues)
        }
    
    def _log_issue(self, file_path: Path, message: str) -> None:
        """Log an issue"""
        self.issues.append({
            "file": str(file_path),
            "message": message
        })
    
    def _generate_summary(self) -> Dict[str, Any]:
        """Generate summary statistics"""
        total_files = len(self.results)
        
        syntax_errors = sum(1 for r in self.results.values() if not r["syntax"]["valid"])
        style_errors = sum(r["style"]["error_count"] for r in self.results.values())
        
        return {
            "total_files": total_files,
            "syntax_errors": syntax_errors,
            "style_errors": style_errors,
            "average_complexity": self._calculate_average_complexity(),
            "total_issues": len(self.issues)
        }
    
    def _calculate_average_complexity(self) -> float:
        """Calculate average cyclomatic complexity"""
        complexities = []
        for result in self.results.values():
            if "complexity" in result and "cyclomatic_complexity" in result["complexity"]:
                complexities.append(result["complexity"]["cyclomatic_complexity"]["average"])
        
        return sum(complexities) / len(complexities) if complexities else 0
    
    def generate_report(self) -> str:
        """Generate markdown report"""
        summary = self._generate_summary()
        
        report = f"""# Code Quality Evaluation Report

## Summary
Evaluation of code quality for Stack 2.9.

## Overall Statistics

| Metric | Value |
|--------|-------|
| Total Files Evaluated | {summary[\"total_files\"]} |
| Files with Syntax Errors | {summary[\"syntax_errors\"]} |
| Total Style Issues | {summary[\"style_errors\"]} |
| Average Cyclomatic Complexity | {summary[\"average_complexity"]:.2f} |
| Total Issues Found | {summary[\"total_issues\"]} |

## Detailed Results

"""
        
        for file_path, result in self.results.items():
            report += f"""### {file_path}

- **Syntax**: {\"Valid\" if result[\"syntax\"][\"valid\"] else \"Invalid\"}
- **Style Issues**: {result[\"style\"][\"error_count\"]}
- **Cyclomatic Complexity**: {result[\"complexity\"][\"cyclomatic_complexity\"][\"average\"]:.2f}
- **Bug Potential Issues**: {result[\"bug_potential\"][\"issue_count\"]}

"""
        
        if self.issues:
            report += """## Issues

"""
            for issue in self.issues:
                report += f"""- **{issue[\"file\"]}** {issue[\"message\"]}

"""
        
        return report


if __name__ == "__main__":
    evaluator = CodeQualityEvaluator()
    results = evaluator.evaluate_directory()
    
    print("Code Quality Evaluation Complete!")
    print(json.dumps(results, indent=2))
    
    report = evaluator.generate_report()
    print(report)
    
    # Save results
    with open("results/code_quality_evaluation.json", 'w') as f:
        json.dump(results, f, indent=2)
    
    with open("results/code_quality_report.md", 'w') as f:
        f.write(report)