feat: add system packaging (.rpm, .deb, .tar.gz) and Gitea Actions CI/CD release workflow
This commit is contained in:
1 parent
e5784db650
commit
a03d9a85e6
10 files changed
+834
No files matched your search
@@ -0,0 +1,155 @@
|
||||
name: Build and Publish Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Build Packages and Publish
|
||||
runs-on: fedora
|
||||
steps:
|
||||
- name: Checkout Source Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Verify Build Environment
|
||||
run: |
|
||||
echo "=== Runner System Info ==="
|
||||
uname -a
|
||||
python3 --version
|
||||
if ! command -v rpmbuild &>/dev/null; then
|
||||
echo "Installing rpm-build..."
|
||||
sudo dnf install -y rpm-build
|
||||
else
|
||||
echo "rpmbuild is already available: $(which rpmbuild)"
|
||||
fi
|
||||
|
||||
- name: Run Test Suite
|
||||
run: |
|
||||
echo "=== Running Unit Tests ==="
|
||||
python3 -m unittest discover tests
|
||||
|
||||
- name: Build Distribution Packages
|
||||
run: |
|
||||
echo "=== Building Packages (.rpm, .deb, .tar.gz) ==="
|
||||
python3 packaging/build_packages.py
|
||||
echo "=== Built Artifacts in dist/ ==="
|
||||
ls -lh dist/*.tar.gz dist/*.deb 2>/dev/null || true
|
||||
ls -lh dist/*.rpm 2>/dev/null || true
|
||||
ls -lh dist/rpm/RPMS/*/*.rpm 2>/dev/null || true
|
||||
|
||||
- name: Publish to Gitea Package Registry
|
||||
env:
|
||||
PKG_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
echo "=== Publishing to Gitea Package Registry ==="
|
||||
RPM_FILE=$(find dist -maxdepth 2 -name "*.rpm" 2>/dev/null | head -n 1)
|
||||
DEB_FILE=$(ls dist/*.deb 2>/dev/null | head -n 1)
|
||||
|
||||
if [ -n "$RPM_FILE" ] && [ -f "$RPM_FILE" ]; then
|
||||
echo "Uploading RPM: $RPM_FILE"
|
||||
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
|
||||
-u "${{ github.actor }}:${PKG_TOKEN}" \
|
||||
--upload-file "$RPM_FILE" \
|
||||
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/rpm/upload")
|
||||
echo "RPM Registry HTTP status: $HTTP_CODE"
|
||||
fi
|
||||
|
||||
if [ -n "$DEB_FILE" ] && [ -f "$DEB_FILE" ]; then
|
||||
echo "Uploading DEB: $DEB_FILE"
|
||||
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
|
||||
-u "${{ github.actor }}:${PKG_TOKEN}" \
|
||||
--upload-file "$DEB_FILE" \
|
||||
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/debian/pool/stable/main/upload")
|
||||
echo "Debian Registry HTTP status: $HTTP_CODE"
|
||||
fi
|
||||
|
||||
# Link packages to this repository in Gitea
|
||||
REPO_NAME=$(basename "${{ github.repository }}")
|
||||
echo "Linking RPM package 'inventory-collector' to repository ${REPO_NAME}..."
|
||||
LINK_RPM=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
|
||||
-H "Authorization: token ${PKG_TOKEN}" \
|
||||
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/rpm/inventory-collector/-/link/${REPO_NAME}")
|
||||
echo "RPM link result: $LINK_RPM"
|
||||
|
||||
echo "Linking Debian package 'inventory-collector' to repository ${REPO_NAME}..."
|
||||
LINK_DEB=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
|
||||
-H "Authorization: token ${PKG_TOKEN}" \
|
||||
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/debian/inventory-collector/-/link/${REPO_NAME}")
|
||||
echo "Debian link result: $LINK_DEB"
|
||||
|
||||
- name: Attach Artifacts to Gitea Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
SERVER_URL: ${{ github.server_url }}
|
||||
REPO: ${{ github.repository }}
|
||||
TAG_REF: ${{ github.ref_name }}
|
||||
run: |
|
||||
echo "=== Attaching Assets to Release ==="
|
||||
# Determine tag name (default to package version if workflow_dispatch on branch)
|
||||
TAG="${TAG_REF}"
|
||||
if [[ "$TAG" == "main" || "$TAG" == "" ]]; then
|
||||
VER=$(python3 -c "import inventory_collector; print(inventory_collector.__version__)")
|
||||
TAG="v${VER}"
|
||||
fi
|
||||
echo "Target Release Tag: $TAG"
|
||||
|
||||
# 1. Fetch release ID or create release if missing
|
||||
REL_JSON=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
"${SERVER_URL}/api/v1/repos/${REPO}/releases/tags/${TAG}")
|
||||
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$REL_JSON" 2>/dev/null || true)
|
||||
|
||||
if [ -z "$REL_ID" ]; then
|
||||
echo "Release $TAG does not exist yet. Creating release..."
|
||||
CREATE_DATA=$(python3 -c "import sys, json; print(json.dumps({'tag_name': sys.argv[1], 'name': 'Release ' + sys.argv[1], 'body': 'Automated build and release for ' + sys.argv[1]}))" "$TAG")
|
||||
CREATE_RESP=$(curl -k -s -X POST \
|
||||
-H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$CREATE_DATA" \
|
||||
"${SERVER_URL}/api/v1/repos/${REPO}/releases")
|
||||
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$CREATE_RESP" 2>/dev/null || true)
|
||||
echo "Create release response: $CREATE_RESP"
|
||||
fi
|
||||
|
||||
echo "Release ID: $REL_ID"
|
||||
|
||||
if [ -n "$REL_ID" ]; then
|
||||
# Clean up any existing assets for this release (ensures idempotency on re-runs)
|
||||
EXISTING_ASSETS=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets" || true)
|
||||
ASSET_IDS=$(python3 -c "import sys, json; print(' '.join(str(a['id']) for a in json.loads(sys.argv[1])))" "$EXISTING_ASSETS" 2>/dev/null || true)
|
||||
for aid in $ASSET_IDS; do
|
||||
echo "Removing previous asset ID $aid..."
|
||||
curl -k -s -X DELETE -H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets/${aid}" || true
|
||||
done
|
||||
|
||||
# Target only user-facing binaries (exclude internal rpm SOURCES and SRPMS)
|
||||
ASSET_FILES=(
|
||||
$(ls dist/*.tar.gz 2>/dev/null || true)
|
||||
$(ls dist/*.deb 2>/dev/null || true)
|
||||
$(ls dist/*.rpm 2>/dev/null || true)
|
||||
$(ls dist/rpm/RPMS/*/*.rpm 2>/dev/null || true)
|
||||
)
|
||||
|
||||
# Deduplicate list
|
||||
declare -A SEEN
|
||||
for f in "${ASSET_FILES[@]}"; do
|
||||
if [ -f "$f" ]; then
|
||||
fname=$(basename "$f")
|
||||
if [[ -z "${SEEN[$fname]:-}" ]]; then
|
||||
SEEN[$fname]=1
|
||||
echo "Uploading asset $fname from $f..."
|
||||
curl -k -s -X POST \
|
||||
-H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
-F "attachment=@${f}" \
|
||||
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets?name=${fname}" || echo "Asset upload note: $?"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
echo "Artifacts successfully attached to release $TAG!"
|
||||
else
|
||||
echo "Could not obtain release ID, skipping asset attachment."
|
||||
fi
|
||||
@@ -24,6 +24,25 @@ Universal homelab and fleet inventory collector and deduplicator for **Ansible**
|
||||
|
||||
## Installation
|
||||
|
||||
### From Gitea Package Registry (RPM / Fedora / Alma / Rocky)
|
||||
```bash
|
||||
# Add Wired LAB Gitea repository (/etc/yum.repos.d/gitea-wired.repo)
|
||||
sudo dnf install -y inventory-collector
|
||||
```
|
||||
|
||||
### From Debian / Ubuntu (.deb)
|
||||
```bash
|
||||
sudo dpkg -i inventory-collector_1.0.0_all.deb
|
||||
```
|
||||
|
||||
### Standalone Tarball Installer
|
||||
```bash
|
||||
tar -xzf inventory-collector-1.0.0.tar.gz
|
||||
cd inventory-collector-1.0.0
|
||||
sudo ./install.sh
|
||||
```
|
||||
|
||||
### From Source Checkout
|
||||
```bash
|
||||
git clone https://gitea.wired.synology.me/soda64/inventory-collector.git
|
||||
cd inventory-collector
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# inventory-collector configuration file example
|
||||
# Can be placed at:
|
||||
# - ./inventory-collector.yaml
|
||||
# - ~/.config/inventory-collector/config.yaml
|
||||
# - /etc/inventory-collector/config.yaml
|
||||
|
||||
sources:
|
||||
proxmox:
|
||||
enabled: true
|
||||
url: "${PROXMOX_URL}"
|
||||
token_id: "${PROXMOX_TOKEN_ID}"
|
||||
token_secret: "${PROXMOX_TOKEN_SECRET}"
|
||||
verify_ssl: false
|
||||
timeout: 10
|
||||
static_files:
|
||||
- path: "~/.config/inventory-collector/static_hosts.ini"
|
||||
required: false
|
||||
|
||||
defaults:
|
||||
ssh_user: "lain"
|
||||
ssh_port: 22
|
||||
conflict_policy: "runtime_over_static"
|
||||
|
||||
destinations:
|
||||
ansible: "inventory/hosts.yaml"
|
||||
linux_connector: "~/.config/linux-connector/hosts.yaml"
|
||||
@@ -12,6 +12,7 @@
|
||||
- [x] Slice 4 — In-memory deduplication and conflict resolution engine with stderr warnings
|
||||
- [x] Slice 5 — Extended exporters (linux-connector, Generic YAML, XML) and --sync flag
|
||||
- [x] Slice 6 — Configuration file (config.yaml), CLI check mode (--check), and documentation
|
||||
- [x] Slice 7 — Packaging (.tar.gz, .deb, .rpm) and Gitea Actions CI/CD pipeline
|
||||
|
||||
## Notes for a fresh session
|
||||
- Project: Universal homelab and fleet inventory collector and deduplicator.
|
||||
|
||||
@@ -73,3 +73,16 @@ The implementation is broken down into 6 thin, verifiable vertical slices. Each
|
||||
- **Test / Verification:**
|
||||
- `tests/test_cli.py` testing `--check` output format and config file loading.
|
||||
- End-to-end regression test suite passing 100% of unit tests.
|
||||
|
||||
---
|
||||
|
||||
## Slice 7: Packaging (.tar.gz, .deb, .rpm) & Gitea Actions CI/CD
|
||||
- **Scope:**
|
||||
- Create `packaging/install.sh` for standalone installation to standard system directories (`/usr/bin`, `/usr/lib/inventory-collector`, `/usr/share/man/man1`, shell completions).
|
||||
- Create `packaging/inventory-collector.spec` and `packaging/build_packages.py` to automate packaging into `.tar.gz`, `.deb`, and `.rpm`.
|
||||
- Create Gitea Actions workflow `.gitea/workflows/build-and-release.yml` targeting `runs-on: fedora`.
|
||||
- Workflow features: unit testing, package generation, Gitea Release asset uploads, and Gitea Package Registry publication (RPM & Debian) with repo linking.
|
||||
- **Test / Verification:**
|
||||
- Build packages inside `docker.io/library/fedora:40` container via Podman.
|
||||
- Test installation of `.rpm` and `.tar.gz` (`install.sh`) inside clean Podman container.
|
||||
- Verify executable, man page, completions, and version output.
|
||||
Executable
+346
@@ -0,0 +1,346 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inventory Collector Package Builder.
|
||||
|
||||
Generates:
|
||||
1. .tar.gz standalone portable distribution with installer
|
||||
2. .deb package for Debian/Ubuntu (pure Python ar/tar packaging or dpkg-deb)
|
||||
3. .rpm build tree and package for RHEL/Fedora/CentOS/Rocky
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
|
||||
def get_version(source_root: Path) -> str:
|
||||
"""Extract __version__ dynamically from inventory_collector/__init__.py."""
|
||||
init_path = source_root / "inventory_collector" / "__init__.py"
|
||||
if init_path.exists():
|
||||
for line in init_path.read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith("__version__"):
|
||||
parts = line.split("=")
|
||||
if len(parts) >= 2:
|
||||
return parts[1].strip().strip('"').strip("'")
|
||||
return "1.0.0"
|
||||
|
||||
|
||||
def write_ar_header(name: str, size: int, mtime: int = 0) -> bytes:
|
||||
"""Creates a standard 60-byte Unix 'ar' file header."""
|
||||
file_id = f"{name:<16}".encode("ascii")[:16]
|
||||
file_mtime = f"{mtime:<12}".encode("ascii")[:12]
|
||||
owner_id = b"0 "[:6]
|
||||
group_id = b"0 "[:6]
|
||||
file_mode = b"100644 "[:8]
|
||||
file_size = f"{size:<10}".encode("ascii")[:10]
|
||||
trailer = b"`\n"
|
||||
return file_id + file_mtime + owner_id + group_id + file_mode + file_size + trailer
|
||||
|
||||
|
||||
def create_native_deb(control_tar_gz: Path, data_tar_gz: Path, output_deb_path: Path) -> Path:
|
||||
"""Builds a binary-compatible Debian .deb package using pure Python standard library."""
|
||||
debian_binary = b"2.0\n"
|
||||
now = int(time.time())
|
||||
|
||||
with open(str(output_deb_path), "wb") as deb:
|
||||
# 1. Global ar magic identifier
|
||||
deb.write(b"!<arch>\n")
|
||||
|
||||
# 2. debian-binary member
|
||||
deb.write(write_ar_header("debian-binary", len(debian_binary), now))
|
||||
deb.write(debian_binary)
|
||||
if len(debian_binary) % 2 != 0:
|
||||
deb.write(b"\n")
|
||||
|
||||
# 3. control.tar.gz member
|
||||
ctrl_bytes = control_tar_gz.read_bytes()
|
||||
deb.write(write_ar_header("control.tar.gz", len(ctrl_bytes), now))
|
||||
deb.write(ctrl_bytes)
|
||||
if len(ctrl_bytes) % 2 != 0:
|
||||
deb.write(b"\n")
|
||||
|
||||
# 4. data.tar.gz member
|
||||
data_bytes = data_tar_gz.read_bytes()
|
||||
deb.write(write_ar_header("data.tar.gz", len(data_bytes), now))
|
||||
deb.write(data_bytes)
|
||||
if len(data_bytes) % 2 != 0:
|
||||
deb.write(b"\n")
|
||||
|
||||
return output_deb_path
|
||||
|
||||
|
||||
class PackageBuilder:
|
||||
def __init__(
|
||||
self,
|
||||
source_root: Optional[Path] = None,
|
||||
output_dir: Optional[Path] = None,
|
||||
version: Optional[str] = None,
|
||||
) -> None:
|
||||
self.source_root = source_root or Path(__file__).resolve().parent.parent
|
||||
self.output_dir = output_dir or (self.source_root / "dist")
|
||||
self.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.version = version or get_version(self.source_root)
|
||||
|
||||
def build_tarball(self) -> Path:
|
||||
"""Builds a standalone inventory-collector-<version>.tar.gz with installer."""
|
||||
tar_name = f"inventory-collector-{self.version}.tar.gz"
|
||||
out_path = self.output_dir / tar_name
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp_str:
|
||||
tmp_root = Path(tmp_str) / f"inventory-collector-{self.version}"
|
||||
tmp_root.mkdir(parents=True)
|
||||
|
||||
# Copy package modules
|
||||
shutil.copytree(str(self.source_root / "inventory_collector"), str(tmp_root / "inventory_collector"))
|
||||
|
||||
# Copy launcher script
|
||||
bin_dir = tmp_root / "bin"
|
||||
bin_dir.mkdir()
|
||||
shutil.copy2(str(self.source_root / "bin" / "inventory-collector"), str(bin_dir / "inventory-collector"))
|
||||
os.chmod(str(bin_dir / "inventory-collector"), 0o755)
|
||||
|
||||
# Copy installer
|
||||
shutil.copy2(str(self.source_root / "packaging" / "install.sh"), str(tmp_root / "install.sh"))
|
||||
os.chmod(str(tmp_root / "install.sh"), 0o755)
|
||||
|
||||
# Copy packaging directory
|
||||
shutil.copytree(str(self.source_root / "packaging"), str(tmp_root / "packaging"))
|
||||
|
||||
# Copy example config
|
||||
if (self.source_root / "config.yaml.example").exists():
|
||||
shutil.copy2(
|
||||
str(self.source_root / "config.yaml.example"),
|
||||
str(tmp_root / "config.yaml.example"),
|
||||
)
|
||||
|
||||
# Copy documentation
|
||||
if (self.source_root / "README.md").exists():
|
||||
shutil.copy2(str(self.source_root / "README.md"), str(tmp_root / "README.md"))
|
||||
if (self.source_root / "requirements.txt").exists():
|
||||
shutil.copy2(str(self.source_root / "requirements.txt"), str(tmp_root / "requirements.txt"))
|
||||
if (self.source_root / "docs").exists():
|
||||
shutil.copytree(str(self.source_root / "docs"), str(tmp_root / "docs"))
|
||||
|
||||
# Copy man page
|
||||
if (self.source_root / "man").exists():
|
||||
shutil.copytree(str(self.source_root / "man"), str(tmp_root / "man"))
|
||||
|
||||
# Copy shell completions
|
||||
if (self.source_root / "completions").exists():
|
||||
shutil.copytree(str(self.source_root / "completions"), str(tmp_root / "completions"))
|
||||
|
||||
# Archive the tree
|
||||
with tarfile.open(str(out_path), "w:gz") as tar:
|
||||
tar.add(str(tmp_root), arcname=f"inventory-collector-{self.version}")
|
||||
|
||||
return out_path
|
||||
|
||||
def build_deb(self) -> Path:
|
||||
"""Builds Debian .deb package."""
|
||||
deb_filename = f"inventory-collector_{self.version}_all.deb"
|
||||
deb_output_path = self.output_dir / deb_filename
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp_str:
|
||||
root = Path(tmp_str)
|
||||
control_dir = root / "control"
|
||||
data_dir = root / "data"
|
||||
control_dir.mkdir()
|
||||
data_dir.mkdir()
|
||||
|
||||
# Render control file
|
||||
template_path = self.source_root / "packaging" / "deb" / "control.template"
|
||||
template_content = template_path.read_text(encoding="utf-8")
|
||||
rendered_control = template_content.format(version=self.version)
|
||||
(control_dir / "control").write_text(rendered_control, encoding="utf-8")
|
||||
|
||||
# Prepare data directory
|
||||
usr_bin = data_dir / "usr" / "bin"
|
||||
usr_lib = data_dir / "usr" / "lib" / "inventory-collector"
|
||||
etc_dir = data_dir / "etc" / "inventory-collector"
|
||||
usr_bin.mkdir(parents=True)
|
||||
usr_lib.mkdir(parents=True)
|
||||
etc_dir.mkdir(parents=True)
|
||||
|
||||
shutil.copy2(str(self.source_root / "bin" / "inventory-collector"), str(usr_bin / "inventory-collector"))
|
||||
os.chmod(str(usr_bin / "inventory-collector"), 0o755)
|
||||
shutil.copytree(str(self.source_root / "inventory_collector"), str(usr_lib / "inventory_collector"))
|
||||
|
||||
if (self.source_root / "config.yaml.example").exists():
|
||||
shutil.copy2(
|
||||
str(self.source_root / "config.yaml.example"),
|
||||
str(etc_dir / "config.yaml.example"),
|
||||
)
|
||||
|
||||
if (self.source_root / "man" / "inventory-collector.1").exists():
|
||||
man_dir = data_dir / "usr" / "share" / "man" / "man1"
|
||||
man_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(str(self.source_root / "man" / "inventory-collector.1"), str(man_dir / "inventory-collector.1"))
|
||||
|
||||
if (self.source_root / "completions" / "bash" / "inventory-collector").exists():
|
||||
bash_comp_dir = data_dir / "usr" / "share" / "bash-completion" / "completions"
|
||||
bash_comp_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(
|
||||
str(self.source_root / "completions" / "bash" / "inventory-collector"),
|
||||
str(bash_comp_dir / "inventory-collector"),
|
||||
)
|
||||
|
||||
if (self.source_root / "completions" / "zsh" / "_inventory-collector").exists():
|
||||
zsh_comp_dir = data_dir / "usr" / "share" / "zsh" / "site-functions"
|
||||
zsh_comp_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(
|
||||
str(self.source_root / "completions" / "zsh" / "_inventory-collector"),
|
||||
str(zsh_comp_dir / "_inventory-collector"),
|
||||
)
|
||||
|
||||
doc_dir = data_dir / "usr" / "share" / "doc" / "inventory-collector"
|
||||
doc_dir.mkdir(parents=True, exist_ok=True)
|
||||
if (self.source_root / "README.md").exists():
|
||||
shutil.copy2(str(self.source_root / "README.md"), str(doc_dir / "README.md"))
|
||||
if (self.source_root / "docs" / "user-guide.md").exists():
|
||||
shutil.copy2(str(self.source_root / "docs" / "user-guide.md"), str(doc_dir / "user-guide.md"))
|
||||
|
||||
# If dpkg-deb is available, use it; otherwise build native .deb
|
||||
if shutil.which("dpkg-deb"):
|
||||
pkg_tree = root / "deb_tree"
|
||||
shutil.copytree(str(data_dir), str(pkg_tree))
|
||||
debian_meta = pkg_tree / "DEBIAN"
|
||||
debian_meta.mkdir()
|
||||
shutil.copy2(str(control_dir / "control"), str(debian_meta / "control"))
|
||||
subprocess.run(["dpkg-deb", "-b", str(pkg_tree), str(deb_output_path)], check=True)
|
||||
else:
|
||||
# Pure Python build with strict GNU_FORMAT (dpkg rejects PAX 'x' headers)
|
||||
def reset_tarinfo(tarinfo):
|
||||
tarinfo.uid = 0
|
||||
tarinfo.gid = 0
|
||||
tarinfo.uname = "root"
|
||||
tarinfo.gname = "root"
|
||||
tarinfo.pax_headers = {}
|
||||
return tarinfo
|
||||
|
||||
ctrl_tar = root / "control.tar.gz"
|
||||
data_tar = root / "data.tar.gz"
|
||||
|
||||
with tarfile.open(str(ctrl_tar), "w:gz", format=tarfile.GNU_FORMAT) as tar:
|
||||
tar.add(str(control_dir / "control"), arcname="./control", filter=reset_tarinfo)
|
||||
|
||||
with tarfile.open(str(data_tar), "w:gz", format=tarfile.GNU_FORMAT) as tar:
|
||||
for item in sorted(data_dir.iterdir()):
|
||||
tar.add(str(item), arcname=f"./{item.name}", filter=reset_tarinfo)
|
||||
|
||||
create_native_deb(ctrl_tar, data_tar, deb_output_path)
|
||||
|
||||
return deb_output_path
|
||||
|
||||
def build_rpm(self) -> Path:
|
||||
"""Sets up RPM build tree and executes rpmbuild if available."""
|
||||
rpm_topdir = self.output_dir / "rpm"
|
||||
specs_dir = rpm_topdir / "SPECS"
|
||||
sources_dir = rpm_topdir / "SOURCES"
|
||||
rpms_dir = rpm_topdir / "RPMS"
|
||||
srpms_dir = rpm_topdir / "SRPMS"
|
||||
build_dir = rpm_topdir / "BUILD"
|
||||
|
||||
for d in (specs_dir, sources_dir, rpms_dir, srpms_dir, build_dir):
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Generate source tarball in SOURCES
|
||||
tarball_path = sources_dir / f"inventory-collector-{self.version}.tar.gz"
|
||||
with tempfile.TemporaryDirectory() as tmp_str:
|
||||
tmp_root = Path(tmp_str) / f"inventory-collector-{self.version}"
|
||||
tmp_root.mkdir(parents=True)
|
||||
shutil.copytree(str(self.source_root / "inventory_collector"), str(tmp_root / "inventory_collector"))
|
||||
bin_dir = tmp_root / "bin"
|
||||
bin_dir.mkdir()
|
||||
shutil.copy2(str(self.source_root / "bin" / "inventory-collector"), str(bin_dir / "inventory-collector"))
|
||||
os.chmod(str(bin_dir / "inventory-collector"), 0o755)
|
||||
|
||||
shutil.copytree(str(self.source_root / "packaging"), str(tmp_root / "packaging"))
|
||||
|
||||
if (self.source_root / "config.yaml.example").exists():
|
||||
shutil.copy2(
|
||||
str(self.source_root / "config.yaml.example"),
|
||||
str(tmp_root / "config.yaml.example"),
|
||||
)
|
||||
if (self.source_root / "man").exists():
|
||||
shutil.copytree(str(self.source_root / "man"), str(tmp_root / "man"))
|
||||
if (self.source_root / "completions").exists():
|
||||
shutil.copytree(str(self.source_root / "completions"), str(tmp_root / "completions"))
|
||||
if (self.source_root / "README.md").exists():
|
||||
shutil.copy2(str(self.source_root / "README.md"), str(tmp_root / "README.md"))
|
||||
if (self.source_root / "docs").exists():
|
||||
shutil.copytree(str(self.source_root / "docs"), str(tmp_root / "docs"))
|
||||
|
||||
with tarfile.open(str(tarball_path), "w:gz") as tar:
|
||||
tar.add(str(tmp_root), arcname=f"inventory-collector-{self.version}")
|
||||
|
||||
# 2. Copy spec file
|
||||
spec_source = self.source_root / "packaging" / "rpm" / "inventory-collector.spec"
|
||||
target_spec = specs_dir / "inventory-collector.spec"
|
||||
shutil.copy2(str(spec_source), str(target_spec))
|
||||
|
||||
# 3. If rpmbuild is available, build the RPM
|
||||
if shutil.which("rpmbuild"):
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
"rpmbuild",
|
||||
"-ba",
|
||||
"--define",
|
||||
f"_topdir {rpm_topdir}",
|
||||
str(target_spec),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
# Find created .rpm and copy to dist/
|
||||
rpms = list(rpms_dir.glob("**/*.rpm"))
|
||||
if rpms:
|
||||
for rpm in rpms:
|
||||
shutil.copy2(str(rpm), str(self.output_dir / rpm.name))
|
||||
return rpms[0]
|
||||
except Exception as e:
|
||||
print(f"[WARN] rpmbuild encountered error: {e}")
|
||||
|
||||
return target_spec
|
||||
|
||||
def build_all(self) -> Dict[str, Path]:
|
||||
tar_p = self.build_tarball()
|
||||
deb_p = self.build_deb()
|
||||
rpm_p = self.build_rpm()
|
||||
return {
|
||||
"tarball": tar_p,
|
||||
"deb": deb_p,
|
||||
"rpm": rpm_p,
|
||||
}
|
||||
|
||||
|
||||
def sha256_file(filepath: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(filepath, "rb") as f:
|
||||
while chunk := f.read(65536):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
builder = PackageBuilder()
|
||||
print(f"Building inventory-collector v{builder.version} distribution packages...")
|
||||
results = builder.build_all()
|
||||
print("\n=== Package Build Results ===")
|
||||
for name, path in results.items():
|
||||
if path.exists() and path.is_file():
|
||||
size = path.stat().st_size
|
||||
digest = sha256_file(path)
|
||||
print(f"[{name.upper():<7}] {path.name:<45} ({size:>7} bytes) SHA256: {digest[:16]}...")
|
||||
else:
|
||||
print(f"[{name.upper():<7}] {path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,12 @@
|
||||
Package: inventory-collector
|
||||
Version: {version}
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Architecture: all
|
||||
Depends: python3 (>= 3.8)
|
||||
Recommends: python3-yaml
|
||||
Maintainer: Mateusz Stomski <zbytatencyjny@gmail.com>
|
||||
Description: Universal homelab and fleet inventory collector and deduplicator
|
||||
Gathers host definitions from Proxmox VE REST API and static YAML/INI files,
|
||||
normalizes and deduplicates host records in memory with group and tag set unions,
|
||||
and generates unified inventory files for Ansible and linux-connector.
|
||||
Executable
+125
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# inventory-collector installation script
|
||||
# Installs inventory-collector to standard system directories.
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
PREFIX="${PREFIX:-/usr}"
|
||||
DESTDIR="${DESTDIR:-}"
|
||||
|
||||
BIN_DIR="${DESTDIR}${PREFIX}/bin"
|
||||
LIB_DIR="${DESTDIR}${PREFIX}/lib/inventory-collector"
|
||||
ETC_DIR="${DESTDIR}/etc/inventory-collector"
|
||||
MAN_DIR="${DESTDIR}${PREFIX}/share/man/man1"
|
||||
BASH_COMP_DIR="${DESTDIR}${PREFIX}/share/bash-completion/completions"
|
||||
ZSH_COMP_DIR="${DESTDIR}${PREFIX}/share/zsh/site-functions"
|
||||
DOC_DIR="${DESTDIR}${PREFIX}/share/doc/inventory-collector"
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") [OPTIONS]
|
||||
|
||||
Options:
|
||||
--prefix <path> Installation prefix (default: /usr)
|
||||
--destdir <path> Staging root for packaging (default: empty)
|
||||
--uninstall Remove installed files
|
||||
-h, --help Show this help message
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
uninstall() {
|
||||
echo "==> Uninstalling inventory-collector from ${PREFIX}..."
|
||||
rm -f "${BIN_DIR}/inventory-collector"
|
||||
rm -rf "${LIB_DIR}"
|
||||
rm -f "${ETC_DIR}/config.yaml.example"
|
||||
rmdir "${ETC_DIR}" 2>/dev/null || true
|
||||
rm -f "${MAN_DIR}/inventory-collector.1"
|
||||
rm -f "${BASH_COMP_DIR}/inventory-collector"
|
||||
rm -f "${ZSH_COMP_DIR}/_inventory-collector"
|
||||
rm -rf "${DOC_DIR}"
|
||||
echo "==> Uninstallation complete."
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--prefix)
|
||||
PREFIX="$2"
|
||||
shift 2
|
||||
;;
|
||||
--destdir)
|
||||
DESTDIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
--uninstall)
|
||||
uninstall
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
echo "Unknown option: $1" >&2
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Recalculate target paths after arg parsing
|
||||
BIN_DIR="${DESTDIR}${PREFIX}/bin"
|
||||
LIB_DIR="${DESTDIR}${PREFIX}/lib/inventory-collector"
|
||||
ETC_DIR="${DESTDIR}/etc/inventory-collector"
|
||||
MAN_DIR="${DESTDIR}${PREFIX}/share/man/man1"
|
||||
BASH_COMP_DIR="${DESTDIR}${PREFIX}/share/bash-completion/completions"
|
||||
ZSH_COMP_DIR="${DESTDIR}${PREFIX}/share/zsh/site-functions"
|
||||
DOC_DIR="${DESTDIR}${PREFIX}/share/doc/inventory-collector"
|
||||
|
||||
echo "==> Installing inventory-collector to ${PREFIX} (DESTDIR='${DESTDIR}')..."
|
||||
|
||||
# 1. Directories
|
||||
mkdir -p "${BIN_DIR}" "${LIB_DIR}" "${ETC_DIR}" "${MAN_DIR}" "${BASH_COMP_DIR}" "${ZSH_COMP_DIR}" "${DOC_DIR}"
|
||||
|
||||
# 2. Binary
|
||||
install -m 0755 "${ROOT_DIR}/bin/inventory-collector" "${BIN_DIR}/inventory-collector"
|
||||
|
||||
# 3. Python package
|
||||
cp -r "${ROOT_DIR}/inventory_collector" "${LIB_DIR}/"
|
||||
find "${LIB_DIR}" -type d -exec chmod 0755 {} +
|
||||
find "${LIB_DIR}" -type f -exec chmod 0644 {} +
|
||||
|
||||
# 4. Example configuration
|
||||
if [[ -f "${ROOT_DIR}/config.yaml.example" ]]; then
|
||||
install -m 0644 "${ROOT_DIR}/config.yaml.example" "${ETC_DIR}/config.yaml.example"
|
||||
fi
|
||||
|
||||
# 5. Man page
|
||||
if [[ -f "${ROOT_DIR}/man/inventory-collector.1" ]]; then
|
||||
install -m 0644 "${ROOT_DIR}/man/inventory-collector.1" "${MAN_DIR}/inventory-collector.1"
|
||||
fi
|
||||
|
||||
# 6. Shell completions
|
||||
if [[ -f "${ROOT_DIR}/completions/bash/inventory-collector" ]]; then
|
||||
install -m 0644 "${ROOT_DIR}/completions/bash/inventory-collector" "${BASH_COMP_DIR}/inventory-collector"
|
||||
fi
|
||||
if [[ -f "${ROOT_DIR}/completions/zsh/_inventory-collector" ]]; then
|
||||
install -m 0644 "${ROOT_DIR}/completions/zsh/_inventory-collector" "${ZSH_COMP_DIR}/_inventory-collector"
|
||||
fi
|
||||
|
||||
# 7. Documentation
|
||||
if [[ -f "${ROOT_DIR}/README.md" ]]; then
|
||||
install -m 0644 "${ROOT_DIR}/README.md" "${DOC_DIR}/README.md"
|
||||
fi
|
||||
if [[ -f "${ROOT_DIR}/docs/user-guide.md" ]]; then
|
||||
install -m 0644 "${ROOT_DIR}/docs/user-guide.md" "${DOC_DIR}/user-guide.md"
|
||||
fi
|
||||
|
||||
echo "==> Successfully installed inventory-collector."
|
||||
echo " Binary: ${BIN_DIR}/inventory-collector"
|
||||
echo " Library: ${LIB_DIR}"
|
||||
echo " Config Ex.: ${ETC_DIR}/config.yaml.example"
|
||||
echo " Man Page: ${MAN_DIR}/inventory-collector.1"
|
||||
echo " Completions: ${BASH_COMP_DIR}, ${ZSH_COMP_DIR}"
|
||||
@@ -0,0 +1,70 @@
|
||||
Name: inventory-collector
|
||||
Version: 1.0.0
|
||||
Release: 1%{?dist}
|
||||
Summary: Universal homelab and fleet inventory collector and deduplicator
|
||||
|
||||
License: MIT
|
||||
URL: https://gitea.wired.synology.me/soda64/inventory-collector
|
||||
Source0: inventory-collector-%{version}.tar.gz
|
||||
|
||||
BuildArch: noarch
|
||||
Requires: python3 >= 3.8
|
||||
Recommends: python3-pyyaml
|
||||
|
||||
%description
|
||||
Universal homelab and fleet inventory collector and deduplicator for Ansible
|
||||
and linux-connector. Gathers host definitions from Proxmox VE REST API and
|
||||
static YAML/INI files, normalizes and deduplicates host records in memory with
|
||||
group and tag set unions, and generates unified inventory files.
|
||||
|
||||
%prep
|
||||
%setup -q
|
||||
|
||||
%build
|
||||
# Pure Python package, no compilation required
|
||||
|
||||
%install
|
||||
rm -rf %{buildroot}
|
||||
mkdir -p %{buildroot}%{_bindir}
|
||||
mkdir -p %{buildroot}%{_prefix}/lib/inventory-collector
|
||||
mkdir -p %{buildroot}%{_sysconfdir}/inventory-collector
|
||||
mkdir -p %{buildroot}%{_mandir}/man1
|
||||
mkdir -p %{buildroot}%{_datadir}/bash-completion/completions
|
||||
mkdir -p %{buildroot}%{_datadir}/zsh/site-functions
|
||||
mkdir -p %{buildroot}%{_datadir}/doc/inventory-collector
|
||||
|
||||
cp -r inventory_collector %{buildroot}%{_prefix}/lib/inventory-collector/
|
||||
install -m 755 bin/inventory-collector %{buildroot}%{_bindir}/inventory-collector
|
||||
if [ -f config.yaml.example ]; then
|
||||
install -m 644 config.yaml.example %{buildroot}%{_sysconfdir}/inventory-collector/config.yaml.example
|
||||
fi
|
||||
if [ -f man/inventory-collector.1 ]; then
|
||||
install -m 644 man/inventory-collector.1 %{buildroot}%{_mandir}/man1/inventory-collector.1
|
||||
fi
|
||||
if [ -f completions/bash/inventory-collector ]; then
|
||||
install -m 644 completions/bash/inventory-collector %{buildroot}%{_datadir}/bash-completion/completions/inventory-collector
|
||||
fi
|
||||
if [ -f completions/zsh/_inventory-collector ]; then
|
||||
install -m 644 completions/zsh/_inventory-collector %{buildroot}%{_datadir}/zsh/site-functions/_inventory-collector
|
||||
fi
|
||||
if [ -f README.md ]; then
|
||||
install -m 644 README.md %{buildroot}%{_datadir}/doc/inventory-collector/README.md
|
||||
fi
|
||||
if [ -f docs/user-guide.md ]; then
|
||||
install -m 644 docs/user-guide.md %{buildroot}%{_datadir}/doc/inventory-collector/user-guide.md
|
||||
fi
|
||||
|
||||
%files
|
||||
%defattr(-,root,root,-)
|
||||
%attr(0755, root, root) %{_bindir}/inventory-collector
|
||||
%{_prefix}/lib/inventory-collector
|
||||
%dir %{_sysconfdir}/inventory-collector
|
||||
%config(noreplace) %{_sysconfdir}/inventory-collector/config.yaml.example
|
||||
%{_mandir}/man1/inventory-collector.1*
|
||||
%{_datadir}/bash-completion/completions/inventory-collector
|
||||
%{_datadir}/zsh/site-functions/_inventory-collector
|
||||
%doc %{_datadir}/doc/inventory-collector
|
||||
|
||||
%changelog
|
||||
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.0.0-1
|
||||
- Initial release of inventory-collector.
|
||||
@@ -0,0 +1,67 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
|
||||
from packaging.build_packages import (
|
||||
PackageBuilder,
|
||||
get_version,
|
||||
write_ar_header,
|
||||
)
|
||||
|
||||
|
||||
class TestPackaging(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp_dir = tempfile.TemporaryDirectory()
|
||||
self.output_dir = Path(self.tmp_dir.name)
|
||||
self.source_root = Path(__file__).resolve().parent.parent
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp_dir.cleanup()
|
||||
|
||||
def test_write_ar_header(self):
|
||||
header = write_ar_header("debian-binary", 4, 123456789)
|
||||
self.assertEqual(len(header), 60)
|
||||
self.assertTrue(header.startswith(b"debian-binary "))
|
||||
self.assertTrue(header.endswith(b"`\n"))
|
||||
|
||||
def test_get_version(self):
|
||||
version = get_version(self.source_root)
|
||||
self.assertEqual(version, "1.0.0")
|
||||
|
||||
def test_build_tarball(self):
|
||||
builder = PackageBuilder(
|
||||
source_root=self.source_root,
|
||||
output_dir=self.output_dir,
|
||||
version="1.0.0",
|
||||
)
|
||||
tar_path = builder.build_tarball()
|
||||
self.assertTrue(tar_path.exists())
|
||||
self.assertTrue(tar_path.name.endswith(".tar.gz"))
|
||||
|
||||
# Verify tar contents
|
||||
with tarfile.open(str(tar_path), "r:gz") as tar:
|
||||
names = tar.getnames()
|
||||
self.assertIn("inventory-collector-1.0.0/bin/inventory-collector", names)
|
||||
self.assertIn("inventory-collector-1.0.0/inventory_collector/__init__.py", names)
|
||||
self.assertIn("inventory-collector-1.0.0/install.sh", names)
|
||||
self.assertIn("inventory-collector-1.0.0/packaging/install.sh", names)
|
||||
|
||||
def test_build_deb(self):
|
||||
builder = PackageBuilder(
|
||||
source_root=self.source_root,
|
||||
output_dir=self.output_dir,
|
||||
version="1.0.0",
|
||||
)
|
||||
deb_path = builder.build_deb()
|
||||
self.assertTrue(deb_path.exists())
|
||||
self.assertTrue(deb_path.name.endswith(".deb"))
|
||||
|
||||
# Check ar magic
|
||||
with open(deb_path, "rb") as f:
|
||||
magic = f.read(8)
|
||||
self.assertEqual(magic, b"!<arch>\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user