Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
5c3903e
will exit the cli if user doesn't have the formatter installed while …
aseembits93 May 20, 2025
3766ab4
moving things around
aseembits93 May 20, 2025
022d59b
typo
aseembits93 May 20, 2025
cf57fb1
ruff
aseembits93 May 20, 2025
4619f69
Update codeflash/optimization/optimizer.py
misrasaurabh1 May 20, 2025
1def2b4
refactoring
aseembits93 May 20, 2025
7ba496d
stash didnt work as expected
aseembits93 May 20, 2025
72519d5
Update env_utils.py
aseembits93 May 20, 2025
290f7b3
circular depenencies
aseembits93 May 20, 2025
ffbb167
minor fix
aseembits93 May 20, 2025
f484ff0
reduce duplication
aseembits93 May 20, 2025
f090a7a
Merge branch 'main' into fix-formatter-during-runtime
aseembits93 May 20, 2025
498f401
Merge branch 'main' into fix-formatter-during-runtime
aseembits93 May 20, 2025
cd63955
more pythonic
aseembits93 May 20, 2025
dfc5177
covering cases where uv or uvx is used
aseembits93 May 20, 2025
ac0894a
running all commands in list to ensure all run
aseembits93 May 20, 2025
6b27835
minor fixes
aseembits93 May 20, 2025
27fb8eb
Merge branch 'main' into fix-formatter-during-runtime
aseembits93 May 20, 2025
7f01823
bugfix
aseembits93 May 20, 2025
bc31a61
handle more exceptions
aseembits93 May 21, 2025
dfaa1cb
raise proper exception
KRRT7 May 21, 2025
130870e
Merge branch 'main' into fix-formatter-during-runtime
aseembits93 May 21, 2025
64edb0c
Merge branch 'main' into fix-formatter-during-runtime
misrasaurabh1 May 21, 2025
3334392
Merge branch 'main' into fix-formatter-during-runtime
misrasaurabh1 May 21, 2025
5507f8f
Merge branch 'main' into fix-formatter-during-runtime
aseembits93 May 21, 2025
baa747a
precommit fix
aseembits93 May 21, 2025
4cfaea0
Merge branch 'main' into fix-formatter-during-runtime
aseembits93 May 27, 2025
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
16 changes: 10 additions & 6 deletions codeflash/cli_cmds/cmd_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from codeflash.cli_cmds.console import console, logger
from codeflash.code_utils.compat import LF
from codeflash.code_utils.config_parser import parse_config_file
from codeflash.code_utils.env_utils import get_codeflash_api_key
from codeflash.code_utils.env_utils import check_formatter_installed, get_codeflash_api_key
from codeflash.code_utils.git_utils import get_git_remotes, get_repo_owner_and_name
from codeflash.code_utils.github_utils import get_github_secrets_page_url
from codeflash.code_utils.shell_utils import get_shell_rc_path, save_api_key_to_rc
Expand Down Expand Up @@ -720,11 +720,7 @@ def configure_pyproject_toml(setup_info: SetupInfo) -> None:
)
elif formatter == "don't use a formatter":
formatter_cmds.append("disabled")
if formatter in ["black", "ruff"]:
try:
subprocess.run([formatter], capture_output=True, check=False)
except (FileNotFoundError, NotADirectoryError):
click.echo(f"⚠️ Formatter not found: {formatter}, please ensure it is installed")
check_formatter_installed(formatter_cmds)
codeflash_section["formatter-cmds"] = formatter_cmds
# Add the 'codeflash' section, ensuring 'tool' section exists
tool_section = pyproject_data.get("tool", tomlkit.table())
Expand Down Expand Up @@ -924,6 +920,14 @@ def test_sort():


def run_end_to_end_test(args: Namespace, bubble_sort_path: str, bubble_sort_test_path: str) -> None:
try:
check_formatter_installed(args.formatter_cmds)
except Exception:
logger.error(
"Formatter not found. Review the formatter_cmds in your pyproject.toml file and make sure the formatter is installed."
)
return

command = ["codeflash", "--file", "bubble_sort.py", "--function", "sorter"]
if args.no_pr:
command.append("--no-pr")
Expand Down
39 changes: 39 additions & 0 deletions codeflash/code_utils/env_utils.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,52 @@
from __future__ import annotations

import os
import shlex
import subprocess
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.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:
return_code = True
if formatter_cmds[0] == "disabled":
return return_code
tmp_code = """print("hello world")"""
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", suffix=".py") as f:
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)
return return_code


@lru_cache(maxsize=1)
def get_codeflash_api_key() -> str:
api_key = os.environ.get("CODEFLASH_API_KEY") or read_api_key_from_shell_config()
Expand Down
2 changes: 2 additions & 0 deletions codeflash/optimization/optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ def run(self) -> None:
console.rule()
if not env_utils.ensure_codeflash_api_key():
return
if not env_utils.check_formatter_installed(self.args.formatter_cmds):
return
function_optimizer = None
file_to_funcs_to_optimize: dict[Path, list[FunctionToOptimize]]
num_optimizable_functions: int
Expand Down
Loading