feat: release v2.0.0 with tab completion, package filtering, db health checks, flatpak and logrotate
Build and Publish Release / Build Packages and Publish (push) Successful in 27s

This commit is contained in:
soda64 committed 2026-10-03 08:31:00 +02:00
1 parent 8d4157b42d
commit 8bec4ed932
27 files changed
+1053 -69

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
"""Linux System Updater - Multi-distribution system updater and health checker."""
__version__ = "1.3.0"
__version__ = "2.0.0"
__author__ = "Test Factory"
+105 -6
View File
@@ -2,6 +2,7 @@ import argparse
import json
import os
from pathlib import Path
import shutil
import sys
from typing import List, Optional
@@ -116,9 +117,25 @@ Examples:
metavar="PACKAGE",
help="Selectively update only the specified package(s) instead of the entire system.",
)
update_parser.add_argument(
"--exclude",
nargs="+",
metavar="PATTERN",
help="Exclude package(s) or glob patterns (e.g. 'kernel*', 'nginx') from update.",
)
update_parser.add_argument(
"--security",
action="store_true",
help="Apply only security-related updates (supported on RHEL/Fedora/Debian/Ubuntu).",
)
update_parser.add_argument(
"--flatpak",
action="store_true",
help="Also update Flatpak packages if flatpak is installed.",
)
# Subcommand: check
subparsers.add_parser(
check_parser = subparsers.add_parser(
"check",
parents=[common],
help="Check system health and list available updates without making modifications.",
@@ -128,8 +145,21 @@ Examples:
Examples:
linux-updater check
linux-updater check --json
linux-updater check --security
linux-updater check --exclude kernel*
""",
)
check_parser.add_argument(
"--exclude",
nargs="+",
metavar="PATTERN",
help="Exclude package(s) or glob patterns from check.",
)
check_parser.add_argument(
"--security",
action="store_true",
help="Check only security-related updates.",
)
# Subcommand: release-upgrade
release_parser = subparsers.add_parser(
@@ -193,6 +223,33 @@ Examples:
""",
)
# Subcommand: completion
completion_parser = subparsers.add_parser(
"completion",
help="Generate shell autocompletion script (bash or zsh).",
formatter_class=argparse.RawDescriptionHelpFormatter,
description="Generate shell autocompletion script for Bash or Zsh.",
epilog="""
Installation Examples:
# Bash (current session)
source <(linux-updater completion bash)
# Bash (system-wide)
sudo linux-updater completion bash > /usr/share/bash-completion/completions/linux-updater
# Zsh (current session)
source <(linux-updater completion zsh)
# Zsh (system-wide)
sudo linux-updater completion zsh > /usr/share/zsh/site-functions/_linux-updater
""",
)
completion_parser.add_argument(
"shell",
choices=["bash", "zsh"],
help="Shell to generate autocompletion script for.",
)
return parser
@@ -262,6 +319,16 @@ def main(argv: Optional[List[str]] = None) -> int:
parser = create_parser()
args = parser.parse_args(argv)
if args.command == "completion":
from linux_updater.core.completion import get_bash_completion, get_zsh_completion
shell = getattr(args, "shell", "bash")
if shell == "zsh":
sys.stdout.write(get_zsh_completion())
else:
sys.stdout.write(get_bash_completion())
sys.stdout.flush()
return 0
if args.command is None:
args.command = "update"
@@ -444,16 +511,24 @@ def _run(
# 4. Check Command
if args.command == "check":
exclude = getattr(args, "exclude", None) or config.exclude_packages
security_only = getattr(args, "security", False) or config.security_only
if not json_output:
print("Checking for available package updates...")
updates = manager.check_updates()
if security_only:
print("Checking for available security updates...")
else:
print("Checking for available package updates...")
updates = manager.check_updates(exclude=exclude, security_only=security_only)
if json_output:
print(json.dumps({
"updates_count": len(updates),
"security_only": security_only,
"exclude": exclude,
"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)}):")
label = "Security Updates" if security_only else "Available Updates"
print(f"\n{label} ({len(updates)}):")
print("-" * 65)
for u in updates:
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
@@ -463,22 +538,28 @@ def _run(
# 5. Update Command
if args.command == "update":
packages = getattr(args, "packages", None)
exclude = getattr(args, "exclude", None) or config.exclude_packages
security_only = getattr(args, "security", False) or config.security_only
if not json_output:
if packages:
print(f"Preparing to update specific packages: {', '.join(packages)}")
elif security_only:
print("Checking available security updates...")
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()
updates = manager.check_updates(exclude=exclude, security_only=security_only)
if not updates:
if not json_output:
print("System is already up to date. No updates needed.")
return 0
if not json_output:
print(f"\nAvailable Updates ({len(updates)}):")
label = "Available Security Updates" if security_only else "Available Updates"
print(f"\n{label} ({len(updates)}):")
print("-" * 65)
for u in updates[:20]:
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
@@ -498,6 +579,8 @@ def _run(
res = manager.apply_updates(
packages=packages,
exclude=exclude,
security_only=security_only,
dry_run=dry_run,
non_interactive=config.non_interactive,
)
@@ -509,6 +592,22 @@ def _run(
print(json.dumps({"success": False, "result": res.to_dict()}, indent=2))
return 1
# Flatpak updates if requested
flatpak_requested = getattr(args, "flatpak", False) or config.update_flatpak
if flatpak_requested:
flatpak_bin = shutil.which("flatpak")
if flatpak_bin:
if dry_run:
if not json_output:
print("[dry-run] Would execute: flatpak update -y")
else:
if not json_output:
print("\nUpdating Flatpak packages...")
runner.run(["flatpak", "update", "-y"])
elif getattr(args, "flatpak", False):
if not json_output:
print("Warning: flatpak binary not found, skipping Flatpak updates.", file=sys.stderr)
if config.clean_after_update:
if not json_output:
print("Cleaning orphan packages...")
+13 -1
View File
@@ -1,6 +1,6 @@
import json
from pathlib import Path
from typing import Optional, Dict, Any
from typing import Optional, Dict, Any, List
class UpdaterConfig:
@@ -15,6 +15,9 @@ class UpdaterConfig:
check_ac_power: bool = True,
clean_after_update: bool = False,
auto_reboot: bool = False,
exclude_packages: Optional[List[str]] = None,
security_only: bool = False,
update_flatpak: bool = False,
log_dir: Optional[str] = "/var/log/linux-updater",
log_file: Optional[str] = None,
verbose: bool = False,
@@ -28,6 +31,9 @@ class UpdaterConfig:
self.check_ac_power = check_ac_power
self.clean_after_update = clean_after_update
self.auto_reboot = auto_reboot
self.exclude_packages = exclude_packages or []
self.security_only = security_only
self.update_flatpak = update_flatpak
self.log_dir = log_dir
self.log_file = log_file
self.verbose = verbose
@@ -60,6 +66,9 @@ class UpdaterConfig:
check_ac_power=behavior.get("check_ac_power", True),
clean_after_update=behavior.get("clean_after_update", False),
auto_reboot=behavior.get("auto_reboot", False),
exclude_packages=behavior.get("exclude_packages", []),
security_only=behavior.get("security_only", False),
update_flatpak=behavior.get("update_flatpak", False),
log_dir=logging.get("log_dir", "/var/log/linux-updater"),
log_file=logging.get("log_file", None),
verbose=logging.get("verbose", False),
@@ -79,6 +88,9 @@ class UpdaterConfig:
"check_ac_power": self.check_ac_power,
"clean_after_update": self.clean_after_update,
"auto_reboot": self.auto_reboot,
"exclude_packages": self.exclude_packages,
"security_only": self.security_only,
"update_flatpak": self.update_flatpak,
},
"logging": {
"log_dir": self.log_dir,
+163
View File
@@ -0,0 +1,163 @@
"""Shell completion script generator for linux-updater (Bash & Zsh)."""
BASH_COMPLETION = """# bash completion for linux-updater
_linux_updater() {
local cur prev words cword
_init_completion -n : || return
local commands="update check release-upgrade clean health completion"
local common_opts="-c --config -y --yes --non-interactive --dry-run --no-remediation --skip-preflight --json --reboot -h --help"
# Find the current subcommand (if any)
local cmd=""
local i
for (( i=1; i < cword; i++ )); do
case "${words[i]}" in
update|check|release-upgrade|clean|health|completion)
cmd="${words[i]}"
break
;;
esac
done
# Handle completion for previous option
case "$prev" in
-c|--config)
_filedir json
return 0
;;
-t|--target-release|--releasever)
return 0
;;
--packages|--exclude)
return 0
;;
esac
# If no subcommand has been entered yet
if [[ -z "$cmd" ]]; then
if [[ "$cur" == -* ]]; then
COMPREPLY=( $(compgen -W "$common_opts -v --version" -- "$cur") )
return 0
else
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
return 0
fi
fi
# Subcommand-specific completions
case "$cmd" in
update)
COMPREPLY=( $(compgen -W "$common_opts --packages --exclude --security --flatpak" -- "$cur") )
;;
check)
COMPREPLY=( $(compgen -W "$common_opts" -- "$cur") )
;;
release-upgrade)
COMPREPLY=( $(compgen -W "$common_opts -t --target-release --releasever" -- "$cur") )
;;
clean)
COMPREPLY=( $(compgen -W "$common_opts --all" -- "$cur") )
;;
health)
COMPREPLY=( $(compgen -W "$common_opts" -- "$cur") )
;;
completion)
COMPREPLY=( $(compgen -W "bash zsh" -- "$cur") )
;;
esac
return 0
}
complete -F _linux_updater linux-updater
"""
ZSH_COMPLETION = r"""#compdef linux-updater
_linux_updater() {
local context state state_descr line
typeset -A opt_args
local -a common_args
common_args=(
'(-c --config)'{-c,--config}'[Path to JSON configuration file]:config file:_files -g "*.json"'
'(-y --yes --non-interactive)'{-y,--yes,--non-interactive}'[Run without interactive confirmation prompts]'
'--dry-run[Simulate execution without modifying system state]'
'--no-remediation[Disable automatic remediation of failed health checks]'
'--skip-preflight[Skip pre-flight health checks]'
'--json[Output structured JSON results]'
'--reboot[Automatically reboot the system after upgrade or if required]'
'(-h --help)'{-h,--help}'[Show help message and exit]'
)
_arguments -C \
'(-v --version)'{-v,--version}'[Show program version and exit]' \
$common_args \
'1: :->command' \
'*:: :->args'
case $state in
command)
local -a commands
commands=(
'update:Inspect health, auto-remediate safe issues, and apply package updates'
'check:Check system health and list available updates without making modifications'
'release-upgrade:Perform a major distribution release upgrade with safety checks'
'clean:Clean downloaded package cache and remove orphaned packages'
'health:Run only the pre-flight health diagnostic checks'
'completion:Generate shell autocompletion script (bash or zsh)'
)
_describe -t commands 'subcommand' commands
;;
args)
case $line[1] in
update)
_arguments \
$common_args \
'--packages[Selectively update specified package(s)]:package: ' \
'--exclude[Exclude package(s) or glob patterns from update]:exclude: ' \
'--security[Apply only security-related updates]' \
'--flatpak[Update Flatpak packages if available]'
;;
check)
_arguments \
$common_args
;;
release-upgrade)
_arguments \
$common_args \
'(-t --target-release --releasever)'{-t,--target-release,--releasever}'[Specify target distribution version number/codename]:target release: '
;;
clean)
_arguments \
$common_args \
'--all[Clean both package cache and autoremove unused dependencies]'
;;
health)
_arguments \
$common_args
;;
completion)
local -a shells
shells=('bash:Generate Bash completion script' 'zsh:Generate Zsh completion script')
_describe -t shells 'shell' shells
;;
esac
;;
esac
}
_linux_updater "$@"
"""
def get_bash_completion() -> str:
"""Returns the Bash completion script."""
return BASH_COMPLETION.strip() + "\n"
def get_zsh_completion() -> str:
"""Returns the Zsh completion function."""
return ZSH_COMPLETION.strip() + "\n"
+32
View File
@@ -340,6 +340,37 @@ class HealthChecker:
)
return results
def check_package_db(self) -> List[CheckResult]:
results: List[CheckResult] = []
try:
res = self.manager.verify_db_consistency()
if isinstance(res, (tuple, list)) and len(res) == 2:
is_ok, msg = res
else:
is_ok, msg = True, "Package database is consistent."
except Exception as e:
is_ok, msg = False, f"Package database check failed: {e}"
if is_ok:
results.append(
CheckResult(
name="package_db",
status=CheckStatus.PASS,
message=msg,
)
)
else:
results.append(
CheckResult(
name="package_db",
status=CheckStatus.FAIL,
message=msg,
can_remediate=True,
remediation_id="repair_package_db",
)
)
return results
def run_all_checks(self) -> PreflightReport:
all_results: List[CheckResult] = []
all_results.extend(self.check_disk_space())
@@ -347,6 +378,7 @@ class HealthChecker:
all_results.extend(self.check_memory_and_oom())
all_results.extend(self.check_power())
all_results.extend(self.check_pending_reboot())
all_results.extend(self.check_package_db())
has_failure = any(r.status == CheckStatus.FAIL for r in all_results)
return PreflightReport(passed=not has_failure, results=all_results)
+12 -1
View File
@@ -14,7 +14,7 @@ class RemediationEngine:
def can_remediate(self, check: CheckResult) -> bool:
if not check.can_remediate:
return False
return check.remediation_id in {"clean_cache", "remove_stale_lock"}
return check.remediation_id in {"clean_cache", "remove_stale_lock", "repair_package_db"}
def remediate(self, check: CheckResult) -> bool:
if not self.can_remediate(check):
@@ -24,9 +24,20 @@ class RemediationEngine:
return self.clean_cache()
elif check.remediation_id == "remove_stale_lock":
return self.remove_stale_lock(check.message)
elif check.remediation_id == "repair_package_db":
return self.repair_package_db()
return False
def repair_package_db(self) -> bool:
try:
res = self.manager.repair_db()
if hasattr(res, "success"):
return bool(res.success)
return True
except Exception:
return False
def clean_cache(self) -> bool:
try:
res = self.manager.clean_cache()
+49 -10
View File
@@ -1,6 +1,6 @@
import re
from pathlib import Path
from typing import Dict, List, Optional
from typing import Dict, List, Optional, Tuple
from linux_updater.core.runner import CommandRunner
from linux_updater.managers.base import PackageManager
@@ -27,39 +27,67 @@ class AptManager(PackageManager):
cmd = ["apt-get", "update"]
return self.runner.run(cmd, env=self._env(True))
def check_updates(self) -> List[PackageUpdate]:
def check_updates(
self,
exclude: Optional[List[str]] = None,
security_only: bool = False,
) -> List[PackageUpdate]:
cmd = ["apt-get", "-s", "upgrade"]
res = self.runner.run(cmd, env=self._env(True))
updates: List[PackageUpdate] = []
# Inst libssl3 [3.0.13-0ubuntu3.1] (3.0.13-0ubuntu3.4 Ubuntu:24.04/noble-updates [amd64])
import fnmatch
pattern = re.compile(r"^Inst\s+(\S+)\s+\[([^\]]+)\]\s+\((\S+)\s+([^)]*)\)")
pattern_new = re.compile(r"^Inst\s+(\S+)\s+\((\S+)\s+([^)]*)\)")
for line in res.stdout.splitlines():
line = line.strip()
pkg = None
old_ver = "none"
new_ver = ""
repo = None
match = pattern.match(line)
if match:
pkg, old_ver, new_ver, repo = match.groups()
else:
match_new = pattern_new.match(line)
if match_new:
pkg, new_ver, repo = match_new.groups()
if pkg:
if exclude and any(fnmatch.fnmatch(pkg, pat) for pat in exclude):
continue
if security_only:
repo_str = repo.lower() if repo else ""
if "security" not in repo_str and "-sec" not in repo_str:
continue
updates.append(PackageUpdate(package=pkg, current_version=old_ver, new_version=new_ver, repo=repo))
continue
match_new = pattern_new.match(line)
if match_new:
pkg, new_ver, repo = match_new.groups()
updates.append(PackageUpdate(package=pkg, current_version="none", new_version=new_ver, repo=repo))
return updates
def apply_updates(
self,
packages: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
security_only: bool = False,
dry_run: bool = False,
non_interactive: bool = False,
) -> CommandResult:
cmd = ["apt-get"]
if packages:
cmd.extend(["install", "--only-upgrade", "-y"])
cmd.extend(packages)
import fnmatch
target_pkgs = [p for p in packages if not (exclude and any(fnmatch.fnmatch(p, pat) for pat in exclude))]
if not target_pkgs:
return CommandResult(0, "All specified packages were excluded.", "", True)
cmd.extend(["install", "--only-upgrade", "-y"] + target_pkgs)
elif exclude or security_only:
filtered = self.check_updates(exclude=exclude, security_only=security_only)
if not filtered:
return CommandResult(0, "No matching packages to upgrade after applying filters.", "", True)
target_pkgs = [u.package for u in filtered]
cmd.extend(["install", "--only-upgrade", "-y"] + target_pkgs)
else:
cmd.extend(["upgrade", "-y"])
@@ -127,3 +155,14 @@ class AptManager(PackageManager):
Path("/var/lib/dpkg/lock"),
Path("/var/lib/apt/lists/lock"),
]
def verify_db_consistency(self) -> "Tuple[bool, str]":
audit_res = self.runner.run(["dpkg", "--audit"])
if audit_res.return_code != 0 or audit_res.stdout.strip():
msg = audit_res.stdout.strip() or audit_res.stderr.strip() or "Unconfigured or broken packages detected"
return False, f"dpkg audit found package database issues: {msg[:100]}"
return True, "dpkg package database is consistent."
def repair_db(self) -> CommandResult:
self.runner.run(["dpkg", "--configure", "-a"], env=self._env(True))
return self.runner.run(["apt-get", "install", "-f", "-y"], env=self._env(True))
+16 -2
View File
@@ -1,6 +1,6 @@
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Optional
from typing import List, Optional, Tuple
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
@@ -17,7 +17,11 @@ class PackageManager(ABC):
pass
@abstractmethod
def check_updates(self) -> List[PackageUpdate]:
def check_updates(
self,
exclude: Optional[List[str]] = None,
security_only: bool = False,
) -> List[PackageUpdate]:
"""Lists available package updates."""
pass
@@ -25,6 +29,8 @@ class PackageManager(ABC):
def apply_updates(
self,
packages: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
security_only: bool = False,
dry_run: bool = False,
non_interactive: bool = False,
) -> CommandResult:
@@ -60,3 +66,11 @@ class PackageManager(ABC):
def get_lock_files(self) -> List[Path]:
"""Returns paths of lockfiles used by this manager."""
pass
def verify_db_consistency(self) -> "Tuple[bool, str]":
"""Checks whether the package manager database has broken/interrupted transactions."""
return True, "Package database is consistent."
def repair_db(self) -> CommandResult:
"""Attempts automated repair of interrupted/broken package transactions."""
return CommandResult(0, "No repair needed.", "", True)
+29 -1
View File
@@ -29,8 +29,17 @@ class DnfManager(PackageManager):
cmd = [self.binary, "makecache"]
return self.runner.run(cmd)
def check_updates(self) -> List[PackageUpdate]:
def check_updates(
self,
exclude: Optional[List[str]] = None,
security_only: bool = False,
) -> List[PackageUpdate]:
cmd = [self.binary, "check-update"]
if security_only:
cmd.append("--security")
if exclude:
for pat in exclude:
cmd.extend(["-x", pat])
res = self.runner.run(cmd)
# DNF returns exit code 100 when updates are found, 0 when clean
@@ -56,6 +65,8 @@ class DnfManager(PackageManager):
def apply_updates(
self,
packages: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
security_only: bool = False,
dry_run: bool = False,
non_interactive: bool = False,
) -> CommandResult:
@@ -65,6 +76,13 @@ class DnfManager(PackageManager):
else:
cmd.append("-y")
if security_only:
cmd.append("--security")
if exclude:
for pat in exclude:
cmd.extend(["-x", pat])
if packages:
cmd.extend(packages)
@@ -412,3 +430,13 @@ class DnfManager(PackageManager):
Path("/var/lib/rpm/.rpm.lock"),
Path("/var/run/dnf.pid"),
]
def verify_db_consistency(self) -> Tuple[bool, str]:
check_res = self.runner.run([self.binary, "check"])
if check_res.return_code != 0:
msg = check_res.stderr.strip() or check_res.stdout.strip() or "Transaction database issues found"
return False, f"dnf check found package database issues: {msg[:100]}"
return True, "RPM database is consistent."
def repair_db(self) -> CommandResult:
return self.runner.run([self.binary, "clean", "all"])
+37 -4
View File
@@ -1,7 +1,7 @@
import os
import shutil
from pathlib import Path
from typing import List, Optional
from typing import List, Optional, Tuple
from linux_updater.core.runner import CommandRunner
from linux_updater.managers.base import PackageManager
@@ -19,24 +19,32 @@ class PacmanManager(PackageManager):
def refresh_repositories(self) -> CommandResult:
return self.runner.run(["pacman", "-Sy"])
def check_updates(self) -> List[PackageUpdate]:
def check_updates(
self,
exclude: Optional[List[str]] = None,
security_only: bool = False,
) -> List[PackageUpdate]:
# Prefer checkupdates if installed (safe non-root update check)
cmd = ["checkupdates"] if shutil.which("checkupdates") else ["pacman", "-Qu"]
res = self.runner.run(cmd)
import fnmatch
updates: List[PackageUpdate] = []
for line in res.stdout.splitlines():
line = line.strip()
if not line or "->" not in line:
continue
# Format: package old_version -> new_version [repo]
try:
left, right = line.split("->", 1)
left_parts = left.strip().split()
right_parts = right.strip().split()
pkg = left_parts[0]
if exclude and any(fnmatch.fnmatch(pkg, pat) for pat in exclude):
continue
old_ver = left_parts[1] if len(left_parts) > 1 else "unknown"
new_ver = right_parts[0] if right_parts else "unknown"
repo = right_parts[1].strip("[]") if len(right_parts) > 1 else None
@@ -50,22 +58,32 @@ class PacmanManager(PackageManager):
def apply_updates(
self,
packages: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
security_only: bool = False,
dry_run: bool = False,
non_interactive: bool = False,
) -> CommandResult:
if packages:
import fnmatch
target_pkgs = [p for p in packages if not (exclude and any(fnmatch.fnmatch(p, pat) for pat in exclude))]
if not target_pkgs:
return CommandResult(0, "All specified packages were excluded.", "", True)
cmd = ["pacman", "-S"]
if dry_run:
cmd.append("-p")
else:
cmd.append("--noconfirm")
cmd.extend(packages)
if exclude:
cmd.extend(["--ignore", ",".join(exclude)])
cmd.extend(target_pkgs)
else:
cmd = ["pacman", "-Su"]
if dry_run:
cmd.append("-p")
else:
cmd.append("--noconfirm")
if exclude:
cmd.extend(["--ignore", ",".join(exclude)])
return self.runner.run(cmd, stream=not dry_run)
@@ -112,3 +130,18 @@ class PacmanManager(PackageManager):
def get_lock_files(self) -> List[Path]:
return [Path("/var/lib/pacman/db.lck")]
def verify_db_consistency(self) -> "Tuple[bool, str]":
lock_p = Path("/var/lib/pacman/db.lck")
if lock_p.exists():
return False, f"Stale pacman database lock: {lock_p}"
return True, "Pacman database is consistent."
def repair_db(self) -> CommandResult:
lock_p = Path("/var/lib/pacman/db.lck")
if lock_p.exists():
try:
lock_p.unlink()
except Exception:
pass
return CommandResult(0, "Pacman database checked.", "", True)