Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion codeflash/cli_cmds/cmd_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
37 changes: 11 additions & 26 deletions codeflash/code_utils/env_utils.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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


Expand Down
Loading