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
16 changes: 10 additions & 6 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1409,16 +1409,20 @@ def _split_bytes(text: str, budget: int) -> list[str]:
pieces: list[str] = []
current = ""
for line in text.splitlines(keepends=True):
if len(line.encode()) > budget:
encoded = line.encode()
if len(encoded) > budget:
if current:
pieces.append(current)
current = ""
while line:
cut = min(len(line), budget)
while len(line[:cut].encode()) > budget:
start = 0
while start < len(encoded):
cut = min(len(encoded), start + budget)
while cut < len(encoded) and encoded[cut] & 0xC0 == 0x80:
cut -= 1
pieces.append(line[:cut])
line = line[cut:]
if cut <= start:
raise ValueError("diff chunk budget cannot fit one UTF-8 character")
pieces.append(encoded[start:cut].decode())
start = cut
elif current and len((current + line).encode()) > budget:
pieces.append(current)
current = line
Expand Down
22 changes: 22 additions & 0 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1242,6 +1242,28 @@ def test_split_diff_summarizes_real_git_deletion(git_repo: Path, name: str, budg
assert chunks[0].split("\n", 1)[0] == diff.split("\n", 1)[0]


def test_split_diff_encodes_long_utf8_line_in_linear_work() -> None:
diff = "diff --git a/new.txt b/new.txt\n+" + "aé€😀" * 1500 + "\n"
budget = 511
encoded_chars = 0

def count_encodes(frame, event, arg):
nonlocal encoded_chars
if event == "c_call" and arg.__name__ == "encode" and isinstance(arg.__self__, str):
encoded_chars += len(arg.__self__)

previous = sys.getprofile()
sys.setprofile(count_encodes)
try:
chunks = split_diff(diff, budget)
finally:
sys.setprofile(previous)

assert "".join(chunks) == diff
assert all(len(chunk.encode()) <= budget for chunk in chunks)
assert encoded_chars <= 5 * len(diff)


# ----------------------------------------------------------------- family detection


Expand Down
Loading