Skip to content

Commit b991c33

Browse files
authored
Merge branch 'main' into opt-impact-aseem
2 parents c2ffeae + 649f04a commit b991c33

File tree

14 files changed

+471
-329
lines changed

14 files changed

+471
-329
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[tool.codeflash]
2+
# All paths are relative to this pyproject.toml's directory.
3+
module-root = "src/app"
4+
tests-root = "src/tests"
5+
test-framework = "pytest"
6+
ignore-paths = []
7+
disable-telemetry = true
8+
formatter-cmds = ["disabled"]
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def sorter(arr):
2+
print("codeflash stdout: Sorting list")
3+
for i in range(len(arr)):
4+
for j in range(len(arr) - 1):
5+
if arr[j] > arr[j + 1]:
6+
temp = arr[j]
7+
arr[j] = arr[j + 1]
8+
arr[j + 1] = temp
9+
print(f"result: {arr}")
10+
return arr

code_to_optimize/code_directories/nested_module_root/src/tests/.gitkeep

Whitespace-only changes.

codeflash/code_utils/git_worktree_utils.py

Lines changed: 5 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from __future__ import annotations
22

3-
import json
43
import subprocess
54
import tempfile
65
import time
@@ -9,15 +8,12 @@
98
from typing import TYPE_CHECKING, Optional
109

1110
import git
12-
from filelock import FileLock
1311

1412
from codeflash.cli_cmds.console import logger
1513
from codeflash.code_utils.compat import codeflash_cache_dir
1614
from codeflash.code_utils.git_utils import check_running_in_git_repo, git_root_dir
1715

1816
if TYPE_CHECKING:
19-
from typing import Any
20-
2117
from git import Repo
2218

2319

@@ -100,71 +96,24 @@ def get_patches_dir_for_project() -> Path:
10096
return Path(patches_dir / project_id)
10197

10298

103-
def get_patches_metadata() -> dict[str, Any]:
104-
project_patches_dir = get_patches_dir_for_project()
105-
meta_file = project_patches_dir / "metadata.json"
106-
if meta_file.exists():
107-
with meta_file.open("r", encoding="utf-8") as f:
108-
return json.load(f)
109-
return {"id": get_git_project_id() or "", "patches": []}
110-
111-
112-
def save_patches_metadata(patch_metadata: dict) -> dict:
113-
project_patches_dir = get_patches_dir_for_project()
114-
meta_file = project_patches_dir / "metadata.json"
115-
lock_file = project_patches_dir / "metadata.json.lock"
116-
117-
# we are not supporting multiple concurrent optimizations within the same process, but keep that in case we decide to do so in the future.
118-
with FileLock(lock_file, timeout=10):
119-
metadata = get_patches_metadata()
120-
121-
patch_metadata["id"] = time.strftime("%Y%m%d-%H%M%S")
122-
metadata["patches"].append(patch_metadata)
123-
124-
meta_file.write_text(json.dumps(metadata, indent=2))
125-
126-
return patch_metadata
127-
128-
129-
def overwrite_patch_metadata(patches: list[dict]) -> bool:
130-
project_patches_dir = get_patches_dir_for_project()
131-
meta_file = project_patches_dir / "metadata.json"
132-
lock_file = project_patches_dir / "metadata.json.lock"
133-
134-
with FileLock(lock_file, timeout=10):
135-
metadata = get_patches_metadata()
136-
metadata["patches"] = patches
137-
meta_file.write_text(json.dumps(metadata, indent=2))
138-
return True
139-
140-
14199
def create_diff_patch_from_worktree(
142-
worktree_dir: Path,
143-
files: list[str],
144-
fto_name: Optional[str] = None,
145-
metadata_input: Optional[dict[str, Any]] = None,
146-
) -> dict[str, Any]:
100+
worktree_dir: Path, files: list[str], fto_name: Optional[str] = None
101+
) -> Optional[Path]:
147102
repository = git.Repo(worktree_dir, search_parent_directories=True)
148103
uni_diff_text = repository.git.diff(None, "HEAD", *files, ignore_blank_lines=True, ignore_space_at_eol=True)
149104

150105
if not uni_diff_text:
151106
logger.warning("No changes found in worktree.")
152-
return {}
107+
return None
153108

154109
if not uni_diff_text.endswith("\n"):
155110
uni_diff_text += "\n"
156111

157112
project_patches_dir = get_patches_dir_for_project()
158113
project_patches_dir.mkdir(parents=True, exist_ok=True)
159114

160-
final_function_name = fto_name or metadata_input.get("fto_name", "unknown")
161-
patch_path = project_patches_dir / f"{worktree_dir.name}.{final_function_name}.patch"
115+
patch_path = project_patches_dir / f"{worktree_dir.name}.{fto_name}.patch"
162116
with patch_path.open("w", encoding="utf8") as f:
163117
f.write(uni_diff_text)
164118

165-
final_metadata = {"patch_path": str(patch_path)}
166-
if metadata_input:
167-
final_metadata.update(metadata_input)
168-
final_metadata = save_patches_metadata(final_metadata)
169-
170-
return final_metadata
119+
return patch_path

codeflash/discovery/discover_unit_tests.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import annotations
33

44
import ast
5+
import enum
56
import hashlib
67
import os
78
import pickle
@@ -11,12 +12,11 @@
1112
import unittest
1213
from collections import defaultdict
1314
from pathlib import Path
14-
from typing import TYPE_CHECKING, Callable, Optional
15+
from typing import TYPE_CHECKING, Callable, Optional, final
1516

1617
if TYPE_CHECKING:
1718
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
1819

19-
import pytest
2020
from pydantic.dataclasses import dataclass
2121
from rich.panel import Panel
2222
from rich.text import Text
@@ -35,6 +35,22 @@
3535
from codeflash.verification.verification_utils import TestConfig
3636

3737

38+
@final
39+
class PytestExitCode(enum.IntEnum): # don't need to import entire pytest just for this
40+
#: Tests passed.
41+
OK = 0
42+
#: Tests failed.
43+
TESTS_FAILED = 1
44+
#: pytest was interrupted.
45+
INTERRUPTED = 2
46+
#: An internal error got in the way.
47+
INTERNAL_ERROR = 3
48+
#: pytest was misused.
49+
USAGE_ERROR = 4
50+
#: pytest couldn't find tests.
51+
NO_TESTS_COLLECTED = 5
52+
53+
3854
@dataclass(frozen=True)
3955
class TestFunction:
4056
function_name: str
@@ -412,15 +428,15 @@ def discover_tests_pytest(
412428
error_section = match.group(1) if match else result.stdout
413429

414430
logger.warning(
415-
f"Failed to collect tests. Pytest Exit code: {exitcode}={pytest.ExitCode(exitcode).name}\n {error_section}"
431+
f"Failed to collect tests. Pytest Exit code: {exitcode}={PytestExitCode(exitcode).name}\n {error_section}"
416432
)
417433
if "ModuleNotFoundError" in result.stdout:
418434
match = ImportErrorPattern.search(result.stdout).group()
419435
panel = Panel(Text.from_markup(f"⚠️ {match} ", style="bold red"), expand=False)
420436
console.print(panel)
421437

422438
elif 0 <= exitcode <= 5:
423-
logger.warning(f"Failed to collect tests. Pytest Exit code: {exitcode}={pytest.ExitCode(exitcode).name}")
439+
logger.warning(f"Failed to collect tests. Pytest Exit code: {exitcode}={PytestExitCode(exitcode).name}")
424440
else:
425441
logger.warning(f"Failed to collect tests. Pytest Exit code: {exitcode}")
426442
console.rule()

0 commit comments

Comments
 (0)