tarfile: TarFile.offset attribute is not updated with the remainder when closing a TarFile
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 77.2k
- Fork
- 35.9k
- Chỉ số merge pull request
- Chỉ số pull request đang chờ
Mô tả
Bug report
Bug description:
The TarFile.offset attribute is not updated with the remainder when closing the tar.
import io
import pathlib
import tarfile
tar = tarfile.open("test.tar", "w")
t = tarfile.TarInfo("foo")
t.size = 123
tar.addfile(t, io.BytesIO(b"a" * t.size))
tar.close()
assert len(pathlib.Path("test.tar").read_bytes()) == tar.offset # Fails because tar.offset is 2048, although 10240 bytes have been written
If this intentional, a test case asserting the current behavior should be added.
In case this is not intentional, a suggested change to make the offset match the number of bytes written, and a test case asserting it, are included in the snippet below.
In either case, I'd be happy to submit a PR.
diff --git a/Lib/tarfile.py b/Lib/tarfile.py
index a0fab46b24e..feafb88d2d3 100644
--- a/Lib/tarfile.py
+++ b/Lib/tarfile.py
@@ -2027,6 +2027,7 @@ def close(self):
blocks, remainder = divmod(self.offset, RECORDSIZE)
if remainder > 0:
self.fileobj.write(NUL * (RECORDSIZE - remainder))
+ self.offset += (RECORDSIZE - remainder)
finally:
if not self._extfileobj:
self.fileobj.close()
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
index 2549b6b35ad..4d1a2b2171b 100644
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -1333,6 +1333,18 @@ def test_eof_marker(self):
with self.open(tmpname, "rb") as fobj:
self.assertEqual(len(fobj.read()), tarfile.RECORDSIZE * 2)
+ def test_offset_on_close(self):
+ # Check the offset after calling close matches the total number of
+ # bytes written.
+ tar = tarfile.open(tmpname, self.mode)
+ t = tarfile.TarInfo("foo")
+ tar.addfile(t)
+ tar.close()
+
+ with self.open(tmpname, "rb") as fobj:
+ self.assertEqual(len(fobj.read()), tar.offset)
+
class WriteTest(WriteTestBase, unittest.TestCase):
CPython versions tested on:
3.14, 3.13
Operating systems tested on:
Linux
Linked PRs
- gh-133919
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Các tệp liên quan là Lib/tarfile.py và Lib/test/test_tarfile.py. Trước tiên, hãy đọc TarFile.close và các kiểm thử EOF-marker hiện có, sau đó chạy bộ kiểm thử tarfile. Hoàn tất khi hành vi của offset được bao phủ một cách rõ ràng và khớp với số byte dự kiến được ghi sau khi đóng.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- python
- Lĩnh vực
- backend
- Loại issue
- Lỗi
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức phù hợp với người mới
- 25/100