From b3198c04a757ec49c1b01de3f49572aa7a533cb3 Mon Sep 17 00:00:00 2001 From: pander <> Date: Thu, 7 May 2026 00:06:41 +0800 Subject: [PATCH] fix(file_operations): correct total_lines count for files without trailing newline Closes #3907 wc -l counts newline characters, not lines. A file without a trailing newline (e.g. content ending with 'line3' not 'line3\n') has one more line than wc -l reports. Fix: check if the last byte of the file is 0a (\n) and add 1 to the count if it is not. --- tools/file_operations.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tools/file_operations.py b/tools/file_operations.py index 92a948eaaf7b5..4cc2711141f18 100644 --- a/tools/file_operations.py +++ b/tools/file_operations.py @@ -692,6 +692,16 @@ class ShellFileOperations(FileOperations): total_lines = int(wc_output.strip()) except ValueError: total_lines = 0 + + # wc -l counts newline characters, not lines. A file without a trailing + # newline has one more line of content than wc -l reports. Detect this + # by checking if the last byte of the file is 0a (\n). + if file_size > 0: + tail_cmd = f"tail -c 1 {self._escape_shell_arg(path)} | od -An -tx1 | tr -d ' '" + tail_result = self._exec(tail_cmd) + last_byte = tail_result.stdout.strip() + if last_byte and last_byte != "0a": + total_lines += 1 # Check if truncated truncated = total_lines > end_line