feat(pkgcheck): vérification des mises à jour au démarrage sans mdp + notif

Le mode headless --check-updates (QT Core uniquement) synchro checkupdates
sans root, classe les paquets critiques (noyau, glibc, systemd, graphics),
envoie une notif urgente via notify-send quand c'est nécessaire, et installe
soi-même son service systemd --user (paramètre actif par défaut) pour
lancer la vérification à chaque ouverture de session. Ajout de tests
d'unité et de doc.

Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
BlackAngelTVandCodebuff committed 2026-10-04 20:02:41 +02:00
1 parent ed8185d5fe
commit 65b3496b42
9 files changed
+819 -2

No files matched your search

+15 -2
View File
@@ -31,6 +31,8 @@ set(SOURCES
src/history-manager.cpp
src/package-model.cpp
src/update-manager.cpp
# Headless pass run at login by the systemd unit the app installs itself.
src/startup-check.cpp
src/app-logging.cpp
# Logic layer: background workers, the plugin shop and the controller the
# screens delegate to.
@@ -59,6 +61,7 @@ set(HEADERS
include/history-manager.h
include/package-model.h
include/update-manager.h
include/startup-check.h
include/app-logging.h
include/workers.h
include/progress-tracker.h
@@ -188,10 +191,10 @@ add_test(NAME aur-manager-test COMMAND aur-manager-test)
add_executable(app-core-test tests/app-core.test.cpp
src/app-core.cpp src/workers.cpp src/pacman-manager.cpp
src/plugin-manager.cpp src/history-manager.cpp src/update-manager.cpp
src/plugin-shop.cpp
src/plugin-shop.cpp src/startup-check.cpp
src/app-logging.cpp src/log-manager.cpp
include/app-core.h include/workers.h include/update-manager.h
include/plugin-shop.h include/log-manager.h)
include/startup-check.h include/plugin-shop.h include/log-manager.h)
target_include_directories(app-core-test PRIVATE include)
target_link_libraries(app-core-test PRIVATE Qt6::Core Qt6::Network)
target_compile_definitions(app-core-test PRIVATE
@@ -206,6 +209,16 @@ target_compile_definitions(update-manager-test PRIVATE
FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}")
add_test(NAME update-manager-test COMMAND update-manager-test)
# StartupCheck: the pure half (parsing, critical/reboot classification,
# notification text) and the autostart files, driven inside a temporary tree so
# the user's own ~/.config is never touched.
add_executable(startup-check-test tests/startup-check.test.cpp
src/startup-check.cpp src/log-manager.cpp src/app-logging.cpp
include/startup-check.h include/log-manager.h)
target_include_directories(startup-check-test PRIVATE include)
target_link_libraries(startup-check-test PRIVATE Qt6::Core)
add_test(NAME startup-check-test COMMAND startup-check-test)
# ---- Plugins ----
#
# Flatpak ships as an external provider plugin (not compiled into the binary):
+12
View File
@@ -168,6 +168,18 @@ public:
// when the update cannot run (no method available).
bool applySelfUpdate(const QString& sudoPassword, QString* error);
// ---- Startup update check ----
// Whether the app installs its login check: a systemd user unit that runs
// `PacManager --check-updates` and pops a notification when updates are
// pending — no window, no sudo password. On by default, since the point is
// to warn the user without them opening the app.
bool checkUpdatesAtStartup() const;
void setCheckUpdatesAtStartup(bool enabled);
// Refreshes the installed unit when the setting is on, in case the binary
// moved since it was written. Idempotent; called once at window startup so
// an update of the app keeps the login check pointing at the real file.
void ensureStartupAutostart();
// ---- pacman's database lock ----
bool databaseLocked() const;
// What currently holds the lock, so the view can name the process it offers
+1
View File
@@ -211,4 +211,5 @@ private:
// Menu
QAction* m_credLaunchAction = nullptr;
QAction* m_credEachTimeAction = nullptr;
QAction* m_startupCheckAction = nullptr;
};
+118
View File
@@ -0,0 +1,118 @@
#pragma once
#include <QObject>
#include <QString>
#include <QStringList>
// The headless pass that answers "does this machine have pending updates?" and,
// when it does, raises a desktop notification.
//
// It exists because the graphical window is not running when the machine
// starts: the app installs a systemd user unit (see the autostart helpers here)
// that runs `PacManager --check-updates` at login, and that call lands here.
//
// Two guarantees drive the implementation:
// - no password: the check goes through `checkupdates` (pacman-contrib), which
// syncs into a throwaway database and therefore needs no root, instead of a
// `pacman -Sy` the login unit could never authenticate;
// - no display: everything here is Qt Core only, so the unit runs with no
// DISPLAY, no Wayland socket and no widget.
//
// The pure parts (parsing, classification, notification text, unit contents)
// are static so they are unit-tested without a package manager, a network or a
// session bus.
class StartupCheck : public QObject {
Q_OBJECT
public:
// Outcome of one check, so the caller (and the tests) can inspect what
// happened without parsing console output.
struct Result {
int updateCount = 0;
bool anyCritical = false; // kernel, glibc, init, graphics stack...
bool rebootRequired = false; // a kernel or its firmware is pending
QStringList packages;
// Non-empty when the check failed, or when it could only run in a
// degraded way (the pacman -Qu fallback, which reads a database only
// root can refresh). Never a reason to skip the notification.
QString error;
};
explicit StartupCheck(QObject* parent = nullptr);
// Runs the whole headless pass (check, then notify when something is
// pending) and returns the exit code for main(). Always 0: a background
// check that fails must not fill the user's journal with failed units.
int run();
// ---- Pure helpers (unit-tested) ----
// Parses the checked tool's output. `checkupdates` prints
// "name oldver -> newver" and `pacman -Qu` prints "name newver"; only the
// package name is needed and it is the first whitespace-separated token of
// every line, so one parser accepts both. Duplicates are dropped.
static QStringList parseUpdates(const QString& output);
// A package whose update deserves an urgent notification rather than the
// ordinary one: the kernel and its firmware, the C library and init, the
// graphics stack, pacman itself — the updates that either need a reboot or
// can break the session when they fall behind. Prefix-based on purpose: a
// package nobody thought about simply gets the normal notification.
static bool isCritical(const QString& package);
// A package whose update only takes effect after a reboot: the kernel and
// the out-of-tree driver built against the running one.
static bool isRebootRequired(const QString& package);
// The critical subset of a list, so the notification can name what matters.
static QStringList criticalPackages(const QStringList& packages);
// Notification title and body for a set of pending updates.
static QString notificationTitle(const Result& result);
static QString notificationBody(const Result& result);
// ---- Check and notify (touch the machine) ----
// Pending updates, using `checkupdates` when available and falling back to
// the already-synced `pacman -Qu` otherwise. Never needs root; the fallback
// reads a database only root can refresh, so it may miss updates — which is
// what `error` records rather than hiding.
static Result check();
// Sends the notification through notify-send, waiting briefly for the
// notification daemon (the login unit can start before mako). Returns false
// when nothing could be sent.
static bool notify(const Result& result);
// ---- Autostart: a systemd user unit the app installs itself ----
// The unit lives under `configDir` (XDG_CONFIG_HOME, i.e. ~/.config) and is
// enabled by a symlink in default.target.wants, which is the per-user
// equivalent of `systemctl --user enable` without shelling out to it.
// Passing the directory lets the unit test drive install/remove inside a
// temporary tree instead of the user's own ~/.config.
static QString autostartUnitPath(const QString& configDir);
static QString autostartWantsPath(const QString& configDir);
// Writes the unit and the enabling symlink. `program` is the binary to run
// with --check-updates (the running executable, so it follows the install
// wherever it is). Filesystem only: no systemd call, so tests stay hermetic.
static bool installAutostart(const QString& configDir, const QString& program,
QString* error = nullptr);
static bool removeAutostart(const QString& configDir, QString* error = nullptr);
static bool autostartEnabled(const QString& configDir);
// Asks the user's systemd manager to re-read its units, so a fresh install
// takes effect without waiting for the next boot. Best effort; a system
// without a running user manager (a test, a container) is not an error.
static bool reloadUserManager();
private:
// Runs a tool to completion, returning its stdout. stderr is kept out of it
// on purpose: a pacman warning is not a package name, so folding the two
// would feed the parser lines it must not see — `stderrText` receives them
// for the error message instead. `exitCode` receives the status, or -1 when
// the process could not be started or timed out.
static QString runTool(const QString& program, const QStringList& args,
int timeoutMs, int* exitCode, QString* stderrText = nullptr);
// Waits (bounded) for the session's notification daemon, then sends through
// notify-send with the given urgency.
static bool sendNotification(const QString& title, const QString& body, bool urgent);
};
+82
View File
@@ -1,7 +1,10 @@
#include "app-core.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QStandardPaths>
#include <QTimer>
#include <algorithm>
@@ -14,6 +17,7 @@
#include "app-logging.h"
#include "log-manager.h"
#include "plugin-shop.h"
#include "startup-check.h"
#include "workers.h"
namespace {
@@ -1242,6 +1246,84 @@ bool AppCore::applySelfUpdate(const QString& sudoPassword, QString* error) {
return true;
}
// ---------------------------------------------------------------------------
// Startup update check
// ---------------------------------------------------------------------------
namespace {
// Directory the systemd user unit is written under. GenericConfigLocation is
// ~/.config, honouring XDG_CONFIG_HOME, which is exactly where systemd looks.
QString userConfigDir() {
QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
if (dir.isEmpty()) dir = QDir::homePath() + "/.config";
return dir;
}
} // namespace
bool AppCore::checkUpdatesAtStartup() const {
return m_settings.value("updates/checkAtStartup", true).toBool();
}
void AppCore::setCheckUpdatesAtStartup(bool enabled) {
m_settings.setValue("updates/checkAtStartup", enabled);
const QString configDir = userConfigDir();
QString error;
if (enabled) {
// The unit runs the executable that is doing the installing, so the
// check follows an app installed anywhere (~/.local/bin, /usr/bin...).
const QString program =
UpdateManager::restartProgram(QCoreApplication::applicationDirPath());
if (program.isEmpty() ||
!StartupCheck::installAutostart(configDir, program, &error)) {
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("autostart des mises à jour impossible : %1")
.arg(error.isEmpty() ? QStringLiteral("binaire introuvable") : error));
emit statusMessage(QStringLiteral("Impossible d'installer la vérification au démarrage."));
return;
}
StartupCheck::reloadUserManager();
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("vérification des mises à jour au démarrage activée"));
emit statusMessage(QStringLiteral(
"Vérification des mises à jour au démarrage activée (notification à l'ouverture de session)."));
} else {
StartupCheck::removeAutostart(configDir, &error);
StartupCheck::reloadUserManager();
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("vérification des mises à jour au démarrage désactivée"));
emit statusMessage(QStringLiteral("Vérification des mises à jour au démarrage désactivée."));
}
}
void AppCore::ensureStartupAutostart() {
if (!checkUpdatesAtStartup()) return;
const QString program =
UpdateManager::restartProgram(QCoreApplication::applicationDirPath());
if (program.isEmpty()) return;
const QString configDir = userConfigDir();
const bool wasEnabled = StartupCheck::autostartEnabled(configDir);
// Rewriting the unit on every launch keeps the executable path current (the
// app may have moved), but only a fresh install needs systemd to be told.
QString error;
if (!StartupCheck::installAutostart(configDir, program, &error)) {
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("autostart des mises à jour non installé : %1").arg(error));
return;
}
if (!wasEnabled) StartupCheck::reloadUserManager();
}
// ---------------------------------------------------------------------------
// pacman's database lock
// ---------------------------------------------------------------------------
+18
View File
@@ -404,6 +404,10 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
if (m_core->shouldCheckForAppUpdate()) {
QTimer::singleShot(1500, this, &MainWindow::onCheckForUpdates);
}
// Keep the login check's unit in sync with where this binary actually lives
// (an update may have moved it). Silent and idempotent.
m_core->ensureStartupAutostart();
}
MainWindow::~MainWindow() = default;
@@ -750,6 +754,20 @@ void MainWindow::setupMenuBar() {
connect(m_credLaunchAction, &QAction::triggered, this,
[this]() { applyCredentialMode(AppCore::CredentialMode::AtLaunch); });
// The login check: the core installs (or removes) the systemd user unit that
// runs the headless pass, so the setting is what makes the feature exist on
// the machine — nothing to configure by hand.
settingsMenu->addSeparator();
m_startupCheckAction = settingsMenu->addAction("Vérifier les mises à jour au démarrage");
m_startupCheckAction->setCheckable(true);
m_startupCheckAction->setChecked(m_core->checkUpdatesAtStartup());
m_startupCheckAction->setToolTip(
"Prévient par une notification à l'ouverture de session quand des mises à jour "
"sont disponibles — sans mot de passe. Installe le service utilisateur associé.");
connect(m_startupCheckAction, &QAction::toggled, this, [this](bool enabled) {
m_core->setCheckUpdatesAtStartup(enabled);
});
QMenu* helpMenu = menuBar->addMenu("Aide");
helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates);
helpMenu->addSeparator();
+20
View File
@@ -1,13 +1,33 @@
#include <QApplication>
#include <QCoreApplication>
#include <QLoggingCategory>
#include <QStringList>
#include <QTimer>
#include <cstring>
#include "log-manager.h"
#include "main-window.h"
#include "startup-check.h"
#include "update-manager.h"
int main(int argc, char* argv[]) {
// The login check runs headless, from the systemd user unit the app installs
// itself (Paramètres → « Vérifier les mises à jour au démarrage »). It is
// detected before any QApplication: that unit has no display, and building a
// GUI application there would abort on the platform plugin.
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--check-updates") == 0) {
QCoreApplication app(argc, argv);
app.setApplicationName("PacManager");
app.setApplicationVersion(UpdateManager::currentVersion());
app.setOrganizationName("Freebuff");
QLoggingCategory::setFilterRules(QStringLiteral("pacmgr.*=true"));
LogManager::installQtMessageHandler();
return StartupCheck().run();
}
}
QApplication app(argc, argv);
app.setApplicationName("PacManager");
app.setApplicationVersion(UpdateManager::currentVersion());
+347
View File
@@ -0,0 +1,347 @@
#include "startup-check.h"
#include "log-manager.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <QStandardPaths>
#include <QThread>
#include <QtGlobal>
#include <initializer_list>
namespace {
// Package prefixes that make an update worth interrupting the user for. Kept
// short and documented: widening it is a judgement call, not a bug fix.
bool startsWithAny(const QString& name, std::initializer_list<const char*> prefixes) {
for (const char* prefix : prefixes) {
if (name.startsWith(QLatin1String(prefix))) return true;
}
return false;
}
bool toolExists(const QString& program) {
return !QStandardPaths::findExecutable(program).isEmpty();
}
} // namespace
StartupCheck::StartupCheck(QObject* parent) : QObject(parent) {}
// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------
QStringList StartupCheck::parseUpdates(const QString& output) {
QStringList packages;
const QStringList lines = output.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
for (const QString& line : lines) {
// "linux 6.9.1.arch1-1 -> 6.9.2.arch1-1" (checkupdates) and
// "linux 6.9.2.arch1-1" (pacman -Qu) share the same head: the first
// whitespace-separated token is the package name.
const QStringList tokens = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
if (tokens.isEmpty()) continue;
packages << tokens.first();
}
packages.removeDuplicates();
return packages;
}
bool StartupCheck::isCritical(const QString& package) {
return startsWithAny(package, {
"linux", // the kernel itself, its headers and its firmware
"glibc", // everything links against it
"systemd", // init and its libraries
"mesa", // graphics stack: a broken update loses the session
"nvidia", // out-of-tree driver built against the running kernel
"xorg-server",
"wayland",
"pacman", // a broken pacman leaves no way to repair
"openssl",
});
}
bool StartupCheck::isRebootRequired(const QString& package) {
// Only the kernel (and its firmware, which "linux" also covers) plus the
// out-of-tree graphics driver built against the running kernel leave the
// system on the old code until it restarts.
return startsWithAny(package, {"linux", "nvidia"});
}
QStringList StartupCheck::criticalPackages(const QStringList& packages) {
QStringList critical;
for (const QString& package : packages) {
if (isCritical(package)) critical << package;
}
return critical;
}
QString StartupCheck::notificationTitle(const Result& result) {
if (result.rebootRequired) return QStringLiteral("Mise à jour du noyau disponible");
if (result.anyCritical) return QStringLiteral("Mises à jour importantes disponibles");
return QStringLiteral("Mises à jour disponibles");
}
QString StartupCheck::notificationBody(const Result& result) {
const int count = result.updateCount;
QString body = count == 1 ? QStringLiteral("1 mise à jour disponible.")
: QStringLiteral("%1 mises à jour disponibles.").arg(count);
// Name the critical packages, but keep the bubble readable: a system with a
// pending toolchain refresh can have a dozen of them.
const QStringList critical = criticalPackages(result.packages);
if (!critical.isEmpty()) {
const int shown = qMin(critical.size(), 5);
QStringList listed = critical.mid(0, shown);
if (critical.size() > shown) listed << QStringLiteral("…");
body += QStringLiteral("\nPaquets sensibles : %1.").arg(listed.join(QStringLiteral(", ")));
}
body += result.rebootRequired
? QStringLiteral("\nUn redémarrage sera nécessaire après l'installation.")
: QStringLiteral("\nOuvrez PacManager pour les installer.");
return body;
}
// ---------------------------------------------------------------------------
// Check
// ---------------------------------------------------------------------------
QString StartupCheck::runTool(const QString& program, const QStringList& args,
int timeoutMs, int* exitCode, QString* stderrText) {
if (exitCode) *exitCode = -1;
if (stderrText) stderrText->clear();
QProcess process;
// Separate channels: stdout is the package list, stderr is diagnostics. A
// merged stream would turn "warning: database file..." into a package name.
process.setProcessChannelMode(QProcess::SeparateChannels);
process.start(program, args);
if (!process.waitForStarted(5000)) return {};
const bool finished = process.waitForFinished(timeoutMs);
if (!finished) {
process.kill();
process.waitForFinished(2000);
}
const QString out = QString::fromUtf8(process.readAllStandardOutput());
if (stderrText) *stderrText = QString::fromUtf8(process.readAllStandardError()).trimmed();
if (exitCode) *exitCode = finished ? process.exitCode() : -1;
return out;
}
StartupCheck::Result StartupCheck::check() {
Result result;
QString output;
QString stderrText;
int code = 0;
if (toolExists(QStringLiteral("checkupdates"))) {
// checkupdates refreshes a throwaway copy of the databases, so it needs
// no root and cannot leave the real database half-synced. It exits 0
// with updates, 2 when there is nothing to do, and anything else on a
// real failure (no network, broken database...).
output = runTool(QStringLiteral("checkupdates"), {}, 120000, &code, &stderrText);
if (code != 0 && code != 2) {
result.error = stderrText.isEmpty()
? QStringLiteral("checkupdates a échoué (code %1).").arg(code)
: QStringLiteral("checkupdates a échoué (code %1) : %2")
.arg(code).arg(stderrText);
return result;
}
} else if (toolExists(QStringLiteral("pacman"))) {
// Fallback: read the already-synced database. It needs no root either,
// but it only knows what the last `pacman -Sy` saw, so it can miss
// updates — which `error` records rather than hiding.
output = runTool(QStringLiteral("pacman"), {QStringLiteral("-Qu")}, 30000, &code,
&stderrText);
// pacman -Qu exits 1 when nothing matches (= no update at all).
if (code != 0 && code != 1) {
result.error = stderrText.isEmpty()
? QStringLiteral("pacman -Qu a échoué (code %1).").arg(code)
: QStringLiteral("pacman -Qu a échoué (code %1) : %2").arg(code).arg(stderrText);
return result;
}
result.error = QStringLiteral(
"checkupdates est absent (paquet pacman-contrib) : les mises à jour "
"peuvent être manquées tant que la base n'est pas synchronisée.");
} else {
result.error = QStringLiteral("Ni checkupdates ni pacman n'est disponible.");
return result;
}
result.packages = parseUpdates(output);
result.updateCount = result.packages.size();
for (const QString& package : result.packages) {
result.anyCritical = result.anyCritical || isCritical(package);
result.rebootRequired = result.rebootRequired || isRebootRequired(package);
}
return result;
}
int StartupCheck::run() {
const Result result = check();
if (!result.error.isEmpty()) {
LogManager::instance().logEvent(QStringLiteral("maj-verif"), result.error);
}
LogManager::instance().logEvent(
QStringLiteral("maj-verif"),
result.updateCount == 0
? QStringLiteral("aucune mise à jour en attente")
: QStringLiteral("%1 mise(s) à jour en attente : %2")
.arg(result.updateCount)
.arg(result.packages.join(QStringLiteral(", "))));
if (result.updateCount > 0) {
notify(result);
}
return 0;
}
// ---------------------------------------------------------------------------
// Notification
// ---------------------------------------------------------------------------
bool StartupCheck::sendNotification(const QString& title, const QString& body, bool urgent) {
if (!toolExists(QStringLiteral("notify-send"))) return false;
QStringList args{QStringLiteral("-a"), QStringLiteral("PacManager")};
if (urgent) {
// A critical notification that never times out: the user should not be
// able to miss a pending kernel update.
args << QStringLiteral("-u") << QStringLiteral("critical")
<< QStringLiteral("-t") << QStringLiteral("0");
} else {
args << QStringLiteral("-t") << QStringLiteral("10000");
}
args << title << body;
// A login unit can beat the notification daemon (mako, dunst...) to the
// session bus, in which case the first sends fail. Retry for a few seconds
// instead of dropping the notification silently.
for (int attempt = 0; attempt < 30; ++attempt) {
QProcess process;
process.start(QStringLiteral("notify-send"), args);
if (process.waitForStarted(3000) && process.waitForFinished(5000) &&
process.exitCode() == 0) {
return true;
}
QThread::msleep(1000);
}
return false;
}
bool StartupCheck::notify(const Result& result) {
if (result.updateCount <= 0) return false;
const bool urgent = result.rebootRequired || result.anyCritical;
const bool sent = sendNotification(notificationTitle(result),
notificationBody(result), urgent);
LogManager::instance().logEvent(
QStringLiteral("maj-verif"),
sent ? QStringLiteral("notification envoyée")
: QStringLiteral("notification impossible (aucun démon de notification)"));
return sent;
}
// ---------------------------------------------------------------------------
// Autostart
// ---------------------------------------------------------------------------
QString StartupCheck::autostartUnitPath(const QString& configDir) {
if (configDir.isEmpty()) return {};
return configDir + QStringLiteral("/systemd/user/pacmanager-check-updates.service");
}
QString StartupCheck::autostartWantsPath(const QString& configDir) {
if (configDir.isEmpty()) return {};
return configDir +
QStringLiteral("/systemd/user/default.target.wants/pacmanager-check-updates.service");
}
bool StartupCheck::installAutostart(const QString& configDir, const QString& program,
QString* error) {
if (configDir.isEmpty() || program.isEmpty()) {
if (error) *error = QStringLiteral("répertoire de configuration ou programme manquant.");
return false;
}
const QString unitPath = autostartUnitPath(configDir);
const QString wantsPath = autostartWantsPath(configDir);
if (!QDir().mkpath(QFileInfo(unitPath).absolutePath()) ||
!QDir().mkpath(QFileInfo(wantsPath).absolutePath())) {
if (error) *error = QStringLiteral("impossible de créer %1").arg(configDir);
return false;
}
// Quoted because a path may contain spaces; systemd accepts the quotes.
const QString unit = QStringLiteral(
"[Unit]\n"
"Description=PacManager — mises à jour disponibles au démarrage\n"
"Documentation=man:PacManager(1)\n"
"After=network-online.target\n"
"Wants=network-online.target\n"
"\n"
"[Service]\n"
"Type=oneshot\n"
"ExecStart=\"%1\" --check-updates\n"
"\n"
"[Install]\n"
"WantedBy=default.target\n").arg(program);
QFile file(unitPath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate) ||
file.write(unit.toUtf8()) != unit.toUtf8().size()) {
if (error) *error = QStringLiteral("impossible d'écrire %1").arg(unitPath);
return false;
}
file.close();
// The symlink is what `systemctl --user enable` would create; writing it
// directly keeps the install free of any systemd call.
QFile::remove(wantsPath);
if (!QFile::link(unitPath, wantsPath)) {
if (error) *error = QStringLiteral("impossible de créer le lien %1").arg(wantsPath);
return false;
}
return true;
}
bool StartupCheck::removeAutostart(const QString& configDir, QString* error) {
if (configDir.isEmpty()) {
if (error) *error = QStringLiteral("répertoire de configuration manquant.");
return false;
}
QFile::remove(autostartWantsPath(configDir));
QFile::remove(autostartUnitPath(configDir));
return true;
}
bool StartupCheck::autostartEnabled(const QString& configDir) {
const QString wantsPath = autostartWantsPath(configDir);
if (wantsPath.isEmpty()) return false;
const QFileInfo info(wantsPath);
// A symlink whose target is missing would report exists() == false, so the
// link itself is checked too: a stale link is still an installed setting.
return info.isSymLink() || info.exists();
}
bool StartupCheck::reloadUserManager() {
if (!toolExists(QStringLiteral("systemctl"))) return false;
QProcess process;
process.start(QStringLiteral("systemctl"),
{QStringLiteral("--user"), QStringLiteral("daemon-reload")});
if (!process.waitForStarted(3000)) return false;
return process.waitForFinished(10000) && process.exitCode() == 0;
}
+206
View File
@@ -0,0 +1,206 @@
// Unit tests for StartupCheck: parsing of the two update-check formats, the
// critical / reboot-required classification, the notification text, and the
// autostart unit — the last one written inside a temporary directory, never the
// user's own ~/.config.
#include <cassert>
#include <iostream>
#include <QFile>
#include <QFileInfo>
#include <QString>
#include <QTemporaryDir>
#include "startup-check.h"
// ---------------------------------------------------------------------------
// parseUpdates
// ---------------------------------------------------------------------------
static void testParseUpdates_checkupdatesFormat() {
// What `checkupdates` prints: name, current version, "->", new version.
const QString output =
"linux 6.9.1.arch1-1 -> 6.9.2.arch1-1\n"
"firefox 127.0-1 -> 128.0-1\n";
const QStringList packages = StartupCheck::parseUpdates(output);
assert(packages.size() == 2);
assert(packages.at(0) == "linux");
assert(packages.at(1) == "firefox");
}
static void testParseUpdates_pacmanFormat() {
// What `pacman -Qu` prints: name then the *new* version, no arrow.
const QString output = "glibc 2.39-3\nvlc 3.0.21-1\n";
const QStringList packages = StartupCheck::parseUpdates(output);
assert(packages.size() == 2);
assert(packages.at(0) == "glibc");
assert(packages.at(1) == "vlc");
}
static void testParseUpdates_ignoresBlanksAndDuplicates() {
const QString output = "\n\nlinux 6.9-1\n\nlinux 6.9-1\n";
const QStringList packages = StartupCheck::parseUpdates(output);
assert(packages.size() == 1);
assert(packages.at(0) == "linux");
}
static void testParseUpdates_emptyOutput() {
assert(StartupCheck::parseUpdates(QString()).isEmpty());
}
// ---------------------------------------------------------------------------
// Classification
// ---------------------------------------------------------------------------
static void testIsCritical_kernelAndCorePackages() {
assert(StartupCheck::isCritical("linux"));
assert(StartupCheck::isCritical("linux-lts"));
assert(StartupCheck::isCritical("linux-firmware"));
assert(StartupCheck::isCritical("glibc"));
assert(StartupCheck::isCritical("systemd"));
assert(StartupCheck::isCritical("systemd-libs"));
assert(StartupCheck::isCritical("mesa"));
assert(StartupCheck::isCritical("nvidia-utils"));
assert(StartupCheck::isCritical("pacman"));
assert(StartupCheck::isCritical("openssl"));
}
static void testIsCritical_ordinaryPackages() {
assert(!StartupCheck::isCritical("firefox"));
assert(!StartupCheck::isCritical("vlc"));
assert(!StartupCheck::isCritical("gimp"));
assert(!StartupCheck::isCritical("git"));
assert(!StartupCheck::isCritical("python"));
}
static void testIsRebootRequired_onlyKernelAndDrivers() {
assert(StartupCheck::isRebootRequired("linux"));
assert(StartupCheck::isRebootRequired("linux-firmware"));
assert(StartupCheck::isRebootRequired("nvidia-utils"));
// Critical because they can break the session, but they take effect on the
// spot: no reboot to ask for.
assert(!StartupCheck::isRebootRequired("glibc"));
assert(!StartupCheck::isRebootRequired("mesa"));
assert(!StartupCheck::isRebootRequired("firefox"));
}
static void testCriticalPackages_returnsOnlyTheMatchingOnes() {
const QStringList all{"firefox", "linux", "vlc", "glibc"};
const QStringList critical = StartupCheck::criticalPackages(all);
assert(critical.size() == 2);
assert(critical.at(0) == "linux");
assert(critical.at(1) == "glibc");
}
// ---------------------------------------------------------------------------
// Notification text
// ---------------------------------------------------------------------------
static void testNotification_kernelUpdateIsUrgent() {
StartupCheck::Result result;
result.packages = {"linux", "glibc", "firefox"};
result.updateCount = 3;
result.anyCritical = true;
result.rebootRequired = true;
assert(StartupCheck::notificationTitle(result) == "Mise à jour du noyau disponible");
const QString body = StartupCheck::notificationBody(result);
assert(body.contains("3 mises à jour"));
assert(body.contains("linux, glibc"));
assert(body.contains("redémarrage"));
}
static void testNotification_ordinaryUpdate() {
StartupCheck::Result result;
result.packages = {"firefox"};
result.updateCount = 1;
assert(StartupCheck::notificationTitle(result) == "Mises à jour disponibles");
const QString body = StartupCheck::notificationBody(result);
assert(body.contains("1 mise à jour disponible"));
assert(body.contains("Ouvrez PacManager"));
assert(!body.contains("redémarrage"));
}
static void testNotification_capsTheCriticalPackageList() {
// Eight critical packages must not turn the bubble into a wall of text.
StartupCheck::Result result;
result.packages = {"linux", "linux-lts", "linux-zen", "linux-hardened",
"linux-firmware", "glibc", "systemd", "mesa"};
result.updateCount = 8;
result.anyCritical = true;
result.rebootRequired = true;
const QString body = StartupCheck::notificationBody(result);
assert(body.contains("…"));
assert(!body.contains("mesa"));
}
// ---------------------------------------------------------------------------
// Autostart files
// ---------------------------------------------------------------------------
static void testAutostart_installEnableAndRemove() {
QTemporaryDir dir;
assert(dir.isValid());
const QString configDir = dir.path();
// A space in the path checks the quoting systemd needs.
const QString program = "/opt/Pac Manager/PacManager";
assert(!StartupCheck::autostartEnabled(configDir));
QString error;
assert(StartupCheck::installAutostart(configDir, program, &error));
assert(error.isEmpty());
assert(StartupCheck::autostartEnabled(configDir));
QFile unit(StartupCheck::autostartUnitPath(configDir));
assert(unit.open(QIODevice::ReadOnly));
const QString content = QString::fromUtf8(unit.readAll());
unit.close();
assert(content.contains("\"/opt/Pac Manager/PacManager\" --check-updates"));
assert(content.contains("WantedBy=default.target"));
assert(content.contains("Type=oneshot"));
// The enabling link points back at the unit, which is what makes the login
// manager start it.
const QFileInfo link(StartupCheck::autostartWantsPath(configDir));
assert(link.isSymLink());
assert(StartupCheck::removeAutostart(configDir, &error));
assert(!StartupCheck::autostartEnabled(configDir));
assert(!QFile::exists(StartupCheck::autostartUnitPath(configDir)));
assert(!QFileInfo::exists(StartupCheck::autostartWantsPath(configDir)));
}
static void testAutostart_refusesEmptyInputs() {
assert(StartupCheck::autostartUnitPath(QString()).isEmpty());
assert(StartupCheck::autostartWantsPath(QString()).isEmpty());
QString error;
assert(!StartupCheck::installAutostart(QString(), "/usr/bin/PacManager", &error));
assert(!error.isEmpty());
assert(!StartupCheck::installAutostart("/tmp/does-not-matter", QString(), &error));
assert(!StartupCheck::autostartEnabled(QString()));
}
int main() {
testParseUpdates_checkupdatesFormat();
testParseUpdates_pacmanFormat();
testParseUpdates_ignoresBlanksAndDuplicates();
testParseUpdates_emptyOutput();
testIsCritical_kernelAndCorePackages();
testIsCritical_ordinaryPackages();
testIsRebootRequired_onlyKernelAndDrivers();
testCriticalPackages_returnsOnlyTheMatchingOnes();
testNotification_kernelUpdateIsUrgent();
testNotification_ordinaryUpdate();
testNotification_capsTheCriticalPackageList();
testAutostart_installEnableAndRemove();
testAutostart_refusesEmptyInputs();
std::cout << "All startup-check tests passed." << std::endl;
return 0;
}