Sign in

Search issue titles and bodies, change requests and comments. Private repositories you cannot read are not included.

vole
Site
Clone

Read only, no credentials:

https://rodent.software/vole.git

Write over SSH with a registered key:

git clone ssh://git@rodent.software/vole.git

Self-hosted forge that lives in your Git repo.

Blame · scripts/build-package-repos.py

Line attribution on main · 329 line(s)

73e98b74
Keenan Nemetz
15d ago
1 #!/usr/bin/env python3
fbdb3818
Keenan Nemetz
14d ago
2 """Turn a release's packages into the repositories apt, dnf, and pacman read.
73e98b74
Keenan Nemetz
15d ago
3
4 `vole release attach` publishes a directory tree, and a channel gives one URL
5 that follows a release, but neither is a repository on its own: apt reads a flat
fbdb3818
Keenan Nemetz
14d ago
6 `Packages` file and the `Release` that hashes it, dnf reads
7 `repodata/repomd.xml`, and pacman reads a per-architecture `vole.db`. This script
8 takes the `.deb`, `.rpm`, and Arch packages the release workflow just built and
9 writes the three trees beside them:
73e98b74
Keenan Nemetz
15d ago
10
11 dist/apt/ vole_<version>-1_<arch>.deb, Packages, Packages.gz, Release
12 dist/yum/ vole-<version>-1.<rpmarch>.rpm, repodata/
fbdb3818
Keenan Nemetz
14d ago
13 dist/pacman/<arch>/ vole-<version>-1-<arch>.pkg.tar.zst,
14 vole.db, vole.files, and the packages' .sig files
73e98b74
Keenan Nemetz
15d ago
15
16 The release attaches `dist`, so the release root keeps the binaries, the SBOM,
fbdb3818
Keenan Nemetz
14d ago
17 and SHA256SUMS beside `apt/`, `yum/`, and `pacman/`. A channel then makes one
18 stable URL:
73e98b74
Keenan Nemetz
15d ago
19
fbdb3818
Keenan Nemetz
14d ago
20 deb [signed-by=/etc/apt/keyrings/vole.asc] https://host/repo/channels/stable/apt ./
73e98b74
Keenan Nemetz
15d ago
21 baseurl=https://host/repo/channels/stable/yum/
fbdb3818
Keenan Nemetz
14d ago
22 Server = https://host/repo/channels/stable/pacman/$arch
73e98b74
Keenan Nemetz
15d ago
23
fbdb3818
Keenan Nemetz
14d ago
24 All three trees are byte-for-byte reproducible from a tag. `--epoch` is the
25 tag's commit time, and it supplies the `Date` in `Release`, the timestamps in
73e98b74
Keenan Nemetz
15d ago
26 `repomd.xml`, and the copied packages' mtimes, which createrepo_c records as
27 each package's file time. The `Packages` stanzas are sorted rather than left in
fbdb3818
Keenan Nemetz
14d ago
28 directory order, `Packages.gz` is written without a filename or clock in its
29 header, and the pacman databases are repacked with a fixed time and owner.
73e98b74
Keenan Nemetz
15d ago
30
31 It needs dpkg-dev (dpkg-scanpackages) and createrepo-c (createrepo_c), which the
32 release and verify images install. Nothing here signs anything: Vole does not
33 sign release artifacts yet, so the installation docs tell clients to trust the
34 host and to verify SHA256SUMS where that matters.
35 """
36
37 import argparse
38 import email.utils
39 import gzip
40 import hashlib
fbdb3818
Keenan Nemetz
14d ago
41 import io
73e98b74
Keenan Nemetz
15d ago
42 import os
43 import shutil
44 import subprocess
45 import sys
fbdb3818
Keenan Nemetz
14d ago
46 import tarfile
73e98b74
Keenan Nemetz
15d ago
47 import time
48 import xml.etree.ElementTree as ET
49 from pathlib import Path
50
fbdb3818
Keenan Nemetz
14d ago
51 # The architecture names differ between the formats: nfpm writes Debian's
52 # `amd64`, RPM's `x86_64`, and Arch's `x86_64` for the same build.
73e98b74
Keenan Nemetz
15d ago
53 DEB_ARCH = {"amd64": "amd64", "arm64": "arm64"}
54 RPM_ARCH = {"amd64": "x86_64", "arm64": "aarch64"}
fbdb3818
Keenan Nemetz
14d ago
55 PACMAN_ARCH = {"amd64": "x86_64", "arm64": "aarch64"}
73e98b74
Keenan Nemetz
15d ago
56
57 REPOMD_NS = {"r": "http://linux.duke.edu/metadata/repo"}
58
59
60 def digest(name: str, data: bytes) -> str:
61 return hashlib.new(name, data, usedforsecurity=False).hexdigest()
62
63
64 def stanza_key(stanza: str) -> tuple[str, str, str]:
65 """Order stanzas by the fields a Packages file is read by.
66
67 dpkg-scanpackages emits stanzas in directory order, which is not stable
68 across machines. Sorting by package, architecture, and version makes one tag
69 produce one file.
70 """
71 fields = {}
72 for line in stanza.splitlines():
73 if line.startswith((" ", "\t")):
74 continue # a continuation line of a value such as Description
75 name, _, value = line.partition(":")
76 fields[name] = value.strip()
77 return fields.get("Package", ""), fields.get("Architecture", ""), fields.get("Version", "")
78
79
80 def write_apt(apt: Path, debs: list[tuple[Path, str]], epoch: int) -> None:
81 """Write Packages, Packages.gz, and Release for a flat Debian repository."""
82 out = subprocess.run(
83 ["dpkg-scanpackages", "--multiversion", "."],
84 cwd=apt,
85 check=True,
86 capture_output=True,
87 text=True,
88 )
89 stanzas = [s for s in out.stdout.strip().split("\n\n") if s.strip()]
90 if len(stanzas) != len(debs):
91 sys.exit(
92 f"dpkg-scanpackages described {len(stanzas)} package(s), "
93 f"but {len(debs)} were copied"
94 )
95 stanzas.sort(key=stanza_key)
58ac37e0
Keenan Nemetz
15d ago
96 # dpkg-scanpackages writes the path relative to the repository root as
97 # "./name.deb". A client concatenates it to the source URL, so the leading
98 # dot segment only asks the server to normalise the path; the base name is
99 # the same file and resolves without a redirect.
100 stanzas = [
101 "\n".join(
102 "Filename: " + line[len("Filename: ./"):]
103 if line.startswith("Filename: ./")
104 else line
105 for line in stanza.splitlines()
106 )
107 for stanza in stanzas
108 ]
73e98b74
Keenan Nemetz
15d ago
109 packages = ("\n\n".join(stanzas) + "\n").encode()
110 (apt / "Packages").write_bytes(packages)
111 # mtime=0 keeps the clock (and the filename) out of the gzip header.
112 (apt / "Packages.gz").write_bytes(gzip.compress(packages, compresslevel=9, mtime=0))
113
114 # apt reads the hashes from Release and refuses a Packages file that does
115 # not match, so a truncated download or a half-written metadata file fails
116 # before it reaches a system.
117 lines = [
118 "Origin: Vole",
119 "Label: Vole",
120 "Suite: vole",
121 "Codename: vole",
122 f"Date: {email.utils.formatdate(epoch, usegmt=True)}",
123 "Architectures: " + " ".join(sorted(arch for _, arch in debs)),
124 "Components: main",
125 "Description: Vole packages",
126 ]
127 for label, name in (("MD5Sum", "md5"), ("SHA1", "sha1"), ("SHA256", "sha256")):
128 lines.append(f"{label}:")
129 for member in ("Packages", "Packages.gz"):
130 data = (apt / member).read_bytes()
131 lines.append(f" {digest(name, data)} {len(data):16d} {member}")
132 (apt / "Release").write_text("\n".join(lines) + "\n", encoding="utf-8")
133
134
fbdb3818
Keenan Nemetz
14d ago
135 def normalize_tar(path: Path, epoch: int) -> None:
136 """Rewrite a repository database with a fixed time, owner, and order.
137
138 repo-add stamps tar entry times from the clock, so two builds of one release
139 differ even when every field in the database is identical. The database is a
140 small tar; rewriting it costs little and makes a rebuild byte-identical.
141 """
142 with tarfile.open(path, "r:gz") as archive:
143 members = []
144 for member in archive.getmembers():
145 data = archive.extractfile(member).read() if member.isfile() else None
146 member.mtime = epoch
147 member.uid = 0
148 member.gid = 0
149 member.uname = ""
150 member.gname = ""
151 members.append((member, data))
152 buffer = io.BytesIO()
153 with tarfile.open(fileobj=buffer, mode="w", format=tarfile.USTAR_FORMAT) as archive:
154 for member, data in sorted(members, key=lambda item: item[0].name):
155 archive.addfile(member, io.BytesIO(data) if data is not None else None)
156 path.write_bytes(gzip.compress(buffer.getvalue(), compresslevel=9, mtime=0))
157
158
159 def write_pacman(pacman: Path, packages: dict[str, list[Path]], epoch: int) -> int:
160 """Write a per-architecture pacman database from the built packages.
161
162 A release signs the packages before this runs, so repo-add records
163 %PGPSIG% and pacman can require it. A local run without the release key has
164 no .sig files; the database is then unsigned, and sign-release.py refuses to
165 sign the database unless every package beside it is signed.
166 """
167 total = 0
168 for arch, sources in packages.items():
169 directory = pacman / arch
170 directory.mkdir(parents=True)
171 for source in sources:
172 signature = source.with_name(source.name + ".sig")
173 shutil.copyfile(source, directory / source.name)
174 (directory / source.name).chmod(0o644)
175 os.utime(directory / source.name, (epoch, epoch))
176 if signature.is_file():
177 shutil.copyfile(signature, directory / signature.name)
178 (directory / signature.name).chmod(0o644)
179 # repo-add writes vole.db.tar.gz and vole.files.tar.gz and points the
180 # names pacman requests at them with symlinks. Vole's artifact walker
181 # publishes regular files only, so the databases become real files.
182 subprocess.run(
183 ["repo-add", "--quiet", "--nocolor", "vole.db.tar.gz",
184 *[source.name for source in sources]],
185 cwd=directory,
186 check=True,
187 )
188 for name, entry in (("vole.db", "desc"), ("vole.files", "files")):
189 source = directory / (name + ".tar.gz")
190 target = directory / name
191 if not source.is_file():
192 sys.exit(f"repo-add produced no {name}.tar.gz in {directory}")
193 if target.is_symlink() or target.exists():
194 target.unlink()
195 shutil.copyfile(source, target)
196 source.unlink()
197 normalize_tar(target, epoch)
198 with tarfile.open(target, "r:gz") as archive:
199 if not any(member.name.endswith("/" + entry) for member in archive.getmembers()):
200 sys.exit(f"{target} has no {entry} entry")
201 total += len(sources)
202 return total
203
204
73e98b74
Keenan Nemetz
15d ago
205 def write_yum(yum: Path, epoch: int) -> None:
206 """Write repodata for an RPM repository with a pinned revision and clock."""
207 subprocess.run(
208 [
209 "createrepo_c",
210 "--quiet",
211 "--no-database",
212 "--revision", str(epoch),
213 # The revision is an epoch because this flag says so; it is the tag's
214 # commit time, which is also what the packages carry.
215 "--set-timestamp-to-revision",
216 ".",
217 ],
218 cwd=yum,
219 check=True,
220 )
221 repomd = yum / "repodata" / "repomd.xml"
222 if not repomd.is_file():
223 sys.exit("createrepo_c produced no repodata/repomd.xml")
224 # A location that names a missing file is a repository dnf cannot install
225 # from, and the error would surface on a user's machine after the tag was
226 # pushed. Every referenced file is in the tree this release publishes.
227 for location in ET.parse(repomd).getroot().findall(".//r:location", REPOMD_NS):
228 href = location.get("href", "")
229 if not (yum / href).is_file():
230 sys.exit(f"repomd.xml names a file that is not in the tree: {href}")
231
232
233 def main() -> None:
234 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
235 parser.add_argument("--dist", default="dist", help="directory holding the built packages (default: dist)")
fbdb3818
Keenan Nemetz
14d ago
236 parser.add_argument("--version", required=True, help="release version without the leading v; the Arch form is derived from it")
73e98b74
Keenan Nemetz
15d ago
237 parser.add_argument(
238 "--epoch",
239 type=int,
240 default=int(os.environ.get("SOURCE_DATE_EPOCH") or time.time()),
241 help="tag commit time in seconds (default: SOURCE_DATE_EPOCH, else the clock)",
242 )
243 parser.add_argument(
244 "--arch",
245 action="append",
246 choices=sorted(DEB_ARCH),
247 dest="architectures",
248 help="architecture to publish; repeatable (default: amd64 and arm64)",
249 )
250 args = parser.parse_args()
251 architectures = args.architectures or sorted(DEB_ARCH)
252
fbdb3818
Keenan Nemetz
14d ago
253 for tool, package in (
254 ("dpkg-scanpackages", "dpkg-dev"),
255 ("createrepo_c", "createrepo-c"),
256 ("repo-add", "pacman-package-manager"),
257 ("bsdtar", "libarchive-tools"),
258 ):
73e98b74
Keenan Nemetz
15d ago
259 if shutil.which(tool) is None:
260 sys.exit(
261 f"{tool} is not installed; the workflow images carry "
fbdb3818
Keenan Nemetz
14d ago
262 f"{package}, which provides it"
73e98b74
Keenan Nemetz
15d ago
263 )
264
265 dist = Path(args.dist).resolve()
266 if not dist.is_dir():
267 sys.exit(f"{args.dist} is not a directory")
fbdb3818
Keenan Nemetz
14d ago
268 # nfpm rewrites a prerelease hyphen to a tilde for Debian and RPM, so a tag
269 # v0.3.0-rc1 builds vole_0.3.0~rc1-1_amd64.deb. Arch's pkgver cannot carry
270 # that hyphen, so the same tag builds vole-0.3.0rc1-1-x86_64.pkg.tar.zst.
73e98b74
Keenan Nemetz
15d ago
271 package_version = args.version.replace("-", "~")
fbdb3818
Keenan Nemetz
14d ago
272 pacman_version = args.version.replace("-", "")
73e98b74
Keenan Nemetz
15d ago
273 apt = dist / "apt"
274 yum = dist / "yum"
fbdb3818
Keenan Nemetz
14d ago
275 pacman = dist / "pacman"
73e98b74
Keenan Nemetz
15d ago
276
277 # A package missing here would publish a repository that cannot install the
278 # release on the architecture it names, and a tag cannot be rebuilt.
279 deb_sources = [
280 (dist / f"vole_{package_version}-1_{DEB_ARCH[arch]}.deb", arch)
281 for arch in architectures
282 ]
283 rpm_sources = [
284 dist / f"vole-{package_version}-1.{RPM_ARCH[arch]}.rpm"
285 for arch in architectures
286 ]
fbdb3818
Keenan Nemetz
14d ago
287 pacman_packages = {
288 PACMAN_ARCH[arch]: [dist / f"vole-{pacman_version}-1-{PACMAN_ARCH[arch]}.pkg.tar.zst"]
289 for arch in architectures
290 }
73e98b74
Keenan Nemetz
15d ago
291 missing = [str(path) for path, _ in deb_sources if not path.is_file()]
292 missing += [str(path) for path in rpm_sources if not path.is_file()]
fbdb3818
Keenan Nemetz
14d ago
293 missing += [str(path) for paths in pacman_packages.values() for path in paths if not path.is_file()]
73e98b74
Keenan Nemetz
15d ago
294 if missing:
295 sys.exit("the packages for this release are not in " + args.dist + ":\n " + "\n ".join(missing))
296
fbdb3818
Keenan Nemetz
14d ago
297 for directory in (apt, yum, pacman):
73e98b74
Keenan Nemetz
15d ago
298 if directory.is_dir():
299 shutil.rmtree(directory)
300 directory.mkdir(parents=True)
301
302 debs = []
303 for source, arch in deb_sources:
304 destination = apt / source.name
305 shutil.copyfile(source, destination)
306 destination.chmod(0o644)
307 os.utime(destination, (args.epoch, args.epoch))
308 debs.append((destination, arch))
309
310 for source in rpm_sources:
311 destination = yum / source.name
312 shutil.copyfile(source, destination)
313 destination.chmod(0o644)
314 # createrepo_c records this as the package's file time in primary.xml.
315 os.utime(destination, (args.epoch, args.epoch))
316
317 write_apt(apt, debs, args.epoch)
318 write_yum(yum, args.epoch)
fbdb3818
Keenan Nemetz
14d ago
319 pacman_count = write_pacman(pacman, pacman_packages, args.epoch)
73e98b74
Keenan Nemetz
15d ago
320
321 print(
322 f"apt: {len(debs)} package(s) in {apt}\n"
fbdb3818
Keenan Nemetz
14d ago
323 f"yum: {len(architectures)} package(s) in {yum}\n"
324 f"pacman: {pacman_count} package(s) in {pacman}"
73e98b74
Keenan Nemetz
15d ago
325 )
326
327
328 if __name__ == "__main__":
329 main()