zip-deterministic 0.1.0__py3-none-any.whl

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,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,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,5 @@
1
+ zip_deterministic/__init__.py,sha256=c06J8GMqILU_H8LStzsRKIWReBtCp61YfzOVB-frwEc,5154
2
+ zip_deterministic-0.1.0.dist-info/METADATA,sha256=GRnEiQ19PWf7lCM4wBtZvRYh2QVchN1vbqvIIh3OAEI,3419
3
+ zip_deterministic-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ zip_deterministic-0.1.0.dist-info/licenses/LICENSE,sha256=3wTtgLzNnEFJPdhx7gyOtExVhhjxFHxZpQpqgLTcTd8,1072
5
+ zip_deterministic-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.