Skip to content
Open
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
3 changes: 2 additions & 1 deletion py/envoy.base.utils/envoy/base/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ def last_n_bytes_of(target: str | pathlib.Path, n: int = 1) -> bytes:
"""Return the last `n` bytes from a file, defaults to 1 byte."""
with open(target, "rb") as f:
f.seek(0, os.SEEK_END)
f.seek(f.tell() - n)
# Clamp to the start of the file so empty or short files do not raise on negative seek.
f.seek(max(f.tell() - n, 0))
return f.read(n)


Expand Down
8 changes: 7 additions & 1 deletion py/envoy.base.utils/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pathlib
import tempfile
from unittest.mock import MagicMock

import pytest
Expand Down Expand Up @@ -271,7 +272,7 @@ def test_last_n_bytes_of(patches, n):
assert (
m_open.return_value.__enter__.return_value.seek.call_args_list
== [[(0, m_os.SEEK_END), {}],
[(23 - (n or 1), ), {}]])
[(max(23 - (n or 1), 0), ), {}]])
assert (
m_open.return_value.__enter__.return_value.tell.call_args
== [(), {}])
Expand All @@ -280,6 +281,11 @@ def test_last_n_bytes_of(patches, n):
== [(n or 1, ), {}])


def test_last_n_bytes_of_empty_file():
with tempfile.NamedTemporaryFile() as f:
assert utils.last_n_bytes_of(f.name) == b""


def test_minor_version_for(patches):
patched = patches(
"_version",
Expand Down
Loading