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
Build and Publish Release / Build Packages and Publish (push) Successful in 27s
This commit is contained in:
1 parent
8d4157b42d
commit
8bec4ed932
27 files changed
+1053
-69
No files matched your search
@@ -14,19 +14,27 @@
|
||||
- **Pre-flight Health Diagnostics:**
|
||||
- **Disk Space:** Enforces safety thresholds on `/boot` (>= 250 MB), `/var` (>= 1024 MB), and `/` (>= 1024 MB).
|
||||
- **Process Locks:** Detects active package manager locks (via PID checking and non-blocking `fcntl.flock` advisory locks).
|
||||
- **Package Database Consistency:** Verifies package manager integrity (`dpkg --audit`, `dnf check`, `pacman` lock integrity) and auto-remediates interrupted transactions (`dpkg --configure -a`, `apt-get install -f`, `dnf clean all`).
|
||||
- **Memory & OOM Pressure:** Inspects `/proc/meminfo` to warn or halt if available RAM is dangerously low (< 300 MB).
|
||||
- **AC Power Protection:** Inspects `/sys/class/power_supply` on laptops to prevent updates on battery power.
|
||||
- **Reboot Detection:** Detects pending reboots from previous kernel/library updates.
|
||||
- **Safe Automated Remediation:** Safely cleans package cache when `/var` is low and clears stale locks if the holder process is confirmed dead.
|
||||
- **Safe Automated Remediation:** Safely cleans package cache when `/var` is low, clears stale locks if the holder process is dead, and repairs interrupted package transactions.
|
||||
- **Advanced Update Capabilities:**
|
||||
- **Security-only Updates:** `--security` flag restricts updates strictly to CVE/security advisories on RHEL, Fedora, CentOS, Rocky, AlmaLinux, Debian, and Ubuntu.
|
||||
- **Package Filtering:** `--exclude` skips specified packages or glob patterns (e.g., `--exclude "kernel*" "nginx"`).
|
||||
- **Selective Packages:** `--packages` selectively targets specific packages for updates.
|
||||
- **Flatpak Integration:** `--flatpak` triggers Flatpak application updates after OS packages.
|
||||
- **Shell Tab Autocompletion:** Native, zero-latency Bash and Zsh completions with instant flag/subcommand suggestions (`linux-updater completion bash|zsh`).
|
||||
- **Two Update Tiers:**
|
||||
- `update`: Routine updates (with optional selective package targeting via `--packages`).
|
||||
- `update`: Routine updates with security filters, exclusions, and Flatpak support.
|
||||
- `release-upgrade`: Major distribution upgrades (e.g. Debian 12 $\rightarrow$ 13, Ubuntu 22.04 $\rightarrow$ 24.04, Fedora 40 $\rightarrow$ 41, or RHEL/AlmaLinux `leapp` upgrades) with safety warnings.
|
||||
- **Standard Linux FHS Logging:**
|
||||
- **Standard Linux FHS Logging & Logrotate:**
|
||||
- Logs transactions to `/var/log/linux-updater/linux-updater-<YYYYMMDD>-<HHMMSS>.log`.
|
||||
- Atomically maintains `/var/log/linux-updater/latest.log` symlink pointing to the most recent execution.
|
||||
- Atomically maintains `/var/log/linux-updater/latest.log` symlink.
|
||||
- Ships with `/etc/logrotate.d/linux-updater` (weekly rotation, 4 copies, compressed).
|
||||
- **Automation Ready:**
|
||||
- Structured `--json` output for Zabbix, Wazuh, Prometheus node exporters, or custom agents.
|
||||
- Non-interactive mode (`-y` / `--non-interactive`) for cron and systemd timers.
|
||||
- Non-interactive mode (`-y` / `--non-interactive`) for cron, Ansible, and central management.
|
||||
- Deterministic exit codes.
|
||||
|
||||
---
|
||||
@@ -49,7 +57,7 @@
|
||||
python3 packaging/build_packages.py
|
||||
|
||||
# Install generated deb:
|
||||
sudo dpkg -i dist/linux-updater_1.3.0_all.deb
|
||||
sudo dpkg -i dist/linux-updater_2.0.0_all.deb
|
||||
```
|
||||
|
||||
### Option 2: Native `.rpm` Package (RHEL / Fedora / AlmaLinux / Rocky)
|
||||
@@ -63,8 +71,8 @@ sudo rpm -Uvh dist/rpm/RPMS/noarch/linux-updater-*.noarch.rpm
|
||||
|
||||
### Option 3: Standalone Tarball (All Linux Distributions)
|
||||
```bash
|
||||
tar -xzf dist/linux-updater-1.3.0.tar.gz
|
||||
cd linux-updater-1.3.0
|
||||
tar -xzf dist/linux-updater-2.0.0.tar.gz
|
||||
cd linux-updater-2.0.0
|
||||
sudo ./install.sh
|
||||
```
|
||||
|
||||
@@ -91,20 +99,29 @@ sudo linux-updater update
|
||||
# 6. Apply updates non-interactively with automated reboot:
|
||||
sudo linux-updater update -y --reboot
|
||||
|
||||
# 7. Selectively update specific packages:
|
||||
# 7. Apply security-only updates non-interactively:
|
||||
sudo linux-updater update -y --security
|
||||
|
||||
# 8. Exclude specific packages or glob patterns:
|
||||
sudo linux-updater update -y --exclude "kernel*" "nginx"
|
||||
|
||||
# 9. Update system packages and Flatpak apps:
|
||||
sudo linux-updater update -y --flatpak
|
||||
|
||||
# 10. Selectively update specific packages:
|
||||
sudo linux-updater update -y --packages openssl nginx
|
||||
|
||||
# 8. Major distribution release upgrade (interactive confirmation & prompt for reboot):
|
||||
# 11. Major distribution release upgrade (interactive confirmation & prompt for reboot):
|
||||
sudo linux-updater release-upgrade -t 44
|
||||
|
||||
# 9. Major release upgrade with alias syntax and automated reboot:
|
||||
# 12. Major release upgrade with alias syntax and automated reboot:
|
||||
sudo linux-updater release-upgrade --releasever 44 --reboot
|
||||
|
||||
# 10. Simulate major distribution release upgrade:
|
||||
sudo linux-updater release-upgrade --dry-run -t 44
|
||||
|
||||
# 11. Clean package cache and remove orphaned packages:
|
||||
# 13. Clean package cache and remove orphaned packages:
|
||||
sudo linux-updater clean --all
|
||||
|
||||
# 14. Enable Bash or Zsh tab autocompletion:
|
||||
eval "$(linux-updater completion bash)"
|
||||
```
|
||||
|
||||
---
|
||||
@@ -126,7 +143,10 @@ Default settings can be customized in `/etc/linux-updater.json`:
|
||||
"non_interactive": false,
|
||||
"check_ac_power": true,
|
||||
"clean_after_update": false,
|
||||
"auto_reboot": false
|
||||
"auto_reboot": false,
|
||||
"exclude_packages": [],
|
||||
"security_only": false,
|
||||
"update_flatpak": false
|
||||
},
|
||||
"logging": {
|
||||
"log_dir": "/var/log/linux-updater",
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# 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
|
||||
@@ -0,0 +1,76 @@
|
||||
#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 "$@"
|
||||
+39
-5
@@ -71,7 +71,11 @@ The default configuration file `/etc/linux-updater.json` governs health check th
|
||||
"auto_remediate": true,
|
||||
"non_interactive": false,
|
||||
"check_ac_power": true,
|
||||
"clean_after_update": false
|
||||
"clean_after_update": false,
|
||||
"auto_reboot": false,
|
||||
"exclude_packages": [],
|
||||
"security_only": false,
|
||||
"update_flatpak": false
|
||||
},
|
||||
"logging": {
|
||||
"log_dir": "/var/log/linux-updater",
|
||||
@@ -88,10 +92,14 @@ The default configuration file `/etc/linux-updater.json` governs health check th
|
||||
- `min_ram_mb`: Available RAM threshold in `/proc/meminfo`. Protects against OOM killer crashing package scripts. Defaults to 300 MB.
|
||||
|
||||
### Behavior Parameters
|
||||
- `auto_remediate`: When `true`, automatically clears package cache if `/var` is low and unlinks stale locks if the holder PID is dead.
|
||||
- `auto_remediate`: When `true`, automatically clears package cache if `/var` is low, unlinks stale locks if the holder PID is dead, and repairs interrupted package transactions (`dpkg --configure -a`, `apt-get install -f`, `dnf clean all`).
|
||||
- `non_interactive`: Default non-interactive state. (Overridden by CLI `-y`).
|
||||
- `check_ac_power`: Inspects `/sys/class/power_supply` and warns/halts if running on battery power.
|
||||
- `clean_after_update`: If `true`, runs `autoremove` automatically after successful updates.
|
||||
- `auto_reboot`: When `true`, automatically triggers reboot if a kernel or core system component was upgraded.
|
||||
- `exclude_packages`: List of package names or glob patterns to skip during update transactions.
|
||||
- `security_only`: When `true`, restricts all update operations strictly to security patches.
|
||||
- `update_flatpak`: When `true`, executes `flatpak update -y` after OS packages update if flatpak is installed.
|
||||
|
||||
---
|
||||
|
||||
@@ -136,6 +144,13 @@ linux-updater health --json
|
||||
"message": "No pending system reboot detected.",
|
||||
"can_remediate": false,
|
||||
"remediation_id": null
|
||||
},
|
||||
{
|
||||
"name": "package_db",
|
||||
"status": "PASS",
|
||||
"message": "Package database is consistent.",
|
||||
"can_remediate": false,
|
||||
"remediation_id": null
|
||||
}
|
||||
],
|
||||
"remediations_performed": []
|
||||
@@ -174,19 +189,38 @@ esac
|
||||
|
||||
## 4. Log Management & Logrotate
|
||||
|
||||
By default, logs are written to `/var/log/linux-updater/` with:
|
||||
By default, logs are written to `/var/log/linux-updater/` conforming to Linux FHS:
|
||||
- Timestamped files: `linux-updater-YYYYMMDD-HHMMSS.log`
|
||||
- Symlink to latest run: `/var/log/linux-updater/latest.log`
|
||||
|
||||
To manage historical logs and compress older runs, configure `/etc/logrotate.d/linux-updater`:
|
||||
The package installation automatically provides `/etc/logrotate.d/linux-updater`:
|
||||
|
||||
```text
|
||||
/var/log/linux-updater/*.log {
|
||||
weekly
|
||||
rotate 12
|
||||
rotate 4
|
||||
compress
|
||||
missingok
|
||||
notifempty
|
||||
create 0640 root root
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Shell Tab Autocompletion Deployment
|
||||
|
||||
For administrative workstations and fleet servers, shell completions can be automatically deployed:
|
||||
|
||||
- **System-wide Bash:** `/usr/share/bash-completion/completions/linux-updater`
|
||||
- **System-wide Zsh:** `/usr/share/zsh/site-functions/_linux-updater` (or `/usr/share/zsh/vendor-completions/_linux-updater`)
|
||||
|
||||
Both files are automatically placed when installing via `.deb`, `.rpm`, or `install.sh`. Administrators can also dynamically output and evaluate them:
|
||||
|
||||
```bash
|
||||
# Bash:
|
||||
linux-updater completion bash > /etc/bash_completion.d/linux-updater
|
||||
|
||||
# Zsh:
|
||||
linux-updater completion zsh > /usr/local/share/zsh/site-functions/_linux-updater
|
||||
```
|
||||
@@ -16,9 +16,11 @@ linux_updater/
|
||||
├── config.py # JSON configuration loader & default thresholds
|
||||
├── models.py # Core data transfer objects (DistroInfo, CheckResult, etc.)
|
||||
├── core/
|
||||
│ ├── completion.py # Shell autocompletion script generator (Bash & Zsh)
|
||||
│ ├── detector.py # Distro detection via /etc/os-release parsing
|
||||
│ ├── health.py # Pre-flight health diagnostics & lock checking
|
||||
│ ├── remediation.py # Automated remediation actions (cache, stale locks)
|
||||
│ ├── health.py # Pre-flight health diagnostics & package DB checking
|
||||
│ ├── lock.py # Concurrency advisory singleton lock
|
||||
│ ├── remediation.py # Automated remediation actions (cache, stale locks, db repair)
|
||||
│ └── runner.py # Subprocess runner with timestamped file logging
|
||||
└── managers/
|
||||
├── __init__.py # get_manager() factory
|
||||
@@ -149,6 +151,6 @@ python3 packaging/build_packages.py
|
||||
```
|
||||
|
||||
Generated artifacts:
|
||||
- `dist/linux-updater-1.3.0.tar.gz`: Standalone distribution archive containing `install.sh`.
|
||||
- `dist/linux-updater_1.3.0_all.deb`: Native Debian/Ubuntu binary package.
|
||||
- `dist/rpm/RPMS/noarch/linux-updater-1.3.0-1.*.noarch.rpm`: Native RPM package.
|
||||
- `dist/linux-updater-2.0.0.tar.gz`: Standalone distribution archive containing `install.sh`.
|
||||
- `dist/linux-updater_2.0.0_all.deb`: Native Debian/Ubuntu binary package.
|
||||
- `dist/rpm/RPMS/noarch/linux-updater-2.0.0-1.*.noarch.rpm`: Native RPM package.
|
||||
@@ -15,6 +15,13 @@
|
||||
- [x] Slice 7 — safety guardrails: root privilege check on mutating commands & singleton concurrency flock
|
||||
- [x] Slice 8 — upgrade dependency auto-installation (ELevate/Leapp/dnf-plugins-core) & container test suites (AlmaLinux 9, Arch Linux)
|
||||
|
||||
## v2.0.0 Slices (Enterprise Modernization)
|
||||
- [x] Slice 9 — Shell tab completion: static Bash & Zsh completions, generator command `linux-updater completion [bash|zsh]`, and package deployment
|
||||
- [x] Slice 10 — Package filtering & Security-only updates: `--exclude` (patterns/pins) and `--security` flag across apt, dnf, pacman
|
||||
- [x] Slice 11 — Pre-flight package DB consistency: `check_package_db` health check with automated transaction repair (dpkg --configure -a)
|
||||
- [x] Slice 12 — Flatpak support & Logrotate: optional `--flatpak` post-update trigger and `/etc/logrotate.d/linux-updater` configuration
|
||||
- [x] Slice 13 — Version bump to 2.0.0, documentation update (guides, man page Section 8), and package rebuild (.deb, .rpm, .tar.gz)
|
||||
|
||||
## Notes for a fresh session
|
||||
- Project: Multi-distribution Linux system updater in Python.
|
||||
- Process: Software Factory 4-gate workflow.
|
||||
|
||||
+39
-2
@@ -27,7 +27,7 @@ linux-updater health
|
||||
|
||||
**Example Output:**
|
||||
```text
|
||||
Linux System Updater v1.3.0
|
||||
Linux System Updater v2.0.0
|
||||
Detected System: Ubuntu 24.04.1 LTS (Family: debian)
|
||||
|
||||
Pre-flight Health Diagnostics:
|
||||
@@ -40,6 +40,7 @@ Pre-flight Health Diagnostics:
|
||||
[ PASS ] lock_lock No lock active at /var/lib/apt/lists/lock
|
||||
[ PASS ] memory_available Available RAM is sufficient: 7850MB
|
||||
[ PASS ] pending_reboot No pending system reboot detected.
|
||||
[ PASS ] package_db Package database is consistent.
|
||||
-----------------------------------------------------------------
|
||||
Overall Pre-flight Status: PASSED
|
||||
```
|
||||
@@ -53,7 +54,7 @@ linux-updater check
|
||||
|
||||
**Example Output:**
|
||||
```text
|
||||
Linux System Updater v1.3.0
|
||||
Linux System Updater v2.0.0
|
||||
Detected System: Fedora Linux 40 (Family: rhel)
|
||||
Checking available updates...
|
||||
|
||||
@@ -91,6 +92,42 @@ If you only want to upgrade specific software (e.g. security patches for OpenSSL
|
||||
sudo linux-updater update --packages openssl nginx
|
||||
```
|
||||
|
||||
### Security-Only Updates (`--security`)
|
||||
To restrict updates solely to security patches and CVE advisories (supported on RHEL, Fedora, CentOS, Rocky, AlmaLinux, Debian, and Ubuntu):
|
||||
|
||||
```bash
|
||||
sudo linux-updater update --security
|
||||
```
|
||||
|
||||
### Excluding Packages (`--exclude`)
|
||||
To exclude specific packages or glob patterns from being upgraded (e.g., pinning kernels, proprietary drivers, or database servers):
|
||||
|
||||
```bash
|
||||
sudo linux-updater update --exclude "kernel*" "nvidia*"
|
||||
```
|
||||
|
||||
### Flatpak Application Updates (`--flatpak`)
|
||||
If you use Flatpak for desktop applications or isolated utilities, pass `--flatpak` to automatically update all Flatpaks after operating system packages have updated:
|
||||
|
||||
```bash
|
||||
sudo linux-updater update --flatpak
|
||||
```
|
||||
|
||||
### Shell Tab Autocompletion (`completion`)
|
||||
`linux-updater` provides zero-latency static tab completion for both Bash and Zsh. Subcommands, flags, and JSON configuration files auto-complete upon pressing `<Tab>`:
|
||||
|
||||
```bash
|
||||
# Enable completion in current Bash shell:
|
||||
eval "$(linux-updater completion bash)"
|
||||
|
||||
# Enable completion in current Zsh shell:
|
||||
eval "$(linux-updater completion zsh)"
|
||||
|
||||
# Permanently install into user profile:
|
||||
linux-updater completion bash >> ~/.bashrc
|
||||
linux-updater completion zsh >> ~/.zshrc
|
||||
```
|
||||
|
||||
### Simulation / Dry Run (`--dry-run`)
|
||||
To simulate the complete update transaction without changing package states:
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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,
|
||||
|
||||
@@ -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"
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
|
||||
@@ -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))
|
||||
@@ -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,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"])
|
||||
@@ -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)
|
||||
+44
-6
@@ -1,4 +1,4 @@
|
||||
.TH LINUX-UPDATER 8 "October 2026" "linux-updater 1.3.0" "System Administration Utilities"
|
||||
.TH LINUX-UPDATER 8 "October 2026" "linux-updater 2.0.0" "System Administration Utilities"
|
||||
.SH NAME
|
||||
linux-updater \- unified, safe multi-distribution Linux system update utility
|
||||
|
||||
@@ -24,20 +24,22 @@ Free disk space verification on \fB/boot\fR (min 250MB), \fB/var\fR (min 1GB), a
|
||||
.IP \(bu 2
|
||||
Package manager lock detection and advisory locking inspections (\fBfcntl.flock\fR).
|
||||
.IP \(bu 2
|
||||
Package database consistency inspection and safe remediation of interrupted transactions (\fBdpkg \-\-configure \-a\fR, \fBapt\-get install \-f\fR, \fBdnf clean all\fR).
|
||||
.IP \(bu 2
|
||||
Memory availability and low-RAM/OOM risk detection via \fB/proc/meminfo\fR.
|
||||
.IP \(bu 2
|
||||
AC power status detection on portable systems via \fB/sys/class/power_supply\fR.
|
||||
.IP \(bu 2
|
||||
Pending reboot detection from previously installed kernels or libraries.
|
||||
|
||||
If low disk space on \fB/var\fR is detected, \fBlinux-updater\fR safely purges cached packages. If an abandoned lock file is identified whose holder process is confirmed dead, it removes the stale lock.
|
||||
If low disk space on \fB/var\fR is detected, \fBlinux-updater\fR safely purges cached packages. If an abandoned lock file is identified whose holder process is confirmed dead, it removes the stale lock. If an interrupted package installation transaction is detected, it executes automated repair.
|
||||
|
||||
.SH COMMANDS
|
||||
.TP
|
||||
.B update \fR[\fB\-\-packages \fIPKG...\fR]
|
||||
Runs pre-flight diagnostics, cleans caches if needed, checks for available updates, prompts for user confirmation (unless \fB\-y\fR is provided), applies routine package upgrades, and reports reboot status. When \fB\-\-packages\fR is specified, updates only the named packages.
|
||||
.B update \fR[\fB\-\-packages \fIPKG...\fR] [\fB\-\-exclude \fIPATTERN...\fR] [\fB\-\-security\fR] [\fB\-\-flatpak\fR]
|
||||
Runs pre-flight diagnostics, auto-remediates safe issues, checks for available updates, prompts for user confirmation (unless \fB\-y\fR is provided), applies routine package upgrades, and reports reboot status. When \fB\-\-packages\fR is specified, updates only the named packages. When \fB\-\-exclude\fR is specified, skips packages matching the names or glob patterns. When \fB\-\-security\fR is specified, installs only security updates. When \fB\-\-flatpak\fR is specified, updates Flatpak applications after OS packages.
|
||||
.TP
|
||||
.B check
|
||||
.B check \fR[\fB\-\-exclude \fIPATTERN...\fR] [\fB\-\-security\fR]
|
||||
Non-destructively inspects pre-flight health diagnostics and lists all pending package upgrades without modifying system state.
|
||||
.TP
|
||||
.B release\-upgrade \fR[\fB\-t \fITARGET\fR|\fB\-\-target\-release \fITARGET\fR|\fB\-\-releasever \fITARGET\fR]
|
||||
@@ -48,6 +50,9 @@ Cleans the local package cache. When \fB\-\-all\fR is given, also removes unused
|
||||
.TP
|
||||
.B health
|
||||
Runs pre-flight system diagnostics and prints a formatted health report (or JSON with \fB\-\-json\fR) without performing updates.
|
||||
.TP
|
||||
.B completion \fR[\fBbash\fR|\fBzsh\fR]
|
||||
Outputs shell tab completion script to stdout for evaluation or installation into shell profiles.
|
||||
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
@@ -63,8 +68,17 @@ Simulates update operations without altering package states on disk.
|
||||
.B \-\-reboot
|
||||
Automatically reboots the system after a major release upgrade or routine update (if a reboot is required). On Fedora release upgrades, automatically executes offline transaction reboot (\fBdnf5 \-y offline reboot\fR). In interactive mode when this option is omitted, the user is prompted to confirm immediate reboot.
|
||||
.TP
|
||||
.BR \-\-exclude " \fIPATTERN...\fR"
|
||||
Exclude package(s) or glob patterns (e.g. 'kernel*', 'nginx') from update operations.
|
||||
.TP
|
||||
.B \-\-security
|
||||
Restrict update operations strictly to security patches and vulnerability advisories. Supported on RHEL, Fedora, CentOS, Rocky, AlmaLinux, Debian, and Ubuntu.
|
||||
.TP
|
||||
.B \-\-flatpak
|
||||
Execute Flatpak application updates (\fBflatpak update \-y\fR) after OS package manager operations complete.
|
||||
.TP
|
||||
.B \-\-no\-remediation
|
||||
Disables automated remediation actions (such as clearing package caches or unlinking stale locks).
|
||||
Disables automated remediation actions (such as clearing package caches, unlinking stale locks, or repairing interrupted transactions).
|
||||
.TP
|
||||
.B \-\-skip\-preflight
|
||||
Bypasses all pre-flight health diagnostics.
|
||||
@@ -86,11 +100,20 @@ Displays the command-line help summary.
|
||||
.I /etc/linux-updater.json
|
||||
System configuration file containing disk thresholds, behavior switches, and logging directory settings.
|
||||
.TP
|
||||
.I /etc/logrotate.d/linux-updater
|
||||
Logrotate policy rotating updater logs weekly, keeping 4 archives compressed with 0640 permissions.
|
||||
.TP
|
||||
.I /var/log/linux-updater/
|
||||
Standard directory for execution logs conforming to Linux FHS. Each execution creates a timestamped file \fIlinux-updater-YYYYMMDD-HHMMSS.log\fR.
|
||||
.TP
|
||||
.I /var/log/linux-updater/latest.log
|
||||
Atomic symbolic link pointing to the most recent execution log file.
|
||||
.TP
|
||||
.I /usr/share/bash-completion/completions/linux-updater
|
||||
Static Bash command and argument autocompletion definition.
|
||||
.TP
|
||||
.I /usr/share/zsh/site-functions/_linux-updater
|
||||
Static Zsh command and argument autocompletion definition.
|
||||
|
||||
.SH EXIT STATUS
|
||||
.TP
|
||||
@@ -123,6 +146,16 @@ Apply routine updates non-interactively:
|
||||
.B linux-updater \-y update
|
||||
.RE
|
||||
.PP
|
||||
Apply security updates only:
|
||||
.RS
|
||||
.B linux-updater \-y update \-\-security
|
||||
.RE
|
||||
.PP
|
||||
Apply updates excluding kernel packages:
|
||||
.RS
|
||||
.B linux-updater \-y update \-\-exclude "kernel*"
|
||||
.RE
|
||||
.PP
|
||||
Selectively update only the openssl and nginx packages:
|
||||
.RS
|
||||
.B linux-updater \-y update \-\-packages openssl nginx
|
||||
@@ -132,6 +165,11 @@ Simulate major distribution upgrade to target version:
|
||||
.RS
|
||||
.B linux-updater release\-upgrade \-\-dry\-run \-t 41
|
||||
.RE
|
||||
.PP
|
||||
Install shell completions for Bash:
|
||||
.RS
|
||||
.B eval "$(linux-updater completion bash)"
|
||||
.RE
|
||||
|
||||
.SH SEE ALSO
|
||||
.BR apt-get (8),
|
||||
|
||||
@@ -67,7 +67,7 @@ class PackageBuilder:
|
||||
self,
|
||||
source_root: Optional[Path] = None,
|
||||
output_dir: Optional[Path] = None,
|
||||
version: str = "1.3.0",
|
||||
version: str = "2.0.0",
|
||||
) -> None:
|
||||
self.source_root = source_root or Path(__file__).resolve().parent.parent
|
||||
self.output_dir = output_dir or (self.source_root / "dist")
|
||||
@@ -105,6 +105,16 @@ class PackageBuilder:
|
||||
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"))
|
||||
|
||||
# Copy packaging extras (logrotate)
|
||||
if (self.source_root / "packaging" / "logrotate").exists():
|
||||
pkg_dest = tmp_root / "packaging" / "logrotate"
|
||||
pkg_dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copytree(str(self.source_root / "packaging" / "logrotate"), str(pkg_dest))
|
||||
|
||||
# Archive the tree
|
||||
with tarfile.open(str(out_path), "w:gz") as tar:
|
||||
tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}")
|
||||
@@ -151,6 +161,28 @@ class PackageBuilder:
|
||||
man_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(str(self.source_root / "man" / "linux-updater.8"), str(man_dir / "linux-updater.8"))
|
||||
|
||||
if (self.source_root / "completions" / "bash" / "linux-updater").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" / "linux-updater"),
|
||||
str(bash_comp_dir / "linux-updater"),
|
||||
)
|
||||
if (self.source_root / "completions" / "zsh" / "_linux-updater").exists():
|
||||
zsh_comp_dir = data_dir / "usr" / "share" / "zsh" / "vendor-completions"
|
||||
zsh_comp_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(
|
||||
str(self.source_root / "completions" / "zsh" / "_linux-updater"),
|
||||
str(zsh_comp_dir / "_linux-updater"),
|
||||
)
|
||||
if (self.source_root / "packaging" / "logrotate" / "linux-updater").exists():
|
||||
logrotate_dir = data_dir / "etc" / "logrotate.d"
|
||||
logrotate_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(
|
||||
str(self.source_root / "packaging" / "logrotate" / "linux-updater"),
|
||||
str(logrotate_dir / "linux-updater"),
|
||||
)
|
||||
|
||||
# If dpkg-deb is available, use it; otherwise build native .deb
|
||||
if shutil.which("dpkg-deb"):
|
||||
pkg_tree = root / "deb_tree"
|
||||
@@ -211,6 +243,12 @@ class PackageBuilder:
|
||||
)
|
||||
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 / "packaging" / "logrotate").exists():
|
||||
pkg_dest = tmp_root / "packaging" / "logrotate"
|
||||
pkg_dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copytree(str(self.source_root / "packaging" / "logrotate"), str(pkg_dest))
|
||||
with tarfile.open(str(tarball_path), "w:gz") as tar:
|
||||
tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}")
|
||||
|
||||
|
||||
@@ -39,4 +39,23 @@ if [ -f "${SCRIPT_DIR}/man/linux-updater.8" ]; then
|
||||
install -m 644 "${SCRIPT_DIR}/man/linux-updater.8" "${PREFIX}/share/man/man8/linux-updater.8"
|
||||
fi
|
||||
|
||||
# Install shell completions
|
||||
if [ -f "${SCRIPT_DIR}/completions/bash/linux-updater" ]; then
|
||||
mkdir -p "${PREFIX}/share/bash-completion/completions"
|
||||
install -m 644 "${SCRIPT_DIR}/completions/bash/linux-updater" "${PREFIX}/share/bash-completion/completions/linux-updater"
|
||||
fi
|
||||
if [ -f "${SCRIPT_DIR}/completions/zsh/_linux-updater" ]; then
|
||||
mkdir -p "${PREFIX}/share/zsh/site-functions"
|
||||
install -m 644 "${SCRIPT_DIR}/completions/zsh/_linux-updater" "${PREFIX}/share/zsh/site-functions/_linux-updater"
|
||||
fi
|
||||
|
||||
# Install logrotate configuration
|
||||
if [ -f "${SCRIPT_DIR}/packaging/logrotate/linux-updater" ]; then
|
||||
mkdir -p "${SYSCONFDIR}/logrotate.d"
|
||||
install -m 644 "${SCRIPT_DIR}/packaging/logrotate/linux-updater" "${SYSCONFDIR}/logrotate.d/linux-updater"
|
||||
elif [ -f "${SCRIPT_DIR}/logrotate/linux-updater" ]; then
|
||||
mkdir -p "${SYSCONFDIR}/logrotate.d"
|
||||
install -m 644 "${SCRIPT_DIR}/logrotate/linux-updater" "${SYSCONFDIR}/logrotate.d/linux-updater"
|
||||
fi
|
||||
|
||||
echo "Installation complete! Run 'linux-updater --help' to verify."
|
||||
@@ -0,0 +1,8 @@
|
||||
/var/log/linux-updater/*.log {
|
||||
weekly
|
||||
rotate 4
|
||||
compress
|
||||
missingok
|
||||
notifempty
|
||||
create 0640 root root
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: linux-updater
|
||||
Version: 1.3.0
|
||||
Version: 2.0.0
|
||||
Release: 1%{?dist}
|
||||
Summary: Unified, safe multi-distribution Linux system updater
|
||||
|
||||
@@ -32,20 +32,42 @@ mkdir -p $RPM_BUILD_ROOT/var/log/linux-updater
|
||||
cp -r linux_updater $RPM_BUILD_ROOT/usr/lib/linux-updater/
|
||||
install -m 755 bin/linux-updater $RPM_BUILD_ROOT/usr/bin/linux-updater
|
||||
install -m 644 linux-updater.json.example $RPM_BUILD_ROOT/etc/linux-updater.json
|
||||
mkdir -p $RPM_BUILD_ROOT/etc/logrotate.d
|
||||
if [ -f packaging/logrotate/linux-updater ]; then
|
||||
install -m 644 packaging/logrotate/linux-updater $RPM_BUILD_ROOT/etc/logrotate.d/linux-updater
|
||||
fi
|
||||
mkdir -p $RPM_BUILD_ROOT%{_mandir}/man8
|
||||
if [ -f man/linux-updater.8 ]; then
|
||||
install -m 644 man/linux-updater.8 $RPM_BUILD_ROOT%{_mandir}/man8/linux-updater.8
|
||||
fi
|
||||
mkdir -p $RPM_BUILD_ROOT%{_datadir}/bash-completion/completions
|
||||
mkdir -p $RPM_BUILD_ROOT%{_datadir}/zsh/site-functions
|
||||
if [ -f completions/bash/linux-updater ]; then
|
||||
install -m 644 completions/bash/linux-updater $RPM_BUILD_ROOT%{_datadir}/bash-completion/completions/linux-updater
|
||||
fi
|
||||
if [ -f completions/zsh/_linux-updater ]; then
|
||||
install -m 644 completions/zsh/_linux-updater $RPM_BUILD_ROOT%{_datadir}/zsh/site-functions/_linux-updater
|
||||
fi
|
||||
|
||||
%files
|
||||
%defattr(-,root,root,-)
|
||||
%attr(0755, root, root) /usr/bin/linux-updater
|
||||
/usr/lib/linux-updater
|
||||
%config(noreplace) /etc/linux-updater.json
|
||||
%config(noreplace) /etc/logrotate.d/linux-updater
|
||||
%dir %attr(0750, root, root) /var/log/linux-updater
|
||||
%{_mandir}/man8/linux-updater.8*
|
||||
%{_datadir}/bash-completion/completions/linux-updater
|
||||
%{_datadir}/zsh/site-functions/_linux-updater
|
||||
|
||||
%changelog
|
||||
* Sat Oct 03 2026 Test Factory <admin@localhost> - 2.0.0-1
|
||||
- Shell tab autocompletion for Bash and Zsh (completion subcommand and packaging integration).
|
||||
- Selective package filtering with --exclude (patterns/globs) and --security updates.
|
||||
- Pre-flight package database consistency inspection (check_package_db) with auto-remediation (repair_package_db).
|
||||
- Optional Flatpak integration (--flatpak and update_flatpak config).
|
||||
- Dedicated logrotate configuration (/etc/logrotate.d/linux-updater).
|
||||
|
||||
* Fri Oct 02 2026 Test Factory <admin@localhost> - 1.3.0-1
|
||||
- Add Gitea Actions automated CI/CD pipeline for building RPM, DEB, and tarball packages.
|
||||
- Automated publication to Gitea Package Registry and Gitea Release Assets.
|
||||
|
||||
@@ -464,6 +464,55 @@ class TestCLIIntegration(unittest.TestCase):
|
||||
res = trigger_system_reboot("arch", is_release_upgrade=False, runner=mock_runner)
|
||||
self.assertFalse(res)
|
||||
|
||||
@patch("linux_updater.cli.check_root_privileges", return_value=True)
|
||||
@patch("linux_updater.cli.DistroDetector.detect")
|
||||
@patch("linux_updater.cli.get_manager")
|
||||
@patch("shutil.which")
|
||||
def test_cli_update_with_flatpak(self, mock_which, mock_get_manager, mock_detect, mock_root):
|
||||
mock_detect.return_value = DistroInfo(
|
||||
family=DistroFamily.DEBIAN,
|
||||
distro_id="ubuntu",
|
||||
version_id="24.04",
|
||||
pretty_name="Ubuntu 24.04",
|
||||
)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_lock_files.return_value = []
|
||||
mock_manager.is_reboot_required.return_value = RebootStatus(required=False)
|
||||
mock_manager.apply_updates.return_value = CommandResult(0, "All packages upgraded", "", True)
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
def fake_which(cmd):
|
||||
if cmd == "flatpak":
|
||||
return "/usr/bin/flatpak"
|
||||
return None
|
||||
mock_which.side_effect = fake_which
|
||||
|
||||
with patch("linux_updater.cli.CommandRunner.run") as mock_runner_run:
|
||||
mock_runner_run.return_value = CommandResult(0, "", "", True)
|
||||
code = main(["-y", "update", "--flatpak"])
|
||||
self.assertEqual(code, 0)
|
||||
mock_runner_run.assert_called_with(["flatpak", "update", "-y"])
|
||||
|
||||
@patch("linux_updater.cli.check_root_privileges", return_value=True)
|
||||
@patch("linux_updater.cli.DistroDetector.detect")
|
||||
@patch("linux_updater.cli.get_manager")
|
||||
@patch("shutil.which", return_value=None)
|
||||
def test_cli_update_with_flatpak_missing_binary(self, mock_which, mock_get_manager, mock_detect, mock_root):
|
||||
mock_detect.return_value = DistroInfo(
|
||||
family=DistroFamily.DEBIAN,
|
||||
distro_id="ubuntu",
|
||||
version_id="24.04",
|
||||
pretty_name="Ubuntu 24.04",
|
||||
)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_lock_files.return_value = []
|
||||
mock_manager.is_reboot_required.return_value = RebootStatus(required=False)
|
||||
mock_manager.apply_updates.return_value = CommandResult(0, "All packages upgraded", "", True)
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
code = main(["-y", "update", "--flatpak"])
|
||||
self.assertEqual(code, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,52 @@
|
||||
import io
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
|
||||
from linux_updater.cli import create_parser, main
|
||||
from linux_updater.core.completion import get_bash_completion, get_zsh_completion
|
||||
|
||||
|
||||
class TestCompletion(unittest.TestCase):
|
||||
def test_bash_completion_content(self):
|
||||
content = get_bash_completion()
|
||||
self.assertIn("complete -F _linux_updater linux-updater", content)
|
||||
self.assertIn("update check release-upgrade clean health completion", content)
|
||||
self.assertIn("--packages", content)
|
||||
self.assertIn("--exclude", content)
|
||||
self.assertIn("--security", content)
|
||||
self.assertIn("--flatpak", content)
|
||||
|
||||
def test_zsh_completion_content(self):
|
||||
content = get_zsh_completion()
|
||||
self.assertIn("#compdef linux-updater", content)
|
||||
self.assertIn("_linux_updater", content)
|
||||
self.assertIn("update:Inspect health", content)
|
||||
self.assertIn("completion:Generate shell autocompletion script", content)
|
||||
|
||||
def test_cli_completion_bash_runs_without_root_or_lock(self):
|
||||
f = io.StringIO()
|
||||
with redirect_stdout(f):
|
||||
exit_code = main(["completion", "bash"])
|
||||
self.assertEqual(exit_code, 0)
|
||||
output = f.getvalue()
|
||||
self.assertIn("complete -F _linux_updater linux-updater", output)
|
||||
|
||||
def test_cli_completion_zsh_runs_without_root_or_lock(self):
|
||||
f = io.StringIO()
|
||||
with redirect_stdout(f):
|
||||
exit_code = main(["completion", "zsh"])
|
||||
self.assertEqual(exit_code, 0)
|
||||
output = f.getvalue()
|
||||
self.assertIn("#compdef linux-updater", output)
|
||||
|
||||
def test_static_completion_files_exist(self):
|
||||
root_dir = Path(__file__).resolve().parent.parent
|
||||
bash_file = root_dir / "completions" / "bash" / "linux-updater"
|
||||
zsh_file = root_dir / "completions" / "zsh" / "_linux-updater"
|
||||
|
||||
self.assertTrue(bash_file.exists(), f"Missing {bash_file}")
|
||||
self.assertTrue(zsh_file.exists(), f"Missing {zsh_file}")
|
||||
|
||||
self.assertEqual(bash_file.read_text(encoding="utf-8").strip(), get_bash_completion().strip())
|
||||
self.assertEqual(zsh_file.read_text(encoding="utf-8").strip(), get_zsh_completion().strip())
|
||||
@@ -0,0 +1,72 @@
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from linux_updater.managers.apt import AptManager
|
||||
from linux_updater.managers.dnf import DnfManager
|
||||
from linux_updater.managers.pacman import PacmanManager
|
||||
from linux_updater.models import CommandResult, PackageUpdate
|
||||
|
||||
|
||||
class TestFiltering(unittest.TestCase):
|
||||
def test_apt_exclude_filtering(self):
|
||||
mock_runner = MagicMock()
|
||||
mock_runner.run.return_value = CommandResult(
|
||||
return_code=0,
|
||||
stdout=(
|
||||
"Inst nginx [1.18.0] (1.20.0 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||
"Inst linux-image-generic [5.15.0] (5.15.1 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||
"Inst curl [7.81.0] (7.82.0 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||
),
|
||||
stderr="",
|
||||
success=True,
|
||||
)
|
||||
apt = AptManager(runner=mock_runner)
|
||||
updates = apt.check_updates(exclude=["linux-image-*", "curl"])
|
||||
self.assertEqual(len(updates), 1)
|
||||
self.assertEqual(updates[0].package, "nginx")
|
||||
|
||||
def test_apt_security_only_filtering(self):
|
||||
mock_runner = MagicMock()
|
||||
mock_runner.run.return_value = CommandResult(
|
||||
return_code=0,
|
||||
stdout=(
|
||||
"Inst nginx [1.18.0] (1.20.0 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||
"Inst openssl [3.0.2] (3.0.3 Ubuntu:24.04/noble-security [amd64])\n"
|
||||
),
|
||||
stderr="",
|
||||
success=True,
|
||||
)
|
||||
apt = AptManager(runner=mock_runner)
|
||||
updates = apt.check_updates(security_only=True)
|
||||
self.assertEqual(len(updates), 1)
|
||||
self.assertEqual(updates[0].package, "openssl")
|
||||
|
||||
def test_dnf_exclude_arguments(self):
|
||||
mock_runner = MagicMock()
|
||||
mock_runner.run.return_value = CommandResult(return_code=0, stdout="", stderr="", success=True)
|
||||
dnf = DnfManager(runner=mock_runner, binary="dnf")
|
||||
|
||||
dnf.apply_updates(exclude=["kernel*", "redis*"])
|
||||
cmd = mock_runner.run.call_args[0][0]
|
||||
self.assertIn("-x", cmd)
|
||||
self.assertIn("kernel*", cmd)
|
||||
self.assertIn("redis*", cmd)
|
||||
|
||||
def test_dnf_security_only_arguments(self):
|
||||
mock_runner = MagicMock()
|
||||
mock_runner.run.return_value = CommandResult(return_code=0, stdout="", stderr="", success=True)
|
||||
dnf = DnfManager(runner=mock_runner, binary="dnf")
|
||||
|
||||
dnf.apply_updates(security_only=True)
|
||||
cmd = mock_runner.run.call_args[0][0]
|
||||
self.assertIn("--security", cmd)
|
||||
|
||||
def test_pacman_exclude_arguments(self):
|
||||
mock_runner = MagicMock()
|
||||
mock_runner.run.return_value = CommandResult(return_code=0, stdout="", stderr="", success=True)
|
||||
pacman = PacmanManager(runner=mock_runner)
|
||||
|
||||
pacman.apply_updates(exclude=["linux", "systemd"])
|
||||
cmd = mock_runner.run.call_args[0][0]
|
||||
self.assertIn("--ignore", cmd)
|
||||
self.assertIn("linux,systemd", cmd)
|
||||
@@ -18,7 +18,7 @@ class TestPackaging(unittest.TestCase):
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.out_dir = Path(self.temp_dir.name)
|
||||
self.root_dir = Path(__file__).resolve().parent.parent
|
||||
self.builder = PackageBuilder(source_root=self.root_dir, output_dir=self.out_dir, version="1.3.0")
|
||||
self.builder = PackageBuilder(source_root=self.root_dir, output_dir=self.out_dir, version="2.0.0")
|
||||
|
||||
def tearDown(self):
|
||||
self.temp_dir.cleanup()
|
||||
@@ -35,6 +35,7 @@ class TestPackaging(unittest.TestCase):
|
||||
self.assertTrue(any("linux_updater/__init__.py" in n for n in names))
|
||||
self.assertTrue(any("linux-updater.json.example" in n for n in names))
|
||||
self.assertTrue(any("linux-updater.8" in n for n in names))
|
||||
self.assertTrue(any("logrotate" in n for n in names))
|
||||
|
||||
def test_build_deb_creates_package_or_tree(self):
|
||||
deb_path = self.builder.build_deb()
|
||||
@@ -55,6 +56,7 @@ class TestPackaging(unittest.TestCase):
|
||||
self.assertIn("Name: linux-updater", content)
|
||||
self.assertIn("Requires: python3 >= 3.6", content)
|
||||
self.assertIn("BuildArch: noarch", content)
|
||||
self.assertIn("/etc/logrotate.d/linux-updater", content)
|
||||
|
||||
def test_build_all(self):
|
||||
results = self.builder.build_all()
|
||||
|
||||
@@ -51,15 +51,20 @@ class TestRemediationEngine(unittest.TestCase):
|
||||
if lock_p.exists():
|
||||
lock_p.unlink()
|
||||
|
||||
def test_remediate_refuses_non_remediable(self):
|
||||
def test_remediate_repair_package_db(self):
|
||||
check = CheckResult(
|
||||
name="disk_boot",
|
||||
name="package_db",
|
||||
status=CheckStatus.FAIL,
|
||||
message="/boot is full",
|
||||
can_remediate=False,
|
||||
message="Unconfigured packages detected",
|
||||
can_remediate=True,
|
||||
remediation_id="repair_package_db",
|
||||
)
|
||||
self.assertFalse(self.engine.can_remediate(check))
|
||||
self.assertFalse(self.engine.remediate(check))
|
||||
self.assertTrue(self.engine.can_remediate(check))
|
||||
self.mock_manager.repair_db.return_value = MagicMock(success=True)
|
||||
success = self.engine.remediate(check)
|
||||
self.assertTrue(success)
|
||||
self.mock_manager.repair_db.assert_called_once()
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user