-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpre-commit-check.py
More file actions
370 lines (306 loc) · 12.1 KB
/
pre-commit-check.py
File metadata and controls
370 lines (306 loc) · 12.1 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python
"""
Pre-commit quality check script for the RAG system.
This script runs a comprehensive suite of quality checks including:
- Code formatting (ruff format)
- Linting (ruff check)
- Type checking (pyright)
- Security checks (bandit)
- Unit tests (pytest)
- Test coverage
"""
import argparse
import subprocess
import sys
from pathlib import Path
from typing import Optional
# Set UTF-8 encoding for Windows console
if sys.platform == "win32":
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
class Colors:
"""ANSI color codes for terminal output."""
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
class QualityChecker:
"""Main quality checker class."""
def __init__(self, fix: bool = False, skip_tests: bool = False, verbose: bool = False):
"""
Initialize the quality checker.
Args:
fix: Whether to automatically fix issues
skip_tests: Whether to skip running tests
verbose: Whether to show verbose output
"""
self.fix = fix
self.skip_tests = skip_tests
self.verbose = verbose
self.results: list[tuple[str, bool, Optional[str]]] = []
def print_header(self, message: str) -> None:
"""Print a formatted header."""
print(f"\n{Colors.HEADER}{Colors.BOLD}{'=' * 70}{Colors.ENDC}")
print(f"{Colors.HEADER}{Colors.BOLD}{message}{Colors.ENDC}")
print(f"{Colors.HEADER}{Colors.BOLD}{'=' * 70}{Colors.ENDC}\n")
def print_step(self, message: str) -> None:
"""Print a step message."""
print(f"{Colors.OKCYAN}> {message}...{Colors.ENDC}")
def print_success(self, message: str) -> None:
"""Print a success message."""
print(f"{Colors.OKGREEN}+ {message}{Colors.ENDC}")
def print_warning(self, message: str) -> None:
"""Print a warning message."""
print(f"{Colors.WARNING}! {message}{Colors.ENDC}")
def print_error(self, message: str) -> None:
"""Print an error message."""
print(f"{Colors.FAIL}x {message}{Colors.ENDC}")
def run_command(
self, cmd: list[str], check_name: str, success_msg: str, error_msg: str
) -> bool:
"""
Run a command and track results.
Args:
cmd: Command to run
check_name: Name of the check
success_msg: Message to show on success
error_msg: Message to show on error
Returns:
True if command succeeded, False otherwise
"""
self.print_step(check_name)
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode == 0:
self.print_success(success_msg)
self.results.append((check_name, True, None))
return True
else:
self.print_error(error_msg)
error_output = result.stdout + result.stderr
if self.verbose and error_output:
print(f"\n{error_output}\n")
self.results.append((check_name, False, error_output))
return False
except FileNotFoundError:
self.print_warning(f"Tool not found: {cmd[0]}")
self.results.append((check_name, False, f"Tool not found: {cmd[0]}"))
return False
except Exception as e:
self.print_error(f"Error running {check_name}: {str(e)}")
self.results.append((check_name, False, str(e)))
return False
def check_ruff_format(self) -> bool:
"""Check code formatting with ruff."""
if self.fix:
cmd = ["python", "-m", "ruff", "format", "rag_system", "tests"]
return self.run_command(
cmd,
"Code formatting (ruff)",
"Code formatted successfully",
"Code formatting issues found",
)
else:
cmd = ["python", "-m", "ruff", "format", "--check", "rag_system", "tests"]
return self.run_command(
cmd,
"Code formatting check (ruff)",
"Code formatting is correct",
"Code formatting issues found (run with --fix to auto-format)",
)
def check_ruff_lint(self) -> bool:
"""Check code style and quality with ruff."""
if self.fix:
cmd = ["python", "-m", "ruff", "check", "--fix", "rag_system", "tests"]
return self.run_command(
cmd,
"Linting (ruff)",
"Linting issues fixed successfully",
"Linting issues found",
)
else:
cmd = ["python", "-m", "ruff", "check", "rag_system", "tests"]
return self.run_command(
cmd,
"Linting check (ruff)",
"No linting issues found",
"Linting issues found (run with --fix to auto-fix)",
)
def check_pyright(self) -> bool:
"""Check type hints with pyright."""
cmd = ["python", "-m", "pyright", "rag_system"]
return self.run_command(
cmd, "Type checking (pyright)", "Type checking passed", "Type checking issues found"
)
def check_bandit(self) -> bool:
"""Check security issues with bandit."""
cmd = [
"python",
"-m",
"bandit",
"-r",
"rag_system",
"-ll", # Only report medium and high severity
"-f",
"screen",
]
return self.run_command(
cmd, "Security check (bandit)", "No security issues found", "Security issues found"
)
def run_tests(self) -> bool:
"""Run unit tests with pytest."""
cmd = [
"python",
"-m",
"pytest",
"tests/",
"-v",
"--tb=short",
"--cov=rag_system",
"--cov-report=term-missing",
"--cov-report=html",
"--cov-fail-under=80",
]
return self.run_command(
cmd,
"Unit tests (pytest)",
"All tests passed with sufficient coverage",
"Tests failed or coverage is below 80%",
)
def check_requirements(self) -> bool:
"""Check if requirements.txt is up to date."""
self.print_step("Checking requirements.txt")
try:
# Check if requirements.txt exists
req_file = Path("requirements.txt")
if not req_file.exists():
self.print_warning("requirements.txt not found")
self.results.append(("Requirements check", False, "File not found"))
return False
# Check if it's not empty
content = req_file.read_text()
if not content.strip():
self.print_warning("requirements.txt is empty")
self.results.append(("Requirements check", False, "File is empty"))
return False
self.print_success("requirements.txt exists and is not empty")
self.results.append(("Requirements check", True, None))
return True
except Exception as e:
self.print_error(f"Error checking requirements: {str(e)}")
self.results.append(("Requirements check", False, str(e)))
return False
def check_git_status(self) -> bool:
"""Check git status for uncommitted changes."""
self.print_step("Checking git status")
try:
result = subprocess.run(
["git", "status", "--porcelain"], capture_output=True, text=True, check=False
)
if result.returncode != 0:
self.print_warning("Not a git repository or git not available")
self.results.append(("Git status check", False, "Git not available"))
return False
changes = result.stdout.strip()
if changes:
self.print_warning(f"Uncommitted changes found:\n{changes}")
self.results.append(("Git status check", True, "Changes found"))
else:
self.print_success("No uncommitted changes")
self.results.append(("Git status check", True, None))
return True
except Exception as e:
self.print_warning(f"Error checking git status: {str(e)}")
self.results.append(("Git status check", False, str(e)))
return False
def print_summary(self) -> bool:
"""Print summary of all checks."""
self.print_header("QUALITY CHECK SUMMARY")
passed = sum(1 for _, success, _ in self.results if success)
failed = len(self.results) - passed
print(f"Total checks: {len(self.results)}")
print(f"{Colors.OKGREEN}Passed: {passed}{Colors.ENDC}")
print(f"{Colors.FAIL}Failed: {failed}{Colors.ENDC}\n")
if failed > 0:
print(f"{Colors.FAIL}Failed checks:{Colors.ENDC}")
for name, success, error in self.results:
if not success:
print(f" {Colors.FAIL}✗ {name}{Colors.ENDC}")
if self.verbose and error:
print(f" {error[:200]}...")
print()
if failed == 0:
self.print_success("All quality checks passed! ✨")
print(f"\n{Colors.OKGREEN}Your code is ready to commit!{Colors.ENDC}\n")
return True
else:
self.print_error("Some quality checks failed!")
print(f"\n{Colors.FAIL}Please fix the issues before committing.{Colors.ENDC}")
if not self.fix:
print(
f"{Colors.WARNING}Tip: Run with --fix to automatically fix some issues.{Colors.ENDC}\n"
)
return False
def run_all_checks(self) -> bool:
"""Run all quality checks."""
self.print_header("RAG SYSTEM - PRE-COMMIT QUALITY CHECKS")
# Check requirements first
self.check_requirements()
# Check git status
self.check_git_status()
# Code formatting with ruff
self.check_ruff_format()
# Linting with ruff
self.check_ruff_lint()
# Type checking with pyright
self.check_pyright()
# Security
self.check_bandit()
# Tests (if not skipped)
if not self.skip_tests:
self.run_tests()
else:
self.print_warning("Tests skipped (--skip-tests flag)")
# Print summary
return self.print_summary()
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Run pre-commit quality checks for the RAG system",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python pre-commit-check.py # Run all checks
python pre-commit-check.py --fix # Run checks and auto-fix issues
python pre-commit-check.py --skip-tests # Skip running tests
python pre-commit-check.py --verbose # Show detailed output
python pre-commit-check.py --fix --verbose # Fix issues with detailed output
""",
)
parser.add_argument(
"--fix",
action="store_true",
help="Automatically fix issues where possible (formatting, imports)",
)
parser.add_argument(
"--skip-tests",
action="store_true",
help="Skip running unit tests (faster for quick checks)",
)
parser.add_argument(
"--verbose", "-v", action="store_true", help="Show verbose output including error details"
)
args = parser.parse_args()
# Create checker and run all checks
checker = QualityChecker(fix=args.fix, skip_tests=args.skip_tests, verbose=args.verbose)
success = checker.run_all_checks()
# Exit with appropriate code
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()