Skip to content

Commit d2ece1e

Browse files
authored
Merge branch 'main' into pytest-benchmark-err-fix
2 parents 27df760 + fdd7ca9 commit d2ece1e

File tree

14 files changed

+243
-172
lines changed

14 files changed

+243
-172
lines changed

codeflash/api/cfapi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
9191
9292
:return: The userid or None if the request fails.
9393
"""
94-
if not ensure_codeflash_api_key():
94+
if not api_key and not ensure_codeflash_api_key():
9595
return None
9696

9797
response = make_cfapi_request(

codeflash/code_utils/edit_generated_tests.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os
55
import re
66
from pathlib import Path
7-
from typing import TYPE_CHECKING
7+
from typing import TYPE_CHECKING, Optional
88

99
import libcst as cst
1010
from libcst import MetadataWrapper
@@ -149,18 +149,19 @@ def leave_SimpleStatementSuite(
149149
return updated_node
150150

151151

152-
def unique_inv_id(inv_id_runtimes: dict[InvocationId, list[int]]) -> dict[str, int]:
152+
def unique_inv_id(inv_id_runtimes: dict[InvocationId, list[int]], tests_project_rootdir: Path) -> dict[str, int]:
153153
unique_inv_ids: dict[str, int] = {}
154154
for inv_id, runtimes in inv_id_runtimes.items():
155155
test_qualified_name = (
156156
inv_id.test_class_name + "." + inv_id.test_function_name # type: ignore[operator]
157157
if inv_id.test_class_name
158158
else inv_id.test_function_name
159159
)
160-
abs_path = str(Path(inv_id.test_module_path.replace(".", os.sep)).with_suffix(".py").resolve().with_suffix(""))
161-
if "__unit_test_" not in abs_path:
160+
abs_path = tests_project_rootdir / Path(inv_id.test_module_path.replace(".", os.sep)).with_suffix(".py")
161+
abs_path_str = str(abs_path.resolve().with_suffix(""))
162+
if "__unit_test_" not in abs_path_str or not test_qualified_name:
162163
continue
163-
key = test_qualified_name + "#" + abs_path # type: ignore[operator]
164+
key = test_qualified_name + "#" + abs_path_str
164165
parts = inv_id.iteration_id.split("_").__len__() # type: ignore[union-attr]
165166
cur_invid = inv_id.iteration_id.split("_")[0] if parts < 3 else "_".join(inv_id.iteration_id.split("_")[:-1]) # type: ignore[union-attr]
166167
match_key = key + "#" + cur_invid
@@ -174,10 +175,11 @@ def add_runtime_comments_to_generated_tests(
174175
generated_tests: GeneratedTestsList,
175176
original_runtimes: dict[InvocationId, list[int]],
176177
optimized_runtimes: dict[InvocationId, list[int]],
178+
tests_project_rootdir: Optional[Path] = None,
177179
) -> GeneratedTestsList:
178180
"""Add runtime performance comments to function calls in generated tests."""
179-
original_runtimes_dict = unique_inv_id(original_runtimes)
180-
optimized_runtimes_dict = unique_inv_id(optimized_runtimes)
181+
original_runtimes_dict = unique_inv_id(original_runtimes, tests_project_rootdir or Path())
182+
optimized_runtimes_dict = unique_inv_id(optimized_runtimes, tests_project_rootdir or Path())
181183
# Process each generated test
182184
modified_tests = []
183185
for test in generated_tests.generated_tests:

codeflash/code_utils/env_utils.py

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import json
44
import os
5+
import shlex
6+
import shutil
57
import tempfile
68
from functools import lru_cache
79
from pathlib import Path
@@ -14,21 +16,41 @@
1416

1517

1618
def check_formatter_installed(formatter_cmds: list[str], exit_on_failure: bool = True) -> bool: # noqa
17-
return_code = True
18-
if formatter_cmds[0] == "disabled":
19-
return return_code
19+
if not formatter_cmds or formatter_cmds[0] == "disabled":
20+
return True
21+
22+
first_cmd = formatter_cmds[0]
23+
cmd_tokens = shlex.split(first_cmd) if isinstance(first_cmd, str) else [first_cmd]
24+
25+
if not cmd_tokens:
26+
return True
27+
28+
exe_name = cmd_tokens[0]
29+
command_str = " ".join(formatter_cmds).replace(" $file", "")
30+
31+
if shutil.which(exe_name) is None:
32+
logger.error(
33+
f"Could not find formatter: {command_str}\n"
34+
f"Please install it or update 'formatter-cmds' in your codeflash configuration"
35+
)
36+
return False
37+
2038
tmp_code = """print("hello world")"""
21-
with tempfile.TemporaryDirectory() as tmpdir:
22-
tmp_file = Path(tmpdir) / "test_codeflash_formatter.py"
23-
tmp_file.write_text(tmp_code, encoding="utf-8")
24-
try:
25-
format_code(formatter_cmds, tmp_file, print_status=False, exit_on_failure=exit_on_failure)
26-
except Exception:
27-
exit_with_message(
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-
error_on_exit=True,
30-
)
31-
return return_code
39+
try:
40+
with tempfile.TemporaryDirectory() as tmpdir:
41+
tmp_file = Path(tmpdir) / "test_codeflash_formatter.py"
42+
tmp_file.write_text(tmp_code, encoding="utf-8")
43+
format_code(formatter_cmds, tmp_file, print_status=False, exit_on_failure=False)
44+
return True
45+
except FileNotFoundError:
46+
logger.error(
47+
f"Could not find formatter: {command_str}\n"
48+
f"Please install it or update 'formatter-cmds' in your codeflash configuration"
49+
)
50+
return False
51+
except Exception as e:
52+
logger.error(f"Formatter failed to run: {command_str}\nError: {e}")
53+
return False
3254

3355

3456
@lru_cache(maxsize=1)

codeflash/code_utils/formatter.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,12 +76,9 @@ def apply_formatter_cmds(
7676
logger.error(f"Failed to format code with {' '.join(formatter_cmd_list)}")
7777
except FileNotFoundError as e:
7878
from rich.panel import Panel
79-
from rich.text import Text
8079

81-
panel = Panel(
82-
Text.from_markup(f"⚠️ Formatter command not found: {' '.join(formatter_cmd_list)}", style="bold red"),
83-
expand=False,
84-
)
80+
command_str = " ".join(str(part) for part in formatter_cmd_list)
81+
panel = Panel(f"⚠️ Formatter command not found: {command_str}", expand=False, border_style="yellow")
8582
console.print(panel)
8683
if exit_on_failure:
8784
raise e from None

codeflash/code_utils/git_worktree_utils.py

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,18 @@
33
import subprocess
44
import tempfile
55
import time
6-
from functools import lru_cache
76
from pathlib import Path
8-
from typing import TYPE_CHECKING, Optional
7+
from typing import Optional
98

109
import git
1110

1211
from codeflash.cli_cmds.console import logger
1312
from codeflash.code_utils.compat import codeflash_cache_dir
1413
from codeflash.code_utils.git_utils import check_running_in_git_repo, git_root_dir
1514

16-
if TYPE_CHECKING:
17-
from git import Repo
18-
19-
2015
worktree_dirs = codeflash_cache_dir / "worktrees"
2116
patches_dir = codeflash_cache_dir / "patches"
2217

23-
if TYPE_CHECKING:
24-
from git import Repo
25-
26-
27-
@lru_cache(maxsize=1)
28-
def get_git_project_id() -> str:
29-
"""Return the first commit sha of the repo."""
30-
repo: Repo = git.Repo(search_parent_directories=True)
31-
root_commits = list(repo.iter_commits(rev="HEAD", max_parents=0))
32-
return root_commits[0].hexsha
33-
3418

3519
def create_worktree_snapshot_commit(worktree_dir: Path, commit_message: str) -> None:
3620
repository = git.Repo(worktree_dir, search_parent_directories=True)
@@ -96,12 +80,6 @@ def remove_worktree(worktree_dir: Path) -> None:
9680
logger.exception(f"Failed to remove worktree: {worktree_dir}")
9781

9882

99-
@lru_cache(maxsize=1)
100-
def get_patches_dir_for_project() -> Path:
101-
project_id = get_git_project_id() or ""
102-
return Path(patches_dir / project_id)
103-
104-
10583
def create_diff_patch_from_worktree(
10684
worktree_dir: Path, files: list[str], fto_name: Optional[str] = None
10785
) -> Optional[Path]:
@@ -115,10 +93,8 @@ def create_diff_patch_from_worktree(
11593
if not uni_diff_text.endswith("\n"):
11694
uni_diff_text += "\n"
11795

118-
project_patches_dir = get_patches_dir_for_project()
119-
project_patches_dir.mkdir(parents=True, exist_ok=True)
120-
121-
patch_path = project_patches_dir / f"{worktree_dir.name}.{fto_name}.patch"
96+
patches_dir.mkdir(parents=True, exist_ok=True)
97+
patch_path = Path(patches_dir / f"{worktree_dir.name}.{fto_name}.patch")
12298
with patch_path.open("w", encoding="utf8") as f:
12399
f.write(uni_diff_text)
124100

0 commit comments

Comments
 (0)