feat(packaging): implement slice 7 native packaging (.deb, .rpm, .tar.gz)
This commit is contained in:
1 parent
e7aa5a54a4
commit
c5c3b87bd9
5 files changed
+652
-1
No files matched your search
Executable
+428
@@ -0,0 +1,428 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Enterprise package builder for linux-backuper.
|
||||
|
||||
Builds:
|
||||
1. Pure Python Debian package (.deb) using standard ar / tar.gz formats.
|
||||
2. RPM package (.rpm) via spec generation and rpmbuild (when available).
|
||||
3. Universal binary distribution (.tar.gz) with standalone install.sh.
|
||||
|
||||
Zero mandatory external pip dependencies required.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
|
||||
|
||||
def get_version(repo_root: str) -> str:
|
||||
"""Extract version from linux_backuper/__init__.py."""
|
||||
init_path = os.path.join(repo_root, "linux_backuper", "__init__.py")
|
||||
with open(init_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
match = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', content)
|
||||
if not match:
|
||||
raise ValueError("Could not find __version__ in linux_backuper/__init__.py")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def create_ar_archive(target_path: str, members: list):
|
||||
"""Create a standard UNIX ar archive (Debian .deb package format).
|
||||
|
||||
members is a list of tuples: (name: str, content: bytes, mode: int)
|
||||
"""
|
||||
with open(target_path, "wb") as out:
|
||||
# 8-byte ar magic header
|
||||
out.write(b"!<arch>\n")
|
||||
|
||||
for name, data, mode in members:
|
||||
# Entry header format:
|
||||
# 0..15 (16) Name
|
||||
# 16..27 (12) Timestamp
|
||||
# 28..33 (6) Owner UID
|
||||
# 34..39 (6) Owner GID
|
||||
# 40..47 (8) File mode (octal)
|
||||
# 48..57 (10) File size (decimal)
|
||||
# 58..59 (2) Trailer `\x60\n`
|
||||
name_bytes = name.encode("ascii").ljust(16)
|
||||
timestamp_bytes = str(int(time.time())).encode("ascii").ljust(12)
|
||||
uid_bytes = b"0 "
|
||||
gid_bytes = b"0 "
|
||||
mode_bytes = f"{mode:o}".encode("ascii").ljust(8)
|
||||
size_bytes = str(len(data)).encode("ascii").ljust(10)
|
||||
trailer = b"`\n"
|
||||
|
||||
header = (
|
||||
name_bytes
|
||||
+ timestamp_bytes
|
||||
+ uid_bytes
|
||||
+ gid_bytes
|
||||
+ mode_bytes
|
||||
+ size_bytes
|
||||
+ trailer
|
||||
)
|
||||
if len(header) != 60:
|
||||
raise ValueError(f"Malformed ar header length: {len(header)}")
|
||||
|
||||
out.write(header)
|
||||
out.write(data)
|
||||
|
||||
# ar entries are padded with \n if size is odd
|
||||
if len(data) % 2 != 0:
|
||||
out.write(b"\n")
|
||||
|
||||
|
||||
def build_deb_package(repo_root: str, out_dir: str, version: str) -> str:
|
||||
"""Build a standard Debian .deb package in pure Python."""
|
||||
deb_filename = f"linux-backuper_{version}_all.deb"
|
||||
deb_path = os.path.join(out_dir, deb_filename)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
||||
# 1. debian-binary member
|
||||
debian_binary = b"2.0\n"
|
||||
|
||||
# 2. control.tar.gz member
|
||||
control_content = f"""Package: linux-backuper
|
||||
Version: {version}
|
||||
Section: admin
|
||||
Priority: optional
|
||||
Architecture: all
|
||||
Depends: python3 (>= 3.6)
|
||||
Recommends: rsync, openssh-client
|
||||
Maintainer: wiredLAB <lain@wired.intra>
|
||||
Description: Enterprise Linux system snapshot and configuration backup utility.
|
||||
linux-backuper creates reliable, verifiable, and restorable system configuration
|
||||
and state snapshots across Debian, Ubuntu, RHEL, AlmaLinux, Fedora, and Arch Linux.
|
||||
Features include zero mandatory external pip dependencies, fast metadata indexing,
|
||||
live system diffing, dry-run safety restore, time-bucket retention pruning, and
|
||||
local-first remote synchronization.
|
||||
"""
|
||||
|
||||
postinst_script = """#!/bin/sh
|
||||
set -e
|
||||
mkdir -p /var/backups/linux-backuper /etc/linux-backuper
|
||||
chmod 0700 /var/backups/linux-backuper
|
||||
exit 0
|
||||
"""
|
||||
|
||||
prerm_script = """#!/bin/sh
|
||||
set -e
|
||||
exit 0
|
||||
"""
|
||||
|
||||
control_buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=control_buf, mode="w:gz", format=tarfile.PAX_FORMAT) as tar:
|
||||
# ./
|
||||
ti = tarfile.TarInfo("./")
|
||||
ti.type = tarfile.DIRTYPE
|
||||
ti.mode = 0o755
|
||||
ti.mtime = int(time.time())
|
||||
tar.addfile(ti)
|
||||
|
||||
# ./control
|
||||
data = control_content.encode("utf-8")
|
||||
ti = tarfile.TarInfo("./control")
|
||||
ti.size = len(data)
|
||||
ti.mode = 0o644
|
||||
ti.mtime = int(time.time())
|
||||
tar.addfile(ti, io.BytesIO(data))
|
||||
|
||||
# ./postinst
|
||||
data = postinst_script.encode("utf-8")
|
||||
ti = tarfile.TarInfo("./postinst")
|
||||
ti.size = len(data)
|
||||
ti.mode = 0o755
|
||||
ti.mtime = int(time.time())
|
||||
tar.addfile(ti, io.BytesIO(data))
|
||||
|
||||
# ./prerm
|
||||
data = prerm_script.encode("utf-8")
|
||||
ti = tarfile.TarInfo("./prerm")
|
||||
ti.size = len(data)
|
||||
ti.mode = 0o755
|
||||
ti.mtime = int(time.time())
|
||||
tar.addfile(ti, io.BytesIO(data))
|
||||
|
||||
control_tar_gz = control_buf.getvalue()
|
||||
|
||||
# 3. data.tar.gz member
|
||||
data_buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=data_buf, mode="w:gz", format=tarfile.PAX_FORMAT) as tar:
|
||||
def add_dir(path: str, mode: int = 0o755):
|
||||
ti = tarfile.TarInfo(path)
|
||||
ti.type = tarfile.DIRTYPE
|
||||
ti.mode = mode
|
||||
ti.mtime = int(time.time())
|
||||
tar.addfile(ti)
|
||||
|
||||
# Base directories
|
||||
add_dir("./usr")
|
||||
add_dir("./usr/bin")
|
||||
add_dir("./usr/lib")
|
||||
add_dir("./usr/lib/linux-backuper")
|
||||
add_dir("./etc")
|
||||
add_dir("./etc/linux-backuper")
|
||||
add_dir("./var")
|
||||
add_dir("./var/backups")
|
||||
add_dir("./var/backups/linux-backuper", mode=0o700)
|
||||
|
||||
# Add executable /usr/bin/linux-backuper
|
||||
bin_src = os.path.join(repo_root, "bin", "linux-backuper")
|
||||
with open(bin_src, "rb") as f:
|
||||
bin_data = f.read()
|
||||
ti = tarfile.TarInfo("./usr/bin/linux-backuper")
|
||||
ti.size = len(bin_data)
|
||||
ti.mode = 0o755
|
||||
ti.mtime = int(time.time())
|
||||
tar.addfile(ti, io.BytesIO(bin_data))
|
||||
|
||||
# Add python library files to /usr/lib/linux-backuper/linux_backuper
|
||||
lib_src_root = os.path.join(repo_root, "linux_backuper")
|
||||
for root, dirs, files in os.walk(lib_src_root):
|
||||
dirs[:] = [d for d in dirs if d != "__pycache__" and not d.startswith("._")]
|
||||
rel_dir = os.path.relpath(root, repo_root)
|
||||
tar_dir = f"./usr/lib/linux-backuper/{rel_dir}".replace("\\", "/")
|
||||
add_dir(tar_dir)
|
||||
|
||||
for file in sorted(files):
|
||||
if file.startswith("._") or file.endswith(".pyc") or file == "__pycache__":
|
||||
continue
|
||||
file_src = os.path.join(root, file)
|
||||
tar_file = f"{tar_dir}/{file}"
|
||||
with open(file_src, "rb") as f:
|
||||
file_data = f.read()
|
||||
ti = tarfile.TarInfo(tar_file)
|
||||
ti.size = len(file_data)
|
||||
ti.mode = 0o644
|
||||
ti.mtime = int(time.time())
|
||||
tar.addfile(ti, io.BytesIO(file_data))
|
||||
|
||||
data_tar_gz = data_buf.getvalue()
|
||||
|
||||
# Package into ar archive
|
||||
members = [
|
||||
("debian-binary", debian_binary, 0o644),
|
||||
("control.tar.gz", control_tar_gz, 0o644),
|
||||
("data.tar.gz", data_tar_gz, 0o644),
|
||||
]
|
||||
create_ar_archive(deb_path, members)
|
||||
print(f"[SUCCESS] Built Debian package: {deb_path} ({os.path.getsize(deb_path)} bytes)")
|
||||
return deb_path
|
||||
|
||||
|
||||
def build_tar_package(repo_root: str, out_dir: str, version: str) -> str:
|
||||
"""Build universal binary tarball distribution."""
|
||||
tar_filename = f"linux-backuper-{version}.tar.gz"
|
||||
tar_path = os.path.join(out_dir, tar_filename)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
||||
prefix = f"linux-backuper-{version}"
|
||||
with tarfile.open(tar_path, "w:gz", format=tarfile.PAX_FORMAT) as tar:
|
||||
# Add root dir
|
||||
ti = tarfile.TarInfo(prefix)
|
||||
ti.type = tarfile.DIRTYPE
|
||||
ti.mode = 0o755
|
||||
tar.addfile(ti)
|
||||
|
||||
# Add install script
|
||||
install_src = os.path.join(repo_root, "packaging", "install.sh")
|
||||
if os.path.isfile(install_src):
|
||||
with open(install_src, "rb") as f:
|
||||
data = f.read()
|
||||
ti = tarfile.TarInfo(f"{prefix}/install.sh")
|
||||
ti.size = len(data)
|
||||
ti.mode = 0o755
|
||||
tar.addfile(ti, io.BytesIO(data))
|
||||
|
||||
# Add bin launcher
|
||||
bin_src = os.path.join(repo_root, "bin", "linux-backuper")
|
||||
with open(bin_src, "rb") as f:
|
||||
data = f.read()
|
||||
ti = tarfile.TarInfo(f"{prefix}/bin/linux-backuper")
|
||||
ti.size = len(data)
|
||||
ti.mode = 0o755
|
||||
tar.addfile(ti, io.BytesIO(data))
|
||||
|
||||
# Add README
|
||||
readme_src = os.path.join(repo_root, "README.md")
|
||||
if os.path.isfile(readme_src):
|
||||
with open(readme_src, "rb") as f:
|
||||
data = f.read()
|
||||
ti = tarfile.TarInfo(f"{prefix}/README.md")
|
||||
ti.size = len(data)
|
||||
ti.mode = 0o644
|
||||
tar.addfile(ti, io.BytesIO(data))
|
||||
|
||||
# Add python library
|
||||
lib_src_root = os.path.join(repo_root, "linux_backuper")
|
||||
for root, dirs, files in os.walk(lib_src_root):
|
||||
dirs[:] = [d for d in dirs if d != "__pycache__" and not d.startswith("._")]
|
||||
rel_dir = os.path.relpath(root, repo_root)
|
||||
tar_dir = f"{prefix}/{rel_dir}".replace("\\", "/")
|
||||
ti = tarfile.TarInfo(tar_dir)
|
||||
ti.type = tarfile.DIRTYPE
|
||||
ti.mode = 0o755
|
||||
tar.addfile(ti)
|
||||
|
||||
for file in sorted(files):
|
||||
if file.startswith("._") or file.endswith(".pyc") or file == "__pycache__":
|
||||
continue
|
||||
file_src = os.path.join(root, file)
|
||||
tar_file = f"{tar_dir}/{file}"
|
||||
with open(file_src, "rb") as f:
|
||||
data = f.read()
|
||||
ti = tarfile.TarInfo(tar_file)
|
||||
ti.size = len(data)
|
||||
ti.mode = 0o644
|
||||
tar.addfile(ti, io.BytesIO(data))
|
||||
|
||||
print(f"[SUCCESS] Built binary tarball: {tar_path} ({os.path.getsize(tar_path)} bytes)")
|
||||
return tar_path
|
||||
|
||||
|
||||
def generate_rpm_spec(repo_root: str, out_dir: str, version: str) -> str:
|
||||
"""Generate standard RPM .spec file for building .rpm packages."""
|
||||
spec_content = f"""Name: linux-backuper
|
||||
Version: {version}
|
||||
Release: 1%{{?dist}}
|
||||
Summary: Enterprise Linux system snapshot and configuration backup utility
|
||||
License: MIT
|
||||
URL: https://gitea.wired.synology.me/soda64/linux-backuper
|
||||
Source0: linux-backuper-%{{version}}.tar.gz
|
||||
BuildArch: noarch
|
||||
Requires: python3 >= 3.6
|
||||
Recommends: rsync, openssh-clients
|
||||
|
||||
%description
|
||||
linux-backuper is an enterprise-grade Linux system snapshot and configuration
|
||||
backup utility written in pure Python >= 3.6 with zero mandatory external pip
|
||||
dependencies. It features fast manifest indexing, live system diffing,
|
||||
safe restore with dry-run protection, time-bucket pruning, and local-first
|
||||
remote storage synchronization.
|
||||
|
||||
%prep
|
||||
%setup -q
|
||||
|
||||
%build
|
||||
# Pure python, no compile step needed
|
||||
|
||||
%install
|
||||
rm -rf %{{buildroot}}
|
||||
mkdir -p %{{buildroot}}/usr/bin
|
||||
mkdir -p %{{buildroot}}/usr/lib/linux-backuper/linux_backuper
|
||||
mkdir -p %{{buildroot}}/etc/linux-backuper
|
||||
mkdir -p %{{buildroot}}/var/backups/linux-backuper
|
||||
|
||||
cp -r bin/linux-backuper %{{buildroot}}/usr/bin/linux-backuper
|
||||
chmod 0755 %{{buildroot}}/usr/bin/linux-backuper
|
||||
|
||||
cp -r linux_backuper/* %{{buildroot}}/usr/lib/linux-backuper/linux_backuper/
|
||||
find %{{buildroot}}/usr/lib/linux-backuper -name "._*" -delete
|
||||
find %{{buildroot}}/usr/lib/linux-backuper -name "__pycache__" -type d -exec rm -rf {{}} + 2>/dev/null || true
|
||||
find %{{buildroot}}/usr/lib/linux-backuper -type d -exec chmod 0755 {{}} +
|
||||
find %{{buildroot}}/usr/lib/linux-backuper -type f -exec chmod 0644 {{}} +
|
||||
|
||||
%files
|
||||
%defattr(-,root,root,-)
|
||||
/usr/bin/linux-backuper
|
||||
/usr/lib/linux-backuper
|
||||
%dir /etc/linux-backuper
|
||||
%attr(0700,root,root) %dir /var/backups/linux-backuper
|
||||
|
||||
%changelog
|
||||
* Fri Oct 09 2026 wiredLAB <lain@wired.intra> - {version}-1
|
||||
- Initial release of linux-backuper.
|
||||
"""
|
||||
spec_path = os.path.join(out_dir, "linux-backuper.spec")
|
||||
with open(spec_path, "w", encoding="utf-8") as f:
|
||||
f.write(spec_content)
|
||||
print(f"[SUCCESS] Generated RPM spec: {spec_path}")
|
||||
return spec_path
|
||||
|
||||
|
||||
def build_rpm_package(repo_root: str, out_dir: str, version: str) -> str:
|
||||
"""Build RPM package using rpmbuild if available."""
|
||||
spec_path = generate_rpm_spec(repo_root, out_dir, version)
|
||||
|
||||
rpmbuild_bin = shutil.which("rpmbuild")
|
||||
if not rpmbuild_bin:
|
||||
print("[WARNING] 'rpmbuild' binary not found on this system. RPM spec was generated, but .rpm build skipped.")
|
||||
return spec_path
|
||||
|
||||
# Build source tarball required by rpmbuild
|
||||
tar_path = build_tar_package(repo_root, out_dir, version)
|
||||
|
||||
# Set up isolated rpmbuild directory structure inside out_dir/rpmbuild
|
||||
rpmbuild_dir = os.path.abspath(os.path.join(out_dir, "rpmbuild"))
|
||||
for d in ["BUILD", "RPMS", "SOURCES", "SPECS", "SRPMS"]:
|
||||
os.makedirs(os.path.join(rpmbuild_dir, d), exist_ok=True)
|
||||
|
||||
# Copy source tarball to SOURCES and spec to SPECS
|
||||
shutil.copy2(tar_path, os.path.join(rpmbuild_dir, "SOURCES"))
|
||||
rpm_spec_in_tree = os.path.join(rpmbuild_dir, "SPECS", "linux-backuper.spec")
|
||||
shutil.copy2(spec_path, rpm_spec_in_tree)
|
||||
|
||||
cmd = [
|
||||
rpmbuild_bin,
|
||||
"-bb",
|
||||
f"--define=_topdir {rpmbuild_dir}",
|
||||
rpm_spec_in_tree,
|
||||
]
|
||||
print(f"[INFO] Running rpmbuild: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"[ERROR] rpmbuild failed:\n{result.stderr}", file=sys.stderr)
|
||||
raise RuntimeError("rpmbuild execution failed")
|
||||
|
||||
# Locate generated rpm and copy to out_dir
|
||||
rpms_found = []
|
||||
for root, _, files in os.walk(os.path.join(rpmbuild_dir, "RPMS")):
|
||||
for f in files:
|
||||
if f.endswith(".rpm"):
|
||||
full_rpm = os.path.join(root, f)
|
||||
target_rpm = os.path.join(out_dir, f)
|
||||
shutil.copy2(full_rpm, target_rpm)
|
||||
rpms_found.append(target_rpm)
|
||||
|
||||
if not rpms_found:
|
||||
raise RuntimeError("rpmbuild succeeded but no .rpm file was found in RPMS")
|
||||
|
||||
print(f"[SUCCESS] Built RPM package: {rpms_found[0]} ({os.path.getsize(rpms_found[0])} bytes)")
|
||||
return rpms_found[0]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Package builder for linux-backuper")
|
||||
parser.add_argument("--deb", action="store_true", help="Build Debian .deb package")
|
||||
parser.add_argument("--rpm", action="store_true", help="Build RPM .rpm package / spec")
|
||||
parser.add_argument("--tar", action="store_true", help="Build universal .tar.gz package")
|
||||
parser.add_argument("--all", action="store_true", help="Build all package types (default)")
|
||||
parser.add_argument("--out-dir", default="dist", help="Output directory (default: dist)")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
version = get_version(repo_root)
|
||||
out_dir = os.path.abspath(args.out_dir)
|
||||
|
||||
build_all = args.all or (not args.deb and not args.rpm and not args.tar)
|
||||
|
||||
print(f"[INFO] Building packages for linux-backuper v{version} into {out_dir}")
|
||||
|
||||
if build_all or args.tar:
|
||||
build_tar_package(repo_root, out_dir, version)
|
||||
|
||||
if build_all or args.deb:
|
||||
build_deb_package(repo_root, out_dir, version)
|
||||
|
||||
if build_all or args.rpm:
|
||||
build_rpm_package(repo_root, out_dir, version)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user