feat(server): add self-hosted fws Arch repo server and Caddy config
Publishes the Python stdlib server (admin UI, upload API, repo-add compatible DB generation) with its deployed Caddyfile, install script and pacman client snippet, so the whole fws repository stack lives next to the package sources. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
1 parent
a73a901389
commit
c903e28254
10 files changed
+1851
No files matched your search
Executable
+412
@@ -0,0 +1,412 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Outils de dépôt pacman : inspection des paquets et génération des bases.
|
||||
|
||||
Tout repose sur la bibliothèque standard de Python (plus zstd/xz/gzip en ligne de
|
||||
commande). Le résultat a la même structure que celle produite par `repo-add`
|
||||
(<repo>.db.tar.gz + lien <repo>.db, idem pour .files), ce qui permet de tenir un
|
||||
dépôt Arch depuis une machine où pacman n'est pas installé.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
|
||||
PKG_FILENAME_RE = re.compile(
|
||||
r"^[A-Za-z0-9@._+][A-Za-z0-9@._+-]*\.pkg\.tar\.(?:zst|xz|gz)$"
|
||||
)
|
||||
|
||||
# Champs écrits dans le fichier `desc` de la base, dans l'ordre de repo-add.
|
||||
DESC_FIELDS = (
|
||||
("FILENAME", "filename"),
|
||||
("NAME", "name"),
|
||||
("BASE", "base"),
|
||||
("VERSION", "version"),
|
||||
("DESC", "desc"),
|
||||
("CSIZE", "csize"),
|
||||
("ISIZE", "isize"),
|
||||
("MD5SUM", "md5sum"),
|
||||
("SHA256SUM", "sha256sum"),
|
||||
("URL", "url"),
|
||||
("LICENSE", "licenses"),
|
||||
("ARCH", "arch"),
|
||||
("BUILDDATE", "builddate"),
|
||||
("PACKAGER", "packager"),
|
||||
("GROUPS", "groups"),
|
||||
("REPLACES", "replaces"),
|
||||
("CONFLICTS", "conflicts"),
|
||||
("PROVIDES", "provides"),
|
||||
("DEPENDS", "depends"),
|
||||
("OPTDEPENDS", "optdepends"),
|
||||
("MAKEDEPENDS", "makedepends"),
|
||||
("CHECKDEPENDS", "checkdepends"),
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Inspection des paquets
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def is_pkg_filename(name: str) -> bool:
|
||||
"""Vrai si le nom est un nom de paquet pacman valide et sans chemin."""
|
||||
return bool(PKG_FILENAME_RE.match(name)) and "/" not in name and ".." not in name
|
||||
|
||||
|
||||
def _decompress_cmd(path: str) -> list[str]:
|
||||
"""Détecte la compression par les octets magiques (le nom peut être *.part)."""
|
||||
with open(path, "rb") as handle:
|
||||
magic = handle.read(6)
|
||||
if magic[:4] == b"\x28\xb5\x2f\xfd":
|
||||
return ["zstd", "-dc", path]
|
||||
if magic[:6] == b"\xfd7zXZ\x00":
|
||||
return ["xz", "-dc", path]
|
||||
if magic[:2] == b"\x1f\x8b":
|
||||
return ["gzip", "-dc", path]
|
||||
raise ValueError("format d'archive non reconnu (zst, xz ou gz attendu)")
|
||||
|
||||
|
||||
def _close_process(proc: subprocess.Popen) -> str:
|
||||
"""Tue le processus s'il tourne encore et renvoie sa sortie d'erreur."""
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
stderr = b""
|
||||
try:
|
||||
if proc.stderr:
|
||||
stderr = proc.stderr.read() or b""
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
for stream in (proc.stdout, proc.stderr):
|
||||
try:
|
||||
if stream:
|
||||
stream.close()
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
proc.wait()
|
||||
return stderr.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def parse_pkginfo(text: str) -> dict[str, list[str]]:
|
||||
""".PKGINFO -> {clé: [valeurs]} (les clés peuvent apparaître plusieurs fois)."""
|
||||
info: dict[str, list[str]] = {}
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or " = " not in line:
|
||||
continue
|
||||
key, value = line.split(" = ", 1)
|
||||
info.setdefault(key.strip(), []).append(value.strip())
|
||||
return info
|
||||
|
||||
|
||||
def _with_parent_dirs(entries: list[str]) -> list[str]:
|
||||
"""Complète la liste avec les répertoires parents manquants (avec « / »)."""
|
||||
seen = set(entries)
|
||||
for entry in entries:
|
||||
parts = entry.rstrip("/").split("/")
|
||||
for depth in range(1, len(parts)):
|
||||
parent = "/".join(parts[:depth]) + "/"
|
||||
if parent not in seen:
|
||||
seen.add(parent)
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def _read_archive(path: str) -> tuple[dict[str, list[str]], list[str]]:
|
||||
"""Lit .PKGINFO et la liste des fichiers sans extraire le paquet."""
|
||||
cmd = _decompress_cmd(path)
|
||||
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
info: dict[str, list[str]] = {}
|
||||
entries: list[str] = []
|
||||
try:
|
||||
try:
|
||||
with tarfile.open(fileobj=proc.stdout, mode="r|") as archive:
|
||||
for member in archive:
|
||||
name = member.name
|
||||
while name.startswith("./"):
|
||||
name = name[2:]
|
||||
name = name.rstrip("/")
|
||||
if not name or name == ".":
|
||||
continue
|
||||
if name == ".PKGINFO":
|
||||
handle = archive.extractfile(member)
|
||||
if handle is not None:
|
||||
info = parse_pkginfo(
|
||||
handle.read().decode("utf-8", "replace")
|
||||
)
|
||||
continue
|
||||
if name.startswith("."):
|
||||
# .BUILDINFO, .MTREE, .INSTALL, .CHANGELOG, .PKGINFO
|
||||
continue
|
||||
if member.isdir():
|
||||
entries.append(name + "/")
|
||||
elif member.isfile() or member.issym() or member.islnk():
|
||||
entries.append(name)
|
||||
except tarfile.TarError as exc:
|
||||
raise ValueError(f"archive illisible : {exc}") from exc
|
||||
finally:
|
||||
stderr = _close_process(proc)
|
||||
if not info:
|
||||
detail = f" ({stderr})" if stderr else ""
|
||||
raise ValueError(f"archive sans .PKGINFO : ce n'est pas un paquet makepkg{detail}")
|
||||
return info, _with_parent_dirs(entries)
|
||||
|
||||
|
||||
def checksums(path: str) -> tuple[str, str]:
|
||||
md5 = hashlib.md5()
|
||||
sha256 = hashlib.sha256()
|
||||
with open(path, "rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
md5.update(chunk)
|
||||
sha256.update(chunk)
|
||||
return md5.hexdigest(), sha256.hexdigest()
|
||||
|
||||
|
||||
def _first(info: dict[str, list[str]], key: str) -> str:
|
||||
values = info.get(key)
|
||||
return values[0] if values else ""
|
||||
|
||||
|
||||
def _int_or_zero(value: str) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def read_package_metadata(path: str, filename: str | None = None) -> dict:
|
||||
"""Métadonnées complètes d'un paquet, au format attendu par build_databases."""
|
||||
filename = filename or os.path.basename(path)
|
||||
stat = os.stat(path)
|
||||
info, files = _read_archive(path)
|
||||
|
||||
name = _first(info, "pkgname")
|
||||
version = _first(info, "pkgver")
|
||||
if not name or not version:
|
||||
raise ValueError(f"{filename} : .PKGINFO incomplet (pkgname/pkgver manquant)")
|
||||
|
||||
arch = _first(info, "arch") or "any"
|
||||
warnings = []
|
||||
expected = f"{name}-{version}-{arch}"
|
||||
if not filename.startswith(expected):
|
||||
warnings.append(
|
||||
f"le nom du fichier ne commence pas par « {expected} » "
|
||||
"(le paquet reste utilisable, mais pacman se fie au nom de fichier)"
|
||||
)
|
||||
|
||||
md5sum, sha256sum = checksums(path)
|
||||
return {
|
||||
"name": name,
|
||||
"base": _first(info, "pkgbase") or name,
|
||||
"version": version,
|
||||
"desc": _first(info, "pkgdesc"),
|
||||
"url": _first(info, "url"),
|
||||
"arch": arch,
|
||||
"builddate": _int_or_zero(_first(info, "builddate")),
|
||||
"packager": _first(info, "packager"),
|
||||
"isize": _int_or_zero(_first(info, "size")),
|
||||
"licenses": info.get("license", []),
|
||||
"groups": info.get("group", []),
|
||||
"depends": info.get("depend", []),
|
||||
"optdepends": info.get("optdepend", []),
|
||||
"makedepends": info.get("makedepend", []),
|
||||
"checkdepends": info.get("checkdepend", []),
|
||||
"provides": info.get("provides", []),
|
||||
"conflicts": info.get("conflicts", []),
|
||||
"replaces": info.get("replaces", []),
|
||||
"filename": filename,
|
||||
"csize": stat.st_size,
|
||||
"md5sum": md5sum,
|
||||
"sha256sum": sha256sum,
|
||||
"mtime": int(stat.st_mtime),
|
||||
"cache_key": f"{stat.st_mtime_ns}:{stat.st_size}",
|
||||
"files": files,
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
|
||||
def scan_packages(directory: str, cache: dict[str, dict] | None = None) -> dict[str, dict]:
|
||||
"""Scanne le dossier des paquets, en ne réanalysant que les fichiers modifiés."""
|
||||
cache = cache or {}
|
||||
found: dict[str, dict] = {}
|
||||
try:
|
||||
names = sorted(os.listdir(directory))
|
||||
except FileNotFoundError:
|
||||
return found
|
||||
for name in names:
|
||||
if not is_pkg_filename(name):
|
||||
continue
|
||||
path = os.path.join(directory, name)
|
||||
if os.path.islink(path) or not os.path.isfile(path):
|
||||
continue
|
||||
try:
|
||||
stat = os.stat(path)
|
||||
except OSError:
|
||||
continue
|
||||
key = f"{stat.st_mtime_ns}:{stat.st_size}"
|
||||
cached = cache.get(name)
|
||||
if cached and cached.get("cache_key") == key:
|
||||
found[name] = cached
|
||||
continue
|
||||
try:
|
||||
found[name] = read_package_metadata(path, name)
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"archrepo: paquet ignoré {name} : {exc}", flush=True)
|
||||
return found
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Comparaison de versions (algorithme vercmp de pacman, dérivé de rpmvercmp)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _split_evr(version: str) -> tuple[str, str, str]:
|
||||
epoch = "0"
|
||||
rest = version
|
||||
if ":" in rest:
|
||||
epoch, rest = rest.split(":", 1)
|
||||
if "-" in rest:
|
||||
ver, rel = rest.rsplit("-", 1)
|
||||
else:
|
||||
ver, rel = rest, ""
|
||||
return epoch, ver, rel
|
||||
|
||||
|
||||
def _rpmvercmp(left: str, right: str) -> int:
|
||||
if left == right:
|
||||
return 0
|
||||
i = j = 0
|
||||
len_left, len_right = len(left), len(right)
|
||||
while i < len_left and j < len_right:
|
||||
while i < len_left and not left[i].isalnum():
|
||||
i += 1
|
||||
while j < len_right and not right[j].isalnum():
|
||||
j += 1
|
||||
if i >= len_left or j >= len_right:
|
||||
break
|
||||
left_num = left[i].isdigit()
|
||||
right_num = right[j].isdigit()
|
||||
start_left, start_right = i, j
|
||||
while i < len_left and left[i].isalnum() and left[i].isdigit() == left_num:
|
||||
i += 1
|
||||
while j < len_right and right[j].isalnum() and right[j].isdigit() == right_num:
|
||||
j += 1
|
||||
segment_left, segment_right = left[start_left:i], right[start_right:j]
|
||||
if not segment_left:
|
||||
return -1
|
||||
if not segment_right:
|
||||
return 1
|
||||
if left_num != right_num:
|
||||
return 1 if left_num else -1
|
||||
if segment_left == segment_right:
|
||||
continue
|
||||
if left_num:
|
||||
segment_left = segment_left.lstrip("0") or "0"
|
||||
segment_right = segment_right.lstrip("0") or "0"
|
||||
if len(segment_left) != len(segment_right):
|
||||
return 1 if len(segment_left) > len(segment_right) else -1
|
||||
return 1 if segment_left > segment_right else -1
|
||||
if i >= len_left and j >= len_right:
|
||||
return 0
|
||||
return 1 if i < len_left else -1
|
||||
|
||||
|
||||
def vercmp(left: str, right: str) -> int:
|
||||
"""Compare deux versions pacman : <0, 0, >0."""
|
||||
epoch_left, ver_left, rel_left = _split_evr(left)
|
||||
epoch_right, ver_right, rel_right = _split_evr(right)
|
||||
result = _rpmvercmp(epoch_left, epoch_right)
|
||||
if result == 0:
|
||||
result = _rpmvercmp(ver_left, ver_right)
|
||||
if result == 0:
|
||||
result = _rpmvercmp(rel_left, rel_right)
|
||||
return result
|
||||
|
||||
|
||||
def latest_by_name(packages) -> list[dict]:
|
||||
"""Ne garde que la version la plus récente de chaque nom (comme repo-add)."""
|
||||
best: dict[str, dict] = {}
|
||||
for pkg in packages:
|
||||
current = best.get(pkg["name"])
|
||||
if current is None:
|
||||
best[pkg["name"]] = pkg
|
||||
continue
|
||||
result = vercmp(pkg["version"], current["version"])
|
||||
if result > 0:
|
||||
best[pkg["name"]] = pkg
|
||||
elif result == 0:
|
||||
# même version : préférer l'architecture spécifique à « any »
|
||||
if current["arch"] == "any" and pkg["arch"] != "any":
|
||||
best[pkg["name"]] = pkg
|
||||
elif pkg["arch"] == current["arch"] and pkg["mtime"] >= current["mtime"]:
|
||||
best[pkg["name"]] = pkg
|
||||
return list(best.values())
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Génération des bases
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _desc_text(pkg: dict) -> str:
|
||||
blocks = []
|
||||
for field, key in DESC_FIELDS:
|
||||
value = pkg.get(key)
|
||||
if value in (None, "", []):
|
||||
continue
|
||||
values = value if isinstance(value, list) else [str(value)]
|
||||
blocks.append("%" + field + "%\n" + "\n".join(values))
|
||||
return "\n\n".join(blocks) + "\n"
|
||||
|
||||
|
||||
def _files_text(pkg: dict) -> str:
|
||||
files = pkg.get("files") or []
|
||||
if not files:
|
||||
return "%FILES%\n"
|
||||
return "%FILES%\n" + "\n".join(files) + "\n"
|
||||
|
||||
|
||||
def _add_entry(archive: tarfile.TarFile, name: str, data: str | None) -> None:
|
||||
info = tarfile.TarInfo(name)
|
||||
info.mtime = int(time.time())
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = "root"
|
||||
if data is None:
|
||||
info.type = tarfile.DIRTYPE
|
||||
info.mode = 0o755
|
||||
archive.addfile(info)
|
||||
else:
|
||||
raw = data.encode("utf-8")
|
||||
info.mode = 0o644
|
||||
info.size = len(raw)
|
||||
archive.addfile(info, io.BytesIO(raw))
|
||||
|
||||
|
||||
def _point_link(link_path: str, target: str) -> None:
|
||||
tmp = link_path + ".new"
|
||||
if os.path.lexists(tmp):
|
||||
os.unlink(tmp)
|
||||
os.symlink(target, tmp)
|
||||
os.replace(tmp, link_path)
|
||||
|
||||
|
||||
def build_databases(directory: str, repo_name: str, packages) -> dict:
|
||||
"""(Re)génère <repo>.db.tar.gz, <repo>.files.tar.gz et leurs liens symboliques."""
|
||||
packages = sorted(packages, key=lambda pkg: pkg["name"])
|
||||
built = int(time.time())
|
||||
stats = {"count": len(packages), "db_size": 0, "files_size": 0, "built": built}
|
||||
for kind in ("db", "files"):
|
||||
filename = f"{repo_name}.{kind}.tar.gz"
|
||||
target = os.path.join(directory, filename)
|
||||
tmp = target + ".new"
|
||||
with tarfile.open(tmp, "w:gz", format=tarfile.GNU_FORMAT) as archive:
|
||||
for pkg in packages:
|
||||
entry = f"{pkg['name']}-{pkg['version']}"
|
||||
_add_entry(archive, entry + "/", None)
|
||||
_add_entry(archive, entry + "/desc", _desc_text(pkg))
|
||||
if kind == "files":
|
||||
_add_entry(archive, entry + "/files", _files_text(pkg))
|
||||
os.replace(tmp, target)
|
||||
_point_link(os.path.join(directory, f"{repo_name}.{kind}"), filename)
|
||||
stats["db_size" if kind == "db" else "files_size"] = os.path.getsize(target)
|
||||
return stats
|
||||
Reference in new issue
Block a user