feat: implement slice 3 package managers (apt, dnf, pacman) and update workflows

This commit is contained in:
soda64 committed 2026-10-02 10:14:54 +02:00
1 parent 62ce7e63f8
commit dcb224150f
8 files changed
+779 -43

No files matched your search

+174 -41
View File
@@ -1,4 +1,5 @@
import argparse
import json
from pathlib import Path
import sys
from typing import List, Optional
@@ -6,7 +7,11 @@ from typing import List, Optional
from linux_updater import __version__
from linux_updater.config import UpdaterConfig
from linux_updater.core.detector import DistroDetector
from linux_updater.models import DistroFamily
from linux_updater.core.health import HealthChecker
from linux_updater.core.remediation import RemediationEngine
from linux_updater.core.runner import CommandRunner
from linux_updater.managers import get_manager
from linux_updater.models import CheckStatus, DistroFamily
def create_parser() -> argparse.ArgumentParser:
@@ -118,6 +123,30 @@ def create_parser() -> argparse.ArgumentParser:
return parser
def format_health_report(report) -> None:
print("\nPre-flight Health Diagnostics:")
print("-" * 65)
for res in report.results:
status_symbol = "[ PASS ]" if res.status.value == "PASS" else (
"[ WARN ]" if res.status.value == "WARN" else "[ FAIL ]"
)
print(f"{status_symbol} {res.name:<22} {res.message}")
print("-" * 65)
status_text = "PASSED" if report.passed else "FAILED"
print(f"Overall Pre-flight Status: {status_text}\n")
def prompt_confirmation(prompt: str = "Do you want to proceed with updates? [Y/n]: ") -> bool:
try:
choice = input(prompt).strip().lower()
if not choice or choice in ("y", "yes", "tak", "t"):
return True
return False
except (KeyboardInterrupt, EOFError):
print("\nAborted.")
return False
def main(argv: Optional[List[str]] = None) -> int:
parser = create_parser()
args = parser.parse_args(argv)
@@ -132,61 +161,165 @@ def main(argv: Optional[List[str]] = None) -> int:
print(f"Linux System Updater v{__version__}")
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
if distro.family == DistroFamily.UNKNOWN:
if not args.json:
print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr)
return 1
config = UpdaterConfig.load(Path(args.config) if args.config else None)
if args.non_interactive:
config.non_interactive = True
if args.no_remediation:
config.auto_remediate = False
# Create dummy manager for health checks when specific manager isn't wired yet
from linux_updater.managers.base import PackageManager
from linux_updater.models import RebootStatus
class FallbackManager(PackageManager):
@property
def name(self) -> str:
return distro.family.value
def refresh_repositories(self): pass
def check_updates(self): return []
def apply_updates(self, packages=None, dry_run=False, non_interactive=False): pass
def release_upgrade(self, target_release=None, non_interactive=False): pass
def clean_cache(self): pass
def autoremove(self): pass
def is_reboot_required(self) -> RebootStatus:
reboot_p = Path("/var/run/reboot-required")
return RebootStatus(required=reboot_p.exists(), reason="reboot-required flag found" if reboot_p.exists() else "")
def get_lock_files(self) -> List[Path]:
if distro.family == DistroFamily.DEBIAN:
return [Path("/var/lib/dpkg/lock-frontend"), Path("/var/lib/dpkg/lock")]
elif distro.family == DistroFamily.RHEL:
return [Path("/var/lib/rpm/.rpm.lock")]
elif distro.family == DistroFamily.ARCH:
return [Path("/var/lib/pacman/db.lck")]
return []
manager = FallbackManager()
from linux_updater.core.health import HealthChecker
runner = CommandRunner(verbose=config.verbose, log_file=Path(config.log_file) if config.log_file else None)
manager = get_manager(distro.family, runner=runner)
checker = HealthChecker(config=config, manager=manager)
remediation = RemediationEngine(manager=manager)
# 1. Health Command
if args.command == "health":
report = checker.run_all_checks()
if args.json:
import json
print(json.dumps(report.to_dict(), indent=2))
else:
print("\nPre-flight Health Diagnostics:")
print("-" * 65)
for res in report.results:
status_symbol = "[ PASS ]" if res.status.value == "PASS" else (
"[ WARN ]" if res.status.value == "WARN" else "[ FAIL ]"
)
print(f"{status_symbol} {res.name:<22} {res.message}")
print("-" * 65)
status_text = "PASSED" if report.passed else "FAILED"
print(f"Overall Pre-flight Status: {status_text}\n")
format_health_report(report)
return 0 if report.passed else 1
# 2. Clean Command
if args.command == "clean":
if not args.json:
print("Cleaning package cache...")
res_clean = manager.clean_cache()
res_auto = None
if getattr(args, "all", False):
if not args.json:
print("Removing unused dependencies...")
res_auto = manager.autoremove()
if args.json:
print(json.dumps({
"clean_cache": res_clean.to_dict(),
"autoremove": res_auto.to_dict() if res_auto else None,
}, indent=2))
else:
print("Clean operation completed successfully.")
return 0
# 3. Pre-flight health checks (for update, check, release-upgrade)
if not args.skip_preflight:
report = checker.run_all_checks()
if not report.passed:
if config.auto_remediate:
if not args.json:
print("Pre-flight checks failed. Attempting automated safe remediation...")
remediated_any = False
for r in report.results:
if r.status == CheckStatus.FAIL and remediation.can_remediate(r):
if not args.json:
print(f"-> Remediating: {r.name} ({r.remediation_id})...")
if remediation.remediate(r):
remediated_any = True
if remediated_any:
# Re-run checks
report = checker.run_all_checks()
if not report.passed:
if args.json:
print(json.dumps({"error": "preflight_failed", "report": report.to_dict()}, indent=2))
else:
format_health_report(report)
print("Error: Pre-flight checks failed and could not be remediated. Aborting updates.", file=sys.stderr)
return 1
# 4. Check Command
if args.command == "check":
if not args.json:
print("Checking for available package updates...")
updates = manager.check_updates()
if args.json:
print(json.dumps({
"updates_count": len(updates),
"updates": [{"package": u.package, "current_version": u.current_version, "new_version": u.new_version, "repo": u.repo} for u in updates]
}, indent=2))
else:
print(f"\nAvailable Updates ({len(updates)}):")
print("-" * 65)
for u in updates:
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
print("-" * 65)
return 0
# 5. Update Command
if args.command == "update":
packages = getattr(args, "packages", None)
if not args.json:
if packages:
print(f"Preparing to update specific packages: {', '.join(packages)}")
else:
print("Checking available updates...")
# If not selective, query updates for preview in interactive mode
updates = []
if not packages and not config.non_interactive:
updates = manager.check_updates()
if not updates:
if not args.json:
print("System is already up to date. No updates needed.")
return 0
if not args.json:
print(f"\nAvailable Updates ({len(updates)}):")
print("-" * 65)
for u in updates[:20]:
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
if len(updates) > 20:
print(f"... and {len(updates) - 20} more packages.")
print("-" * 65)
# Interactive confirmation gate
if not config.non_interactive and not args.dry_run:
if not prompt_confirmation():
if not args.json:
print("Operation cancelled by user.")
return 3
if not args.json:
print("\nApplying updates...")
res = manager.apply_updates(
packages=packages,
dry_run=args.dry_run,
non_interactive=config.non_interactive,
)
if not res.success:
if not args.json:
print(f"\nUpdate failed with exit code {res.return_code}: {res.stderr}", file=sys.stderr)
else:
print(json.dumps({"success": False, "result": res.to_dict()}, indent=2))
return 1
if config.clean_after_update:
if not args.json:
print("Cleaning orphan packages...")
manager.autoremove()
reboot = manager.is_reboot_required()
if args.json:
print(json.dumps({
"success": True,
"reboot_required": reboot.required,
"reboot_reason": reboot.reason,
}, indent=2))
else:
print("\nUpdates applied successfully!")
if reboot.required:
print(f"\n[!] ATTENTION: A system reboot is required ({reboot.reason}).")
return 2
return 0
return 0