Debian Codegraph @

tools/retar.py

raw
1 """
2 Un-targz and retargz a targz file to ensure reproducible build.
3
4 usage:
5
6 $ export SOURCE_DATE_EPOCH=$(date +%s)
7 # or
8 $ export SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)
9 ...
10 $ python retar.py <tarfile.gz>
11
12 The process of creating an sdist can be non-reproducible:
13 - directory created during the process get a mtime of the creation date;
14 - gziping files embed the timestamp of zip creation.
15
16 This will untar-retar; ensuring that all mtime > SOURCE_DATE_EPOCH will be set
17 equal to SOURCE_DATE_EPOCH.
18
19 """
20
21 import tarfile
22 import sys
23 import os
24 import gzip
25 import io
26
27 from pathlib import Path
28
29 if len(sys.argv) > 2:
30 raise ValueError("Too many arguments")
31
32
33 timestamp = int(os.environ["SOURCE_DATE_EPOCH"])
34
35 path = Path(sys.argv[1])
36 old_buf = io.BytesIO()
37 with open(path, "rb") as f:
38 old_buf.write(f.read())
39 old_buf.seek(0)
40 if path.name.endswith("gz"):
41 r_mode = "r:gz"
42 if path.name.endswith("bz2"):
43 r_mode = "r:bz2"
44 if path.name.endswith("xz"):
45 raise ValueError("XZ is deprecated but it's written nowhere")
46 old = tarfile.open(fileobj=old_buf, mode=r_mode)
47
48 buf = io.BytesIO()
49 new = tarfile.open(fileobj=buf, mode="w", format=tarfile.GNU_FORMAT)
50 for i, m in enumerate(old):
51 data = None
52 # mutation does not work, copy
53 if m.name.endswith('.DS_Store'):
54 continue
55 m2 = tarfile.TarInfo(m.name)
56 m2.mtime = min(timestamp, m.mtime)
57 m2.pax_headers["mtime"] = m2.mtime
58 m2.size = m.size
59 m2.type = m.type
60 m2.linkname = m.linkname
61 m2.mode = m.mode
62 if m.isdir():
63 new.addfile(m2)
64 else:
65 data = old.extractfile(m)
66 new.addfile(m2, data)
67 new.close()
68 old.close()
69
70 buf.seek(0)
71
72 if r_mode == "r:gz":
73 with open(path, "wb") as f:
74 with gzip.GzipFile("", "wb", fileobj=f, mtime=timestamp) as gzf:
75 gzf.write(buf.read())
76 elif r_mode == "r:bz2":
77 import bz2
78
79 with bz2.open(path, "wb") as f:
80 f.write(buf.read())
81
82 else:
83 assert False
84
85 # checks the archive is valid.
86 archive = tarfile.open(path)
87 names = archive.getnames()