Spaces:
Sleeping
Sleeping
Create utils/code_utils.py
Browse files- utils/code_utils.py +58 -0
utils/code_utils.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import black
|
2 |
+
from pylint import lint
|
3 |
+
from io import StringIO
|
4 |
+
from typing import List, Dict, Optional
|
5 |
+
|
6 |
+
# --- Define custom exceptions for better error handling ---
|
7 |
+
class CodeRefinementError(Exception):
|
8 |
+
"""Raised when code refinement fails."""
|
9 |
+
pass
|
10 |
+
|
11 |
+
class CodeTestingError(Exception):
|
12 |
+
"""Raised when code testing fails."""
|
13 |
+
pass
|
14 |
+
|
15 |
+
class CodeIntegrationError(Exception):
|
16 |
+
"""Raised when code integration fails."""
|
17 |
+
pass
|
18 |
+
|
19 |
+
# --- Implement code refinement functionality ---
|
20 |
+
def refine_code(file_path: str) -> str:
|
21 |
+
"""Refines the code in the specified file."""
|
22 |
+
try:
|
23 |
+
with open(file_path, 'r') as f:
|
24 |
+
code = f.read()
|
25 |
+
refined_code = black.format_str(code, mode=black.FileMode())
|
26 |
+
return refined_code
|
27 |
+
except black.InvalidInput:
|
28 |
+
raise CodeRefinementError("Error: Invalid code input for black formatting.")
|
29 |
+
except FileNotFoundError:
|
30 |
+
raise CodeRefinementError(f"Error: File not found: {file_path}")
|
31 |
+
except Exception as e:
|
32 |
+
raise CodeRefinementError(f"Error during code refinement: {e}")
|
33 |
+
|
34 |
+
# --- Implement code testing functionality ---
|
35 |
+
def test_code(file_path: str) -> str:
|
36 |
+
"""Tests the code in the specified file."""
|
37 |
+
try:
|
38 |
+
with open(file_path, 'r') as f:
|
39 |
+
code = f.read()
|
40 |
+
output = StringIO()
|
41 |
+
lint.run(code, output=output)
|
42 |
+
return output.getvalue()
|
43 |
+
except FileNotFoundError:
|
44 |
+
raise CodeTestingError(f"Error: File not found: {file_path}")
|
45 |
+
except Exception as e:
|
46 |
+
raise CodeTestingError(f"Error during code testing: {e}")
|
47 |
+
|
48 |
+
# --- Implement code integration functionality ---
|
49 |
+
def integrate_code(file_path: str, code_snippet: str) -> str:
|
50 |
+
"""Integrates the code snippet into the specified file."""
|
51 |
+
try:
|
52 |
+
with open(file_path, 'a') as f:
|
53 |
+
f.write(code_snippet)
|
54 |
+
return "Code integrated successfully."
|
55 |
+
except FileNotFoundError:
|
56 |
+
raise CodeIntegrationError(f"Error: File not found: {file_path}")
|
57 |
+
except Exception as e:
|
58 |
+
raise CodeIntegrationError(f"Error during code integration: {e}")
|