Skip to content

Commit c38a93e

Browse files
committed
replay file name fixed
1 parent 5dbca86 commit c38a93e

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

codeflash/tracing/tracing_new_process.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import json
88
import os
99
import pickle
10+
import re
1011
import sqlite3
1112
import sys
1213
import threading
@@ -112,7 +113,7 @@ def __init__(
112113
console.rule(f"Project Root: {self.project_root}", style="bold blue")
113114
self.ignored_functions = {"<listcomp>", "<genexpr>", "<dictcomp>", "<setcomp>", "<lambda>", "<module>"}
114115

115-
self.file_being_called_from: str = str(Path(sys._getframe().f_back.f_code.co_filename).name).replace(".", "_") # noqa: SLF001
116+
self.sanitized_filename = self.sanitize_to_filename(command)
116117
self.result_pickle_file_path = result_pickle_file_path
117118

118119
assert timeout is None or timeout > 0, "Timeout should be greater than 0"
@@ -167,7 +168,7 @@ def __enter__(self) -> None:
167168

168169
# Store command metadata
169170
cur.execute("INSERT INTO metadata VALUES (?, ?)", ("command", self.command))
170-
cur.execute("INSERT INTO metadata VALUES (?, ?)", ("program_name", self.file_being_called_from))
171+
cur.execute("INSERT INTO metadata VALUES (?, ?)", ("program_name", self.sanitized_filename))
171172
cur.execute(
172173
"INSERT INTO metadata VALUES (?, ?)",
173174
("functions_filter", json.dumps(self.functions) if self.functions else None),
@@ -263,7 +264,7 @@ def __exit__(
263264
test_framework=self.config["test_framework"],
264265
max_run_count=self.max_function_count,
265266
)
266-
function_path = "_".join(self.functions) if self.functions else self.file_being_called_from
267+
function_path = "_".join(self.functions) if self.functions else self.sanitized_filename
267268
test_file_path = get_test_file_path(
268269
test_dir=Path(self.config["tests_root"]), function_name=function_path, test_type="replay"
269270
)
@@ -783,6 +784,22 @@ def snapshot_stats(self) -> None:
783784
nc += callcnt
784785
self.stats[func] = cc, nc, tt, ct, callers
785786

787+
def sanitize_to_filename(self, arg: str) -> str:
788+
# Replace newlines with underscores
789+
arg = arg.replace("\n", "_").replace("\r", "_")
790+
791+
# Replace contiguous whitespace (including tabs and multiple spaces) with a single underscore
792+
arg = re.sub(r"\s+", "_", arg)
793+
794+
# Remove all characters that are not alphanumeric, underscore, or dot
795+
arg = re.sub(r"[^\w._]", "", arg)
796+
797+
# Avoid filenames starting or ending with a dot or underscore
798+
arg = arg.strip("._")
799+
800+
# Fallback if resulting name is empty
801+
return arg or "untitled"
802+
786803
def runctx(self, cmd: str, global_vars: dict[str, Any], local_vars: dict[str, Any]) -> Tracer | None:
787804
self.__enter__()
788805
try:

0 commit comments

Comments
 (0)