Files
linux-updater/linux_updater/core/detector.py
T

87 lines
3.1 KiB
Python

from pathlib import Path
from typing import Dict, Optional
from linux_updater.models import DistroFamily, DistroInfo
class DistroDetector:
def __init__(self, os_release_path: Optional[Path] = None) -> None:
if os_release_path is not None:
self.os_release_path = os_release_path
else:
default_p = Path("/etc/os-release")
fallback_p = Path("/usr/lib/os-release")
self.os_release_path = default_p if default_p.exists() else fallback_p
def _parse_os_release(self) -> Dict[str, str]:
data: Dict[str, str] = {}
if not self.os_release_path.exists():
return data
try:
with open(str(self.os_release_path), "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, val = line.split("=", 1)
key = key.strip()
val = val.strip()
# Strip surrounding quotes if present
if len(val) >= 2 and (
(val.startswith('"') and val.endswith('"'))
or (val.startswith("'") and val.endswith("'"))
):
val = val[1:-1]
data[key] = val
except Exception:
return {}
return data
def detect(self) -> DistroInfo:
data = self._parse_os_release()
if not data:
return DistroInfo(
family=DistroFamily.UNKNOWN,
distro_id="unknown",
version_id="unknown",
pretty_name="Unknown Linux System",
)
distro_id = data.get("ID", "").lower().strip()
id_like = data.get("ID_LIKE", "").lower().strip().split()
version_id = data.get("VERSION_ID", data.get("BUILD_ID", "rolling")).strip()
pretty_name = data.get("PRETTY_NAME", data.get("NAME", distro_id)).strip()
family = self._resolve_family(distro_id, id_like)
return DistroInfo(
family=family,
distro_id=distro_id,
version_id=version_id,
pretty_name=pretty_name,
)
def _resolve_family(self, distro_id: str, id_like: list) -> DistroFamily:
debian_ids = {"debian", "ubuntu", "linuxmint", "pop", "elementary", "kali", "raspbian"}
rhel_ids = {"rhel", "fedora", "centos", "rocky", "almalinux", "ol", "amzn"}
arch_ids = {"arch", "manjaro", "endeavouros", "garuda", "artix"}
if distro_id in debian_ids:
return DistroFamily.DEBIAN
if distro_id in rhel_ids:
return DistroFamily.RHEL
if distro_id in arch_ids:
return DistroFamily.ARCH
# Check ID_LIKE
for like in id_like:
if like in debian_ids:
return DistroFamily.DEBIAN
if like in rhel_ids:
return DistroFamily.RHEL
if like in arch_ids:
return DistroFamily.ARCH
return DistroFamily.UNKNOWN