zip-deterministic 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ name: tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ${{ matrix.os }}
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ os: [ubuntu-latest, windows-latest, macos-latest]
15
+ python: ["3.9", "3.10", "3.11", "3.12", "3.13"]
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: ${{ matrix.python }}
21
+ - run: python -m pip install -e ".[test]" ruff
22
+ - run: python -m ruff check .
23
+ - run: python -m pytest -q
@@ -0,0 +1,38 @@
1
+ name: release
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.12"
16
+ - run: python -m pip install build twine
17
+ - run: python -m build
18
+ - run: python -m twine check dist/*
19
+ - uses: actions/upload-artifact@v4
20
+ with:
21
+ name: dist
22
+ path: dist/
23
+
24
+ publish:
25
+ needs: build
26
+ # Set the PYPI_READY repository variable once PyPI trusted publishing is
27
+ # configured for this project; until then the release only builds.
28
+ if: vars.PYPI_READY == 'true'
29
+ runs-on: ubuntu-latest
30
+ environment: pypi
31
+ permissions:
32
+ id-token: write
33
+ steps:
34
+ - uses: actions/download-artifact@v4
35
+ with:
36
+ name: dist
37
+ path: dist/
38
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .venv-test/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .ruff_cache/
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release.
6
+
7
+ - `zip_bytes` / `write_zip`: sorted members, 1980-01-01 timestamps, fixed mode,
8
+ normalised separators, no extra fields.
9
+ - `tar_bytes` / `write_tar`: sorted members, mtime 0, fixed mode, gzip header with the
10
+ timestamp and name cleared.
11
+ - Refuses absolute paths, `..` traversal and duplicate members.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sandesh Bagmare
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.5
2
+ Name: zip-deterministic
3
+ Version: 0.1.0
4
+ Summary: Reproducible zip and tar archives: pinned timestamps, modes and ordering
5
+ Project-URL: Homepage, https://github.com/sandeshbagmare/zip-deterministic
6
+ Project-URL: Issues, https://github.com/sandeshbagmare/zip-deterministic/issues
7
+ Project-URL: Changelog, https://github.com/sandeshbagmare/zip-deterministic/blob/main/CHANGELOG.md
8
+ Author: Sandesh Bagmare
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: archive,build,deterministic,reproducible,tar,zip
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.9
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=8; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # zip-deterministic
24
+
25
+ Build the same archive twice, get the **same bytes**.
26
+
27
+ ```python
28
+ from zip_deterministic import zip_bytes
29
+
30
+ assert zip_bytes({"a.txt": b"hello"}) == zip_bytes({"a.txt": b"hello"})
31
+ ```
32
+
33
+ A zip or tar file stores the modification time, permission bits and member order of
34
+ everything it contains, so two builds of the same tree normally differ. That breaks
35
+ cache keys, signatures, reproducible builds and "did this artifact really change?"
36
+ comparisons. This package pins all of it:
37
+
38
+ | value | default | why |
39
+ | ----- | ------- | --- |
40
+ | modification time | `1980-01-01 00:00:00` for zip, `0` for tar | the earliest zip can store, and the reproducible-builds convention for tar |
41
+ | permissions | `0o644` | no umask, no author's home directory leaking into the artifact |
42
+ | member order | sorted by name | the order of a `dict` or a directory listing must not matter |
43
+ | gzip header | no timestamp, no file name | `gzip` writes the current time and the name of the file it compressed |
44
+
45
+ Zero dependencies, Python 3.9+.
46
+
47
+ ## Install
48
+
49
+ ```console
50
+ pip install zip-deterministic
51
+ ```
52
+
53
+ ## Use
54
+
55
+ ```python
56
+ from zip_deterministic import zip_bytes, tar_bytes, write_zip, write_tar
57
+
58
+ data = zip_bytes(
59
+ {"README.md": b"# hello\n", "src/app.py": b"print('hi')\n"},
60
+ compression=__import__("zipfile").ZIP_DEFLATED,
61
+ level=6,
62
+ )
63
+
64
+ tar = tar_bytes({"README.md": b"# hello\n"}) # .tar.gz, gzip header cleared
65
+ plain = tar_bytes({"README.md": b"# hello\n"}, gz=False) # bare .tar
66
+
67
+ write_zip("release.zip", {"a.txt": b"a"}) # returns the size in bytes
68
+ write_tar("release.tar.gz", {"a.txt": b"a"})
69
+ ```
70
+
71
+ Executables keep their bit when you ask for it:
72
+
73
+ ```python
74
+ zip_bytes({"bin/run.sh": b"#!/bin/sh\n"}, mode=0o755)
75
+ ```
76
+
77
+ Members are checked before anything is written. Absolute paths, `..` traversal,
78
+ duplicate names and non-bytes content raise instead of producing an archive that
79
+ extracts outside the target directory.
80
+
81
+ ## What it does not do
82
+
83
+ - It does not walk a directory for you: pass the members, so the caller decides what
84
+ goes in and in what encoding.
85
+ - Symbols, hard links and directories are not modelled; only regular file members.
86
+ - Deflate output still depends on the zlib version. Same interpreter and zlib, same
87
+ bytes; across zlib versions the compressed stream may differ, which is why the
88
+ reproducible-builds project recommends `ZIP_STORED` when that matters.
89
+
90
+ ## Development
91
+
92
+ ```console
93
+ python -m venv .venv
94
+ .venv/bin/pip install -e ".[test]"
95
+ .venv/bin/pytest
96
+ ```
97
+
98
+ ## License
99
+
100
+ MIT.
@@ -0,0 +1,78 @@
1
+ # zip-deterministic
2
+
3
+ Build the same archive twice, get the **same bytes**.
4
+
5
+ ```python
6
+ from zip_deterministic import zip_bytes
7
+
8
+ assert zip_bytes({"a.txt": b"hello"}) == zip_bytes({"a.txt": b"hello"})
9
+ ```
10
+
11
+ A zip or tar file stores the modification time, permission bits and member order of
12
+ everything it contains, so two builds of the same tree normally differ. That breaks
13
+ cache keys, signatures, reproducible builds and "did this artifact really change?"
14
+ comparisons. This package pins all of it:
15
+
16
+ | value | default | why |
17
+ | ----- | ------- | --- |
18
+ | modification time | `1980-01-01 00:00:00` for zip, `0` for tar | the earliest zip can store, and the reproducible-builds convention for tar |
19
+ | permissions | `0o644` | no umask, no author's home directory leaking into the artifact |
20
+ | member order | sorted by name | the order of a `dict` or a directory listing must not matter |
21
+ | gzip header | no timestamp, no file name | `gzip` writes the current time and the name of the file it compressed |
22
+
23
+ Zero dependencies, Python 3.9+.
24
+
25
+ ## Install
26
+
27
+ ```console
28
+ pip install zip-deterministic
29
+ ```
30
+
31
+ ## Use
32
+
33
+ ```python
34
+ from zip_deterministic import zip_bytes, tar_bytes, write_zip, write_tar
35
+
36
+ data = zip_bytes(
37
+ {"README.md": b"# hello\n", "src/app.py": b"print('hi')\n"},
38
+ compression=__import__("zipfile").ZIP_DEFLATED,
39
+ level=6,
40
+ )
41
+
42
+ tar = tar_bytes({"README.md": b"# hello\n"}) # .tar.gz, gzip header cleared
43
+ plain = tar_bytes({"README.md": b"# hello\n"}, gz=False) # bare .tar
44
+
45
+ write_zip("release.zip", {"a.txt": b"a"}) # returns the size in bytes
46
+ write_tar("release.tar.gz", {"a.txt": b"a"})
47
+ ```
48
+
49
+ Executables keep their bit when you ask for it:
50
+
51
+ ```python
52
+ zip_bytes({"bin/run.sh": b"#!/bin/sh\n"}, mode=0o755)
53
+ ```
54
+
55
+ Members are checked before anything is written. Absolute paths, `..` traversal,
56
+ duplicate names and non-bytes content raise instead of producing an archive that
57
+ extracts outside the target directory.
58
+
59
+ ## What it does not do
60
+
61
+ - It does not walk a directory for you: pass the members, so the caller decides what
62
+ goes in and in what encoding.
63
+ - Symbols, hard links and directories are not modelled; only regular file members.
64
+ - Deflate output still depends on the zlib version. Same interpreter and zlib, same
65
+ bytes; across zlib versions the compressed stream may differ, which is why the
66
+ reproducible-builds project recommends `ZIP_STORED` when that matters.
67
+
68
+ ## Development
69
+
70
+ ```console
71
+ python -m venv .venv
72
+ .venv/bin/pip install -e ".[test]"
73
+ .venv/bin/pytest
74
+ ```
75
+
76
+ ## License
77
+
78
+ MIT.
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "zip-deterministic"
7
+ version = "0.1.0"
8
+ description = "Reproducible zip and tar archives: pinned timestamps, modes and ordering"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Sandesh Bagmare" }]
13
+ keywords = ["reproducible", "zip", "tar", "deterministic", "archive", "build"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/sandeshbagmare/zip-deterministic"
26
+ Issues = "https://github.com/sandeshbagmare/zip-deterministic/issues"
27
+ Changelog = "https://github.com/sandeshbagmare/zip-deterministic/blob/main/CHANGELOG.md"
28
+
29
+ [project.optional-dependencies]
30
+ test = ["pytest>=8"]
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/zip_deterministic"]
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+ addopts = "-q"
38
+
39
+ [tool.ruff]
40
+ line-length = 100
41
+ target-version = "py39"
42
+
43
+ [tool.ruff.lint]
44
+ select = ["E", "F", "I", "UP", "B", "SIM"]
@@ -0,0 +1,154 @@
1
+ """Write archives whose bytes do not change between runs.
2
+
3
+ A zip or tar file records the modification time, permissions and order of every
4
+ member, so building the same tree twice usually gives two different files, which
5
+ breaks cache keys, signatures and reproducible builds. This module writes archives
6
+ with those values pinned.
7
+
8
+ >>> from zip_deterministic import zip_bytes
9
+ >>> data = zip_bytes({"a.txt": b"hello"})
10
+ >>> zip_bytes({"a.txt": b"hello"}) == data
11
+ True
12
+
13
+ The defaults follow the reproducible-builds convention: modification time
14
+ 1980-01-01 00:00:00 (the earliest a zip can express), permissions ``0o644``, entries
15
+ in sorted order, no extra fields, and gzip headers with the timestamp and file name
16
+ cleared.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import gzip
22
+ import io
23
+ import os
24
+ import tarfile
25
+ import time
26
+ import zipfile
27
+ from collections.abc import Iterable, Mapping
28
+ from pathlib import Path
29
+
30
+ __all__ = [
31
+ "DEFAULT_DATE_TIME",
32
+ "DEFAULT_MODE",
33
+ "tar_bytes",
34
+ "write_tar",
35
+ "write_zip",
36
+ "zip_bytes",
37
+ ]
38
+
39
+ __version__ = "0.1.0"
40
+
41
+ #: 1980-01-01 00:00:00, the earliest timestamp a zip file can store.
42
+ DEFAULT_DATE_TIME = (1980, 1, 1, 0, 0, 0)
43
+ DEFAULT_MODE = 0o644
44
+
45
+ Entry = tuple[str, bytes]
46
+
47
+
48
+ def _entries(source: Mapping[str, bytes] | Iterable[Entry]) -> list[Entry]:
49
+ """Return the members as a sorted list, rejecting unsafe or duplicate names."""
50
+ items = list(source.items()) if isinstance(source, Mapping) else list(source)
51
+ seen: set[str] = set()
52
+ for name, data in items:
53
+ if not isinstance(name, str):
54
+ raise TypeError(f"archive member name must be str, got {type(name).__name__}")
55
+ if not isinstance(data, (bytes, bytearray, memoryview)):
56
+ raise TypeError(f"archive member {name!r} must be bytes")
57
+ normalised = name.replace(os.sep, "/")
58
+ if normalised.startswith("/") or ".." in normalised.split("/"):
59
+ raise ValueError(f"archive member escapes the root: {name!r}")
60
+ if normalised in seen:
61
+ raise ValueError(f"duplicate archive member: {name!r}")
62
+ seen.add(normalised)
63
+ return sorted(((name.replace(os.sep, "/"), bytes(data)) for name, data in items))
64
+
65
+
66
+ def zip_bytes(
67
+ members: Mapping[str, bytes] | Iterable[Entry],
68
+ *,
69
+ date_time: tuple[int, int, int, int, int, int] = DEFAULT_DATE_TIME,
70
+ mode: int = DEFAULT_MODE,
71
+ compression: int = zipfile.ZIP_DEFLATED,
72
+ level: int | None = 6,
73
+ ) -> bytes:
74
+ """Return a zip archive of ``members`` as bytes."""
75
+ buffer = io.BytesIO()
76
+ with zipfile.ZipFile(buffer, "w", compression=compression, allowZip64=True) as archive:
77
+ for name, data in _entries(members):
78
+ info = zipfile.ZipInfo(filename=name, date_time=date_time)
79
+ info.external_attr = (mode & 0xFFFF) << 16
80
+ info.create_system = 3 # Unix, so the permission bits are read as Unix bits
81
+ info.compress_type = compression
82
+ if level is not None:
83
+ archive.writestr(info, data, compresslevel=level)
84
+ else: # pragma: no cover - only for stored archives
85
+ archive.writestr(info, data)
86
+ return buffer.getvalue()
87
+
88
+
89
+ def write_zip(
90
+ path: str | os.PathLike[str],
91
+ members: Mapping[str, bytes] | Iterable[Entry],
92
+ **kwargs,
93
+ ) -> int:
94
+ """Write a zip archive to ``path`` and return its size in bytes."""
95
+ data = zip_bytes(members, **kwargs)
96
+ Path(path).write_bytes(data)
97
+ return len(data)
98
+
99
+
100
+ def _tar_info(name: str, size: int, mtime: int, mode: int) -> tarfile.TarInfo:
101
+ info = tarfile.TarInfo(name)
102
+ info.size = size
103
+ info.mtime = mtime
104
+ info.mode = mode
105
+ info.uid = info.gid = 0
106
+ info.uname = info.gname = ""
107
+ info.type = tarfile.REGTYPE
108
+ return info
109
+
110
+
111
+ def tar_bytes(
112
+ members: Mapping[str, bytes] | Iterable[Entry],
113
+ *,
114
+ mtime: int = 0,
115
+ mode: int = DEFAULT_MODE,
116
+ gz: bool = True,
117
+ compresslevel: int = 9,
118
+ ) -> bytes:
119
+ """Return a tar (or ``.tar.gz``) archive of ``members`` as bytes."""
120
+ buffer = io.BytesIO()
121
+ format_ = tarfile.PAX_FORMAT
122
+ with tarfile.open(fileobj=buffer, mode="w", format=format_) as archive:
123
+ for name, data in _entries(members):
124
+ archive.addfile(_tar_info(name, len(data), mtime, mode), io.BytesIO(data))
125
+ raw = buffer.getvalue()
126
+ if not gz:
127
+ return raw
128
+ compressed = io.BytesIO()
129
+ # mtime=0 and an empty filename keep the gzip header identical between runs.
130
+ with gzip.GzipFile(
131
+ filename="",
132
+ mode="wb",
133
+ fileobj=compressed,
134
+ mtime=0,
135
+ compresslevel=compresslevel,
136
+ ) as handle:
137
+ handle.write(raw)
138
+ return compressed.getvalue()
139
+
140
+
141
+ def write_tar(
142
+ path: str | os.PathLike[str],
143
+ members: Mapping[str, bytes] | Iterable[Entry],
144
+ **kwargs,
145
+ ) -> int:
146
+ """Write a tar archive to ``path`` and return its size in bytes."""
147
+ data = tar_bytes(members, **kwargs)
148
+ Path(path).write_bytes(data)
149
+ return len(data)
150
+
151
+
152
+ def now_as_zip_time() -> tuple[int, int, int, int, int, int]:
153
+ """The current time in the tuple form a zip file wants, for opt-out use."""
154
+ return time.localtime()[:6]
@@ -0,0 +1,132 @@
1
+ """Tests for zip_deterministic."""
2
+
3
+ import gzip
4
+ import io
5
+ import tarfile
6
+ import time
7
+ import zipfile
8
+
9
+ import pytest
10
+
11
+ from zip_deterministic import (
12
+ DEFAULT_DATE_TIME,
13
+ DEFAULT_MODE,
14
+ tar_bytes,
15
+ write_tar,
16
+ write_zip,
17
+ zip_bytes,
18
+ )
19
+
20
+
21
+ class TestZip:
22
+ def test_two_builds_are_byte_identical(self):
23
+ members = {"b.txt": b"second", "a.txt": b"first"}
24
+ assert zip_bytes(members) == zip_bytes(dict(reversed(list(members.items()))))
25
+
26
+ def test_round_trips_through_zipfile(self):
27
+ data = zip_bytes({"a.txt": b"hello", "dir/b.bin": b"\x00\xff"})
28
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
29
+ assert archive.namelist() == ["a.txt", "dir/b.bin"]
30
+ assert archive.read("a.txt") == b"hello"
31
+
32
+ def test_entry_order_is_sorted(self):
33
+ data = zip_bytes({"z.txt": b"z", "a.txt": b"a", "m/x.txt": b"m"})
34
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
35
+ assert archive.namelist() == ["a.txt", "m/x.txt", "z.txt"]
36
+
37
+ def test_timestamp_is_pinned(self):
38
+ with zipfile.ZipFile(io.BytesIO(zip_bytes({"a.txt": b"a"}))) as archive:
39
+ assert archive.getinfo("a.txt").date_time == DEFAULT_DATE_TIME
40
+
41
+ def test_permissions_are_pinned(self):
42
+ with zipfile.ZipFile(io.BytesIO(zip_bytes({"a.txt": b"a"}))) as archive:
43
+ mode = archive.getinfo("a.txt").external_attr >> 16
44
+ assert mode == DEFAULT_MODE
45
+
46
+ def test_permissions_can_be_chosen(self):
47
+ data = zip_bytes({"run.sh": b"#!/bin/sh\n"}, mode=0o755)
48
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
49
+ assert archive.getinfo("run.sh").external_attr >> 16 == 0o755
50
+
51
+ def test_windows_separators_are_normalised(self):
52
+ with zipfile.ZipFile(io.BytesIO(zip_bytes({"dir\\a.txt": b"a"}))) as archive:
53
+ assert archive.namelist() == ["dir/a.txt"]
54
+
55
+ def test_accepts_an_iterable_of_pairs(self):
56
+ with zipfile.ZipFile(io.BytesIO(zip_bytes([("a.txt", b"a")]))) as archive:
57
+ assert archive.namelist() == ["a.txt"]
58
+
59
+ def test_rejects_absolute_paths(self):
60
+ with pytest.raises(ValueError, match="escapes the root"):
61
+ zip_bytes({"/etc/passwd": b"x"})
62
+
63
+ def test_rejects_traversal(self):
64
+ with pytest.raises(ValueError, match="escapes the root"):
65
+ zip_bytes({"../outside.txt": b"x"})
66
+
67
+ def test_rejects_duplicate_members(self):
68
+ with pytest.raises(ValueError, match="duplicate"):
69
+ zip_bytes([("a.txt", b"1"), ("a.txt", b"2")])
70
+
71
+ def test_rejects_non_bytes_content(self):
72
+ with pytest.raises(TypeError, match="must be bytes"):
73
+ zip_bytes({"a.txt": "text"}) # type: ignore[dict-item]
74
+
75
+ def test_rejects_non_string_names(self):
76
+ with pytest.raises(TypeError, match="must be str"):
77
+ zip_bytes({1: b"x"}) # type: ignore[dict-item]
78
+
79
+ def test_write_zip_returns_the_size(self, tmp_path):
80
+ target = tmp_path / "out.zip"
81
+ size = write_zip(target, {"a.txt": b"hello"})
82
+ assert size == target.stat().st_size
83
+ with zipfile.ZipFile(target) as archive:
84
+ assert archive.read("a.txt") == b"hello"
85
+
86
+
87
+ class TestTar:
88
+ def test_two_builds_are_byte_identical(self):
89
+ members = {"b.txt": b"second", "a.txt": b"first"}
90
+ assert tar_bytes(members) == tar_bytes(dict(reversed(list(members.items()))))
91
+
92
+ def test_round_trips_through_tarfile(self):
93
+ data = tar_bytes({"a.txt": b"hello"}, gz=False)
94
+ with tarfile.open(fileobj=io.BytesIO(data)) as archive:
95
+ assert archive.getnames() == ["a.txt"]
96
+ assert archive.extractfile("a.txt").read() == b"hello"
97
+
98
+ def test_gzip_header_carries_no_timestamp_or_name(self):
99
+ data = tar_bytes({"a.txt": b"hello"})
100
+ header = data[:10]
101
+ assert header[:2] == b"\x1f\x8b"
102
+ assert int.from_bytes(header[4:8], "little") == 0
103
+ assert header[3] & 0x08 == 0 # FNAME unset
104
+ with gzip.open(io.BytesIO(data)) as handle:
105
+ assert handle.read()
106
+
107
+ def test_metadata_is_pinned(self):
108
+ data = tar_bytes({"a.txt": b"hello"}, gz=False, mtime=1_600_000_000, mode=0o600)
109
+ with tarfile.open(fileobj=io.BytesIO(data)) as archive:
110
+ info = archive.getmember("a.txt")
111
+ assert (info.mtime, info.mode, info.uid, info.gid) == (1_600_000_000, 0o600, 0, 0)
112
+
113
+ def test_defaults_use_epoch_zero(self):
114
+ data = tar_bytes({"a.txt": b"hello"}, gz=False)
115
+ with tarfile.open(fileobj=io.BytesIO(data)) as archive:
116
+ assert archive.getmember("a.txt").mtime == 0
117
+
118
+ def test_write_tar_returns_the_size(self, tmp_path):
119
+ target = tmp_path / "out.tar.gz"
120
+ size = write_tar(target, {"a.txt": b"hello"})
121
+ assert size == target.stat().st_size
122
+
123
+ def test_rejects_traversal(self):
124
+ with pytest.raises(ValueError, match="escapes the root"):
125
+ tar_bytes({"../outside.txt": b"x"})
126
+
127
+
128
+ def test_gzip_reproducible_across_time(monkeypatch):
129
+ """Two calls separated by a clock change must still match."""
130
+ first = tar_bytes({"a.txt": b"hello"})
131
+ monkeypatch.setattr(time, "time", lambda: 1_900_000_000)
132
+ assert tar_bytes({"a.txt": b"hello"}) == first