Spaces:
Sleeping
Sleeping
Create code_formatter.py
Browse files- code_formatter.py +30 -0
code_formatter.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import black
|
| 2 |
+
|
| 3 |
+
class CodeFormatter(Tool):
|
| 4 |
+
name = "CodeFormatter"
|
| 5 |
+
description = """
|
| 6 |
+
This tool formats python code using Black.
|
| 7 |
+
You can avoid formatting errors like "IndentationError" with this tool.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
inputs = {
|
| 11 |
+
"code_string": {
|
| 12 |
+
"type": "string",
|
| 13 |
+
"description": "python code string that can be unformatted",
|
| 14 |
+
}
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
output_type = "string"
|
| 18 |
+
|
| 19 |
+
def forward(self, code_string: str) -> str:
|
| 20 |
+
"""
|
| 21 |
+
Format Python code using Black.
|
| 22 |
+
"""
|
| 23 |
+
try:
|
| 24 |
+
formatted_code = black.format_str(code_string, mode=black.Mode())
|
| 25 |
+
return formatted_code
|
| 26 |
+
except black.NothingChanged:
|
| 27 |
+
return code_string
|
| 28 |
+
except Exception as e:
|
| 29 |
+
print(f"An error occurred during formatting: {e}")
|
| 30 |
+
return code_string
|