11from __future__ import annotations
22
33import os
4- import shlex
5- import subprocess
4+ import sys
65import tempfile
76from functools import lru_cache
87from pathlib import Path
98from typing import Optional
109
1110from codeflash .cli_cmds .console import logger
11+ from codeflash .code_utils .formatter import format_code
1212from codeflash .code_utils .shell_utils import read_api_key_from_shell_config
1313
1414
15- class FormatterNotFoundError (Exception ):
16- """Exception raised when a formatter is not found."""
17-
18- def __init__ (self , formatter_cmd : str ) -> None :
19- super ().__init__ (f"Formatter command not found: { formatter_cmd } " )
20-
21-
22- def check_formatter_installed (formatter_cmds : list [str ]) -> bool :
15+ def check_formatter_installed (formatter_cmds : list [str ], exit_on_failure : bool = True ) -> bool : # noqa
2316 return_code = True
2417 if formatter_cmds [0 ] == "disabled" :
2518 return return_code
@@ -28,22 +21,14 @@ def check_formatter_installed(formatter_cmds: list[str]) -> bool:
2821 f .write (tmp_code )
2922 f .flush ()
3023 tmp_file = Path (f .name )
31- file_token = "$file" # noqa: S105
32- for command in set (formatter_cmds ):
33- formatter_cmd_list = shlex .split (command , posix = os .name != "nt" )
34- formatter_cmd_list = [tmp_file .as_posix () if chunk == file_token else chunk for chunk in formatter_cmd_list ]
35- try :
36- result = subprocess .run (formatter_cmd_list , capture_output = True , check = False )
37- except (FileNotFoundError , NotADirectoryError ):
38- return_code = False
39- break
40- if result .returncode :
41- return_code = False
42- break
43- tmp_file .unlink (missing_ok = True )
44- if not return_code :
45- msg = f"Error running formatter command: { command } "
46- raise FormatterNotFoundError (msg )
24+ try :
25+ format_code (formatter_cmds , tmp_file )
26+ except Exception :
27+ print (
28+ "⚠️ Codeflash requires a code formatter to be installed in your environment, but none was found. Please install a supported formatter, verify the formatter-cmds in your codeflash pyproject.toml config and try again."
29+ )
30+ if exit_on_failure :
31+ sys .exit (1 )
4732 return return_code
4833
4934
0 commit comments