diff --git a/codeflash/cli_cmds/cmd_init.py b/codeflash/cli_cmds/cmd_init.py index aaa8cbe53..bfe600fa4 100644 --- a/codeflash/cli_cmds/cmd_init.py +++ b/codeflash/cli_cmds/cmd_init.py @@ -721,7 +721,7 @@ def configure_pyproject_toml(setup_info: SetupInfo) -> None: ) elif formatter == "don't use a formatter": formatter_cmds.append("disabled") - check_formatter_installed(formatter_cmds) + check_formatter_installed(formatter_cmds, exit_on_failure=False) codeflash_section["formatter-cmds"] = formatter_cmds # Add the 'codeflash' section, ensuring 'tool' section exists tool_section = pyproject_data.get("tool", tomlkit.table()) diff --git a/codeflash/code_utils/env_utils.py b/codeflash/code_utils/env_utils.py index ee18cfa00..8bf8a506c 100644 --- a/codeflash/code_utils/env_utils.py +++ b/codeflash/code_utils/env_utils.py @@ -1,25 +1,18 @@ from __future__ import annotations import os -import shlex -import subprocess +import sys import tempfile from functools import lru_cache from pathlib import Path from typing import Optional from codeflash.cli_cmds.console import logger +from codeflash.code_utils.formatter import format_code from codeflash.code_utils.shell_utils import read_api_key_from_shell_config -class FormatterNotFoundError(Exception): - """Exception raised when a formatter is not found.""" - - def __init__(self, formatter_cmd: str) -> None: - super().__init__(f"Formatter command not found: {formatter_cmd}") - - -def check_formatter_installed(formatter_cmds: list[str]) -> bool: +def check_formatter_installed(formatter_cmds: list[str], exit_on_failure: bool = True) -> bool: # noqa return_code = True if formatter_cmds[0] == "disabled": return return_code @@ -28,22 +21,14 @@ def check_formatter_installed(formatter_cmds: list[str]) -> bool: f.write(tmp_code) f.flush() tmp_file = Path(f.name) - file_token = "$file" # noqa: S105 - for command in set(formatter_cmds): - formatter_cmd_list = shlex.split(command, posix=os.name != "nt") - formatter_cmd_list = [tmp_file.as_posix() if chunk == file_token else chunk for chunk in formatter_cmd_list] - try: - result = subprocess.run(formatter_cmd_list, capture_output=True, check=False) - except (FileNotFoundError, NotADirectoryError): - return_code = False - break - if result.returncode: - return_code = False - break - tmp_file.unlink(missing_ok=True) - if not return_code: - msg = f"Error running formatter command: {command}" - raise FormatterNotFoundError(msg) + try: + format_code(formatter_cmds, tmp_file) + except Exception: + print( + "⚠️ 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." + ) + if exit_on_failure: + sys.exit(1) return return_code