From 54bff1636967c181c50e9748badf8b53feda5b52 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Fri, 11 Sep 2026 20:15:41 +0200 Subject: [PATCH] feat(update): self-update from a cloned repo wherever the app is installed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Self-update assumed a conventional install prefix (silently reinstalling into ~/.local when the binary lived elsewhere) and needed a release tarball to do anything. Pick the strategy from what the machine actually has -- a local checkout, git+cmake+compiler for a clone, the prebuilt archive, or the release sources -- and always write the fresh binary next to the running one, building in a temp directory so sudo is only needed for the final copy. Bundles the UI work that depends on it (tray, shortcuts, log filter, CSV exports, cached package details), the structured log categories, and the new test targets (update-manager, AUR, plugins) wired into CTest. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- CMakeLists.txt | 76 ++++- include/app-logging.h | 11 + include/main-window.h | 42 ++- include/update-manager.h | 83 +++++- src/app-logging.cpp | 9 + src/main-window.cpp | 509 +++++++++++++++++++++++++++++----- src/plugin-manager.cpp | 17 +- src/update-manager.cpp | 449 ++++++++++++++++++++++-------- tests/update-manager.test.cpp | 127 +++++++++ 9 files changed, 1123 insertions(+), 200 deletions(-) create mode 100644 include/app-logging.h create mode 100644 src/app-logging.cpp create mode 100644 tests/update-manager.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 76c8631..eef050f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,7 @@ set(SOURCES src/history-manager.cpp src/package-model.cpp src/update-manager.cpp + src/app-logging.cpp resources/resources.qrc ) @@ -31,6 +32,7 @@ set(HEADERS include/history-manager.h include/package-model.h include/update-manager.h + include/app-logging.h ) add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) @@ -48,6 +50,45 @@ add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD # Install install(TARGETS ${PROJECT_NAME} DESTINATION bin) install(FILES version DESTINATION bin) + +# Ship the providers with the install so an installed app keeps its plugins: +# /bin/plugins (next to the binary, first search path) and +# /lib/PacManager/plugins (system-wide search path). +if(FWS_BUILD_FLATPAK_PLUGIN) + install(FILES $ + DESTINATION bin/plugins) + install(FILES $ + DESTINATION lib/PacManager/plugins) +endif() +if(FWS_BUILD_AUR_PLUGIN) + install(FILES $ + DESTINATION bin/plugins) + install(FILES $ + DESTINATION lib/PacManager/plugins) +endif() + +# Desktop entry + icon so the installed app shows up in launchers +# (wofi, GNOME, KDE...). Icon goes to the hicolor theme, desktop file is +# patched with the actual install prefix at install time. +install(FILES resources/icons/package.svg + DESTINATION share/icons/hicolor/scalable/apps + RENAME org.fws.PacManager.svg) +install(CODE " + set(DESKTOP_DIR \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/share/applications\") + file(MAKE_DIRECTORY \"\${DESKTOP_DIR}\") + file(WRITE \"\${DESKTOP_DIR}/org.fws.PacManager.desktop\" +\"[Desktop Entry] +Type=Application +Name=PacManager +GenericName=Package Manager +Comment=Gestionnaire de paquets pour Arch Linux +Exec=${CMAKE_INSTALL_PREFIX}/bin/PacManager +Icon=org.fws.PacManager +Terminal=false +Categories=System;PackageManager;Qt; +StartupNotify=true +\") +") install(DIRECTORY include/ DESTINATION include/${PROJECT_NAME}) # Tests @@ -72,6 +113,19 @@ add_executable(package-utils-test tests/package-utils.test.cpp) target_include_directories(package-utils-test PRIVATE include) add_test(NAME package-utils-test COMMAND package-utils-test) +add_executable(aur-manager-test tests/aur-manager.test.cpp + plugins/aur-provider/aur-manager.cpp) +target_include_directories(aur-manager-test PRIVATE include plugins/aur-provider) +add_test(NAME aur-manager-test COMMAND aur-manager-test) + +# UpdateManager::isNewerVersion is pure logic, but the file also pulls in Qt +# Network, so the test links Core + Network (no display needed). +add_executable(update-manager-test tests/update-manager.test.cpp + src/update-manager.cpp src/app-logging.cpp include/update-manager.h) +target_include_directories(update-manager-test PRIVATE include) +target_link_libraries(update-manager-test PRIVATE Qt6::Core Qt6::Network) +add_test(NAME update-manager-test COMMAND update-manager-test) + # ---- Plugins ---- # # Flatpak ships as an external provider plugin (not compiled into the binary): @@ -81,6 +135,11 @@ add_test(NAME package-utils-test COMMAND package-utils-test) # Flatpak-enabled app; disable with -DFWS_BUILD_FLATPAK_PLUGIN=OFF. option(FWS_BUILD_FLATPAK_PLUGIN "Build the Flatpak provider plugin" ON) +# AUR provider plugin (yay/paru wrapper). Built by default like Flatpak; +# disable with -DFWS_BUILD_AUR_PLUGIN=OFF. Shows "Unavailable" in the Plugins +# page when neither yay nor paru is installed. +option(FWS_BUILD_AUR_PLUGIN "Build the AUR provider plugin" ON) + # Optional example external provider plugin. Demonstrates the plugin mechanism: # the produced library is copied next to the executable and discovered at # runtime by PluginManager (see the Plugins page). @@ -107,6 +166,21 @@ if(FWS_BUILD_FLATPAK_PLUGIN) $/plugins/) endif() +if(FWS_BUILD_AUR_PLUGIN) + add_library(aur-provider-plugin MODULE + plugins/aur-provider/aur-provider.cpp + plugins/aur-provider/aur-manager.cpp) + target_include_directories(aur-provider-plugin PRIVATE include plugins/aur-provider) + set_target_properties(aur-provider-plugin PROPERTIES + OUTPUT_NAME "aur-provider" + CXX_STANDARD 17 + CXX_STANDARD_REQUIRED ON) + add_custom_command(TARGET aur-provider-plugin POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory $/plugins + COMMAND ${CMAKE_COMMAND} -E copy $ + $/plugins/) +endif() + if(FWS_BUILD_EXAMPLE_PLUGIN) add_library(example-provider-plugin MODULE plugins/example-provider/example-provider.cpp) target_include_directories(example-provider-plugin PRIVATE include) @@ -141,7 +215,7 @@ endif() # options. if(FWS_BUILD_EXAMPLE_PLUGIN AND FWS_BUILD_EXAMPLE_ADDON) add_executable(plugin-manager-test tests/plugin-manager.test.cpp - src/plugin-manager.cpp src/pacman-manager.cpp + src/plugin-manager.cpp src/pacman-manager.cpp src/app-logging.cpp plugins/flatpak-provider/flatpak-manager.cpp) target_include_directories(plugin-manager-test PRIVATE include plugins/flatpak-provider) # Qt6::Widgets is linked so the process can load the example addon, which diff --git a/include/app-logging.h b/include/app-logging.h new file mode 100644 index 0000000..690a170 --- /dev/null +++ b/include/app-logging.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +// Structured log categories (P4 quality): use qCDebug/qCInfo/qCWarning with +// these instead of scattering qDebug() so logs can be filtered per area with +// QT_LOGGING_RULES="pacmgr.ui.debug=true" etc. +Q_DECLARE_LOGGING_CATEGORY(pacmgrUi) +Q_DECLARE_LOGGING_CATEGORY(pacmgrOp) +Q_DECLARE_LOGGING_CATEGORY(pacmgrPlugin) +Q_DECLARE_LOGGING_CATEGORY(pacmgrUpdate) diff --git a/include/main-window.h b/include/main-window.h index ba90aea..a068139 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -10,6 +10,8 @@ #include #include #include +#include +#include #include #include @@ -28,6 +30,7 @@ class QListWidgetItem; class QButtonGroup; class QFrame; class QAction; +class QSystemTrayIcon; // Runs a package search off the UI thread. Queries every given provider and // merges the results, tagging each package with its provider id. @@ -104,6 +107,11 @@ private slots: void onNavChanged(int id); void onClearHistory(); void onRefreshLogs(); + void onExportHistory(); + void onExportPackageList(); + void onLogsFilterChanged(); + void onPreviewUpdates(); + void onTrayActivated(QSystemTrayIcon::ActivationReason reason); void onHistoryFilterChanged(); void onInstalledFilterChanged(const QString& text); void onRecentActivityClicked(QListWidgetItem* item); @@ -133,7 +141,16 @@ private: // Show the provider's last error in a dialog when one is available, so a // failed operation explains itself instead of failing silently. - void showProviderError(const QString& title, IPackageManager* provider); + // Returns true when the error was a locked pacman DB (caller may offer + // a retry once the lock is gone). + bool showProviderError(const QString& title, IPackageManager* provider); + + // Re-runs the given privileged action. Used by the "Réessayer" button + // on db-lock errors: the lock (other manager / stale db.lck) is often + // gone by the time the user retries. + void retryPrivilegedAction(const QString& action); + + QString m_pendingRetryAction; void setupUI(); void setupSidebar(); @@ -150,6 +167,7 @@ private: void refreshRecentActivity(); void refreshPluginsTable(); void updatePackageInfo(const PackageInfo& pkg); + std::string richDetails(const PackageInfo& pkg); void resetDetailsPanel(); void setBrowseMode(BrowseMode mode); void performInstall(const std::string& package); @@ -158,11 +176,18 @@ private: void appendPackageRows(const std::vector& results); void addPackageRow(int row, const PackageInfo& pkg); void setBusy(bool busy); + // Single privileged op at a time (pacman DB lock). Returns false + a + // status message when an operation already runs. + bool tryAcquireOp(); void reloadCurrentView(); void loadInstalled(); void loadUpdates(); void refreshHistoryTable(); void loadLogs(); + void applyLogsFilter(); + void setupTray(); + void setupShortcuts(); + void notifyUpdatesAvailable(int count); QFrame* makeCard(); QFrame* makeStatCard(const QString& iconName, const QString& title, QLabel** valueOut); @@ -207,8 +232,10 @@ private: QLabel* m_packageRepo = nullptr; QLabel* m_packageSize = nullptr; QLabel* m_packageProvider = nullptr; - QWidget* m_packageUpdateBadge = nullptr; QLabel* m_packageDescription = nullptr; + // Rich pacman details are cached per package so re-selecting a row (or + // arrowing through the list) does not re-spawn pacman queries. + QHash m_detailsCache; // History page QTableWidget* m_historyTable = nullptr; @@ -217,6 +244,14 @@ private: // Logs page QTextEdit* m_logsText = nullptr; + QLineEdit* m_logsFilter = nullptr; + QString m_logsRaw; + + // Tray (optional: hidden when the desktop has no system tray) + QSystemTrayIcon* m_tray = nullptr; + // Last update count already announced in a tray notification, so repeated + // dashboard refreshes do not spam the user. + int m_lastNotifiedUpdates = -1; // Plugins page QTableWidget* m_pluginTable = nullptr; @@ -231,6 +266,9 @@ private: HistoryManager* m_historyManager = nullptr; UpdateManager* m_updateManager = nullptr; // checks Gitea releases (owned) BrowseMode m_browseMode = ModeSearch; + // True while a privileged op (or blocking load) runs; guards the pacman + // DB lock against concurrent operations from double-clicks. + bool m_busy = false; // Settings QSettings m_settings; diff --git a/include/update-manager.h b/include/update-manager.h index db60058..7724c30 100644 --- a/include/update-manager.h +++ b/include/update-manager.h @@ -9,11 +9,15 @@ // Checks the Gitea repository for new releases and tracks the last check // state in a JSON file so the app only queries the API once per day. -// Self-update works in two modes: -// - source checkout present (dev): git pull + rebuild in place; -// - installed without the repo (~/.local/bin, /usr/...): download the -// release tarball, build it in /tmp and `cmake --install` to the same -// prefix the running binary was installed to (sudo when needed). +// Self-update is location-independent: the fresh binary is always written to +// the directory that holds the running executable, wherever that is +// (~/.local/bin, /usr/bin, an arbitrary extracted folder, a build tree...). +// The strategy is picked by updateMethod(): +// - Checkout: a source checkout around the binary is pulled + rebuilt; +// - Clone: installed without a checkout, the repo is cloned (then pulled) +// into ~/.local/share/PacManager/src, built, and installed in place; +// - Prebuilt: the release's prebuilt archive is unpacked (no compiler); +// - Tarball: the release sources are built and installed in place. // The running binary stays untouched until the next launch. class UpdateManager : public QObject { Q_OBJECT @@ -49,16 +53,52 @@ public: QString tarballUrl() const; QString releasePageUrl() const; - // Install prefix the running binary was installed to (e.g. ~/.local, - // /usr/local, /usr). Used to reinstall the fresh build at the same place. - QString installPrefix() const; + // Prebuilt binary archive attached to the release + // (PacManager--x86_64.tar.gz), when the release workflow + // uploaded one. Used as a fallback when no build toolchain is installed. + QString prebuiltUrl() const; - // Whether a self-update is possible. True when running from a source - // checkout, or when a tarball URL is known (installed mode). + // True when the pending update can be applied by unpacking a prebuilt + // archive instead of recompiling from source. + bool hasPrebuiltUpdate() const; + + // Directory holding the running executable. The update always installs the + // new binary here (in place), so it works whatever the layout on disk. + QString binDir() const; + + // Persistent source clone used to update an installed app that has no + // local checkout (~/.local/share/PacManager/src). The first update clones, + // later ones fast-forward to the latest main. + QString sourceClonePath() const; + + // How the pending update will be applied. Exposed so the UI can describe + // the operation (and offer the releases page when there is no way to + // update locally). + enum class UpdateMethod { None, Checkout, Clone, Prebuilt, Tarball }; + UpdateMethod updateMethod() const; + + // Inputs of the strategy decision, split out so the choice is a pure + // function that can be unit-tested without a network, a filesystem or an + // installed toolchain. + struct UpdateCapabilities { + bool checkoutUsable = false; // a FWS source checkout surrounds the binary + bool hasGit = false; + bool hasCmake = false; + bool hasCompiler = false; + bool hasPrebuilt = false; // the release ships a prebuilt binary archive + bool hasTarball = false; // the release ships a source tarball + }; + static UpdateMethod chooseUpdateMethod(const UpdateCapabilities& capabilities); + + // Human-readable description of the given method and install target, for + // the "update available" dialog. + static QString methodDescription(UpdateMethod method, const QString& targetDir); + + // Whether a self-update is possible with the current state. bool canSelfUpdate() const; // Rebuilds + reinstalls the app in the background. Pass the sudo password - // when the install prefix is not user-writable (empty = no sudo pipe, + // when the target directory is not user-writable (empty = no sudo pipe, // `sudo` will prompt on its own if needed). Emits selfUpdateFinished. void performSelfUpdate(const QString& sudoPassword = QString()); @@ -76,13 +116,32 @@ private: void saveState(const QString& remoteVersion); void loadState(); void runShell(const QString& script, const QString& workingDir); + void performCheckoutUpdate(); + void performCloneUpdate(const QString& sudoPassword); + void performPrebuiltUpdate(const QString& sudoPassword); + void performTarballUpdate(const QString& sudoPassword); + // Shared script header for the installed (no checkout) paths: temp work + // dir, cleanup trap, and the export of the paths the install step needs. + QString installedScriptPrologue() const; + // Copy command that installs a staged tree ($STAGE/bin) into the running + // binary's directory, wrapped in sudo when the target is not writable. + QString installCommand(const QString& quotedPassword, + const QString& action) const; + // Directory holding the installed binary, quoted for the shell. + QString quotedBinDir() const; + static QString quoteShell(const QString& s); + static QString quotedPassword(const QString& sudoPassword); + // Tool lookup cached per process, so the update dialog does not spawn a + // fresh `command -v` for every check. + static bool toolAvailable(const char* tool); + static bool compilerAvailable(); QNetworkAccessManager m_network; QProcess m_process; // runs the git pull + build script QString m_lastCheckDate; // ISO date of the last successful check QString m_lastKnownRemoteVersion; // latest version seen on the server - QString m_latestVersion; // version of the pending update QString m_tarballUrl; // source tarball for the pending update + QString m_prebuiltUrl; // prebuilt binary archive, when attached QString m_releasePageUrl; // human-readable release page QString m_repoPath; // source repo dir when found }; \ No newline at end of file diff --git a/src/app-logging.cpp b/src/app-logging.cpp new file mode 100644 index 0000000..557b8e1 --- /dev/null +++ b/src/app-logging.cpp @@ -0,0 +1,9 @@ +#include "app-logging.h" + +#include + +// Categories are defined once here; the header only declares them. +Q_LOGGING_CATEGORY(pacmgrUi, "pacmgr.ui") +Q_LOGGING_CATEGORY(pacmgrOp, "pacmgr.op") +Q_LOGGING_CATEGORY(pacmgrPlugin, "pacmgr.plugin") +Q_LOGGING_CATEGORY(pacmgrUpdate, "pacmgr.update") diff --git a/src/main-window.cpp b/src/main-window.cpp index d5e6ce0..70cb968 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -26,8 +26,17 @@ #include #include #include +#include +#include +#include +#include +#include +#include + +#include "app-logging.h" #include +#include // Worker threads SearchWorker::SearchWorker(const std::vector& providers, @@ -138,6 +147,14 @@ static QLabel* makeBadge(const QString& text, const QString& bg, const QString& return badge; } +// Closes a popen() stream. A named deleter avoids the GCC warning about the +// function-pointer attributes carried by decltype(&pclose) being dropped. +struct PipeCloser { + void operator()(FILE* file) const { + if (file) pclose(file); + } +}; + // Load one of the embedded SVG icons (see resources/resources.qrc). static QIcon loadIcon(const QString& name) { return QIcon(QString(":/icons/%1.svg").arg(name)); @@ -171,6 +188,25 @@ static QString providersLabel(const PluginManager* pm, const PackageInfo& pkg) { return names.join(", "); } +// Quote a CSV field when it contains the separator, a quote or a newline, so +// exported lists stay importable in a spreadsheet. +static QString csvField(const QString& value) { + if (!value.contains(';') && !value.contains('"') && !value.contains('\n')) { + return value; + } + QString escaped = value; + escaped.replace(QLatin1String("\""), QLatin1String("\"\"")); + return QLatin1Char('"') + escaped + QLatin1Char('"'); +} + +// Human-readable status of a package row, shared by the table and the export. +static QString packageStatusText(const PackageInfo& pkg) { + if (pkg.installed && pkg.updateAvailable) return QStringLiteral("MAJ dispo"); + if (pkg.installed) return QStringLiteral("Installé"); + if (!pkg.repository.empty()) return QStringLiteral("Disponible"); + return QStringLiteral("—"); +} + // MainWindow implementation MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { // Workers emit std::vector from another thread (QThread::run); @@ -195,6 +231,8 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { setupUI(); setupMenuBar(); + setupTray(); + setupShortcuts(); // Addon plugins get the main window so they can attach their own UI // (status-bar widgets, toolbar buttons, ...). Only enabled+available @@ -723,6 +761,11 @@ void MainWindow::setupBrowsePage() { connect(m_updateAllButton, &QPushButton::clicked, this, &MainWindow::onUpdateAll); actionBar->addWidget(m_updateAllButton); + QPushButton* exportBtn = new QPushButton("Exporter"); + exportBtn->setToolTip("Exporter la liste affichée en CSV"); + connect(exportBtn, &QPushButton::clicked, this, &MainWindow::onExportPackageList); + actionBar->addWidget(exportBtn); + actionBar->addStretch(); m_resultCount = new QLabel(""); @@ -803,21 +846,6 @@ void MainWindow::setupBrowsePage() { "padding: 3px 12px; font-size: 12px;"); metaRow->addWidget(m_packageProvider); - // "Update available" badge with an SVG arrow + text. - m_packageUpdateBadge = new QWidget(); - m_packageUpdateBadge->setStyleSheet("background: #3d2f0f; border-radius: 9px;"); - QHBoxLayout* updLayout = new QHBoxLayout(m_packageUpdateBadge); - updLayout->setContentsMargins(9, 2, 9, 2); - updLayout->setSpacing(5); - QLabel* updIcon = new QLabel(); - updIcon->setPixmap(iconPixmap("arrow-up", 12)); - updLayout->addWidget(updIcon); - QLabel* updText = new QLabel("Mise à jour disponible"); - updText->setStyleSheet("font-size: 11px; font-weight: 600; color: #e0af68; background: transparent;"); - updLayout->addWidget(updText); - m_packageUpdateBadge->setVisible(false); - metaRow->addWidget(m_packageUpdateBadge); - metaRow->addStretch(); detailsLayout->addLayout(metaRow); @@ -884,6 +912,11 @@ void MainWindow::setupHistoryPage() { QHBoxLayout* buttonBar = new QHBoxLayout(); buttonBar->addStretch(); + QPushButton* exportBtn = new QPushButton("Exporter (CSV)"); + exportBtn->setToolTip("Enregistrer l'historique affiché dans un fichier CSV"); + connect(exportBtn, &QPushButton::clicked, this, &MainWindow::onExportHistory); + buttonBar->addWidget(exportBtn); + QPushButton* clearBtn = new QPushButton("Effacer l'historique"); clearBtn->setProperty("variant", "danger"); clearBtn->setIcon(loadIcon("trash")); @@ -901,6 +934,22 @@ void MainWindow::setupLogsPage() { layout->setContentsMargins(24, 20, 24, 20); layout->setSpacing(12); + // Filter row: /var/log/pacman.log can be huge, so the content is read once + // into m_logsRaw and filtered in memory (no re-read per keystroke). + QHBoxLayout* filterRow = new QHBoxLayout(); + filterRow->setSpacing(10); + + m_logsFilter = new QLineEdit(); + m_logsFilter->setPlaceholderText("Filtrer les logs (paquet, action, date)..."); + m_logsFilter->setMinimumHeight(36); + m_logsFilter->setClearButtonEnabled(true); + m_logsFilter->addAction(loadIcon("filter"), QLineEdit::LeadingPosition); + connect(m_logsFilter, &QLineEdit::textChanged, + this, &MainWindow::onLogsFilterChanged); + filterRow->addWidget(m_logsFilter, 1); + + layout->addLayout(filterRow); + m_logsText = new QTextEdit(); m_logsText->setReadOnly(true); layout->addWidget(m_logsText, 1); @@ -1026,6 +1075,10 @@ void MainWindow::setupMenuBar() { ); QMenu* fileMenu = menuBar->addMenu("Fichier"); + fileMenu->addAction("Exporter la liste affichée...", this, + &MainWindow::onExportPackageList); + fileMenu->addAction("Exporter l'historique...", this, &MainWindow::onExportHistory); + fileMenu->addSeparator(); fileMenu->addAction("Quitter", this, &QWidget::close); QMenu* toolsMenu = menuBar->addMenu("Outils"); @@ -1040,6 +1093,7 @@ void MainWindow::setupMenuBar() { toolsMenu->addAction("Logs pacman", this, [this]() { m_navGroup->button(5)->click(); }); toolsMenu->addAction("Plugins", this, [this]() { m_navGroup->button(6)->click(); }); toolsMenu->addSeparator(); + toolsMenu->addAction("Prévisualiser les mises à jour", this, &MainWindow::onPreviewUpdates); toolsMenu->addAction("Rafraîchir les sources", this, &MainWindow::onRefresh); QMenu* settingsMenu = menuBar->addMenu("Paramètres"); @@ -1146,11 +1200,51 @@ IPackageManager* MainWindow::providerFor(const std::string& id) const { return available.empty() ? nullptr : available.front(); } -void MainWindow::showProviderError(const QString& title, IPackageManager* provider) { - if (!provider) return; +bool MainWindow::showProviderError(const QString& title, IPackageManager* provider) { + if (!provider) return false; std::string err = provider->lastError(); - if (!err.empty()) { + if (err.empty()) return false; + const bool dbLock = err.find("verrouillée") != std::string::npos + || err.find("db.lck") != std::string::npos; + if (!dbLock) { QMessageBox::warning(this, title, QString::fromStdString(err)); + return false; + } + // Locked DB: explain + offer a retry, since the other manager (or stale + // lock) is often gone by the time the user clicks again. + QMessageBox box(this); + box.setWindowTitle(title); + box.setIcon(QMessageBox::Warning); + box.setText(QString::fromStdString(err)); + box.setInformativeText("Fermez l'autre gestionnaire (ou supprimez le " + "fichier résiduel indiqué), puis réessayez."); + QPushButton* retryBtn = box.addButton("Réessayer", QMessageBox::AcceptRole); + box.addButton("Fermer", QMessageBox::RejectRole); + box.exec(); + if (box.clickedButton() == retryBtn && !m_pendingRetryAction.isEmpty()) { + const QString action = m_pendingRetryAction; + m_pendingRetryAction.clear(); + // Defer so the dialog closes before the worker touches the UI. + QTimer::singleShot(0, this, [this, action] { retryPrivilegedAction(action); }); + } else { + m_pendingRetryAction.clear(); + } + return true; +} + +void MainWindow::retryPrivilegedAction(const QString& action) { + if (action == "install" && !m_selectedPackage.name.empty()) { + m_pendingSelect = m_selectedPackage.name; + performInstall(m_selectedPackage.name); + } else if (action == "remove" && !m_selectedPackage.name.empty()) { + m_pendingSelect = m_selectedPackage.name; + performRemove(m_selectedPackage.name); + } else if (action == "update-all") { + onUpdateAll(); + } else if (action == "refresh") { + onRefresh(); + } else if (action == "update" && !m_selectedPackage.name.empty()) { + onUpdate(); } } @@ -1228,6 +1322,7 @@ void MainWindow::updatePageTitle() { } void MainWindow::onNavChanged(int id) { + qCDebug(pacmgrUi) << "navigate to page" << id; updatePageTitle(); switch (id) { @@ -1283,7 +1378,6 @@ void MainWindow::resetDetailsPanel() { m_packageRepo->setText("—"); m_packageSize->setText("—"); m_packageProvider->setText("—"); - m_packageUpdateBadge->setVisible(false); m_packageDescription->setText(""); m_installButton->setEnabled(false); m_removeButton->setEnabled(false); @@ -1532,9 +1626,94 @@ void MainWindow::updatePackageInfo(const PackageInfo& pkg) { : QString("Taille : %1").arg(QString::fromStdString(pkg.size))); m_packageProvider->setText( QString("Fournisseur : %1").arg(providersLabel(m_pluginManager, pkg))); - m_packageUpdateBadge->setVisible(pkg.updateAvailable); - m_packageDescription->setText(QString::fromStdString(pkg.description)); + // Rich details: dependencies, required-by, install date (pacman), update + // size estimate for pending updates. Loaded on demand so selecting a row + // stays instant even when pacman is slow. + QString details = QString::fromStdString(pkg.description); + const std::string rich = m_pacman ? richDetails(pkg) : std::string(); + if (!rich.empty()) { + if (!details.isEmpty()) details += "\n\n"; + details += QString::fromStdString(rich); + } + m_packageDescription->setText(details); +} + +// Runs the read-only pacman queries backing the details panel. Kept +// synchronous: -Qi/-Si answer in milliseconds and the panel already updated +// the basics above, so no worker thread is worth the complexity. +std::string MainWindow::richDetails(const PackageInfo& pkg) { + if (!m_pacman || !m_pacman->isAvailable()) return {}; + + // Cache per name+provider+version+installed: selecting a row repeatedly (or + // arrowing through the table) must not re-spawn pacman every time. + const QString key = QStringLiteral("%1|%2|%3|%4") + .arg(QString::fromStdString(pkg.name), + QString::fromStdString(pkg.provider), + QString::fromStdString(pkg.version)) + .arg(pkg.installed ? 1 : 0); + const auto cached = m_detailsCache.constFind(key); + if (cached != m_detailsCache.constEnd()) return cached.value(); + + auto run = [](const std::string& cmd) { + std::array buf{}; + std::string out; + std::unique_ptr pipe(popen(cmd.c_str(), "r")); + if (!pipe) return out; + while (fgets(buf.data(), buf.size(), pipe.get())) out += buf.data(); + return out; + }; + auto field = [&](const std::string& out, const std::string& name) { + std::istringstream iss(out); + std::string line; + while (std::getline(iss, line)) { + size_t colon = line.find(':'); + if (colon == std::string::npos) continue; + std::string key = line.substr(0, colon); + while (!key.empty() && key.back() == ' ') key.pop_back(); + if (key != name) continue; + std::string val = line.substr(colon + 1); + size_t start = val.find_first_not_of(" \t"); + if (start != std::string::npos) val = val.substr(start); + while (!val.empty() && (val.back() == '\n' || val.back() == '\r' || val.back() == ' ')) + val.pop_back(); + return val; + } + return std::string(); + }; + + const bool isPacmanPkg = pkg.provider == "pacman" || pkg.provider.empty(); + const std::string q = pkg.provider == "aur" ? "yay -Qi " : "pacman -Qi "; + const std::string s = pkg.provider == "aur" ? "yay -Si " : "pacman -Si "; + std::string installed = run(q + pkg.name + " 2>/dev/null"); + if (installed.empty() && isPacmanPkg) installed = run("pacman -Qi " + pkg.name + " 2>/dev/null"); + + std::string out; + auto addRow = [&](const char* label, const std::string& val) { + if (val.empty() || val == "None" || val == "--") return; + if (!out.empty()) out += "\n"; + out += std::string(label) + " : " + val; + }; + if (!installed.empty()) { + addRow("Taille installée", field(installed, "Installed Size")); + addRow("Date d'installation", field(installed, "Install Date")); + addRow("Dépend de", field(installed, "Depends On")); + addRow("Requis par", field(installed, "Required By")); + } else { + // Only query the sync database when the package is not installed here, + // halving the subprocess count on the Installed/Updates pages. + const std::string sync = run(s + pkg.name + " 2>/dev/null"); + if (!sync.empty()) { + addRow("Taille du téléchargement", field(sync, "Download Size")); + addRow("Taille installée", field(sync, "Installed Size")); + addRow("Dépend de", field(sync, "Depends On")); + } + } + + // Bound the cache so a long browsing session cannot grow it forever. + if (m_detailsCache.size() > 512) m_detailsCache.clear(); + m_detailsCache.insert(key, out); + return out; } void MainWindow::onInstall() { @@ -1552,9 +1731,14 @@ void MainWindow::onUpdate() { IPackageManager* provider = providerFor(m_selectedPackage.provider); if (!provider || !provider->canUpdate()) return; - if (!ensureCredentials({provider})) return; + if (!tryAcquireOp()) return; + m_pendingRetryAction = "update"; + if (!ensureCredentials({provider})) { + setBusy(false); + m_pendingRetryAction.clear(); + return; + } - setBusy(true); statusBar()->showMessage( QString("Mise à jour de %1...").arg(QString::fromStdString(m_selectedPackage.name))); @@ -1586,9 +1770,14 @@ void MainWindow::onUpdateAll() { statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); return; } - if (!ensureCredentials(providers)) return; + if (!tryAcquireOp()) return; + m_pendingRetryAction = "update-all"; + if (!ensureCredentials(providers)) { + setBusy(false); + m_pendingRetryAction.clear(); + return; + } - setBusy(true); statusBar()->showMessage("Mise à jour de tous les paquets..."); auto* worker = new InstallWorker(providers, InstallWorker::Op::UpdateAll); @@ -1604,8 +1793,8 @@ void MainWindow::onUpdateAll() { statusBar()->showMessage("Erreur lors de la mise à jour globale"); for (IPackageManager* pm : providers) { if (!pm->lastError().empty()) { - QMessageBox::warning(this, "Erreur lors de la mise à jour globale", - QString::fromStdString(pm->lastError())); + // showProviderError offers a retry for db-lock errors. + showProviderError("Erreur lors de la mise à jour globale", pm); break; } } @@ -1624,9 +1813,14 @@ void MainWindow::onRefresh() { statusBar()->showMessage("Aucun gestionnaire de paquets disponible."); return; } - if (!ensureCredentials(providers)) return; + if (!tryAcquireOp()) return; + m_pendingRetryAction = "refresh"; + if (!ensureCredentials(providers)) { + setBusy(false); + m_pendingRetryAction.clear(); + return; + } - setBusy(true); statusBar()->showMessage("Rafraîchissement des sources..."); auto* worker = new InstallWorker(providers, InstallWorker::Op::Refresh); @@ -1642,8 +1836,7 @@ void MainWindow::onRefresh() { statusBar()->showMessage("Erreur lors du rafraîchissement"); for (IPackageManager* pm : providers) { if (!pm->lastError().empty()) { - QMessageBox::warning(this, "Erreur lors du rafraîchissement", - QString::fromStdString(pm->lastError())); + showProviderError("Erreur lors du rafraîchissement", pm); break; } } @@ -1658,9 +1851,16 @@ void MainWindow::onRefresh() { void MainWindow::performInstall(const std::string& package) { IPackageManager* provider = providerFor(m_selectedPackage.provider); if (!provider || !provider->canInstall()) return; - if (!ensureCredentials({provider})) return; + qCInfo(pacmgrOp) << "install" << QString::fromStdString(package) + << "via" << QString::fromStdString(provider->getName()); + if (!tryAcquireOp()) return; + m_pendingRetryAction = "install"; + if (!ensureCredentials({provider})) { + setBusy(false); + m_pendingRetryAction.clear(); + return; + } - setBusy(true); statusBar()->showMessage( QString("Installation de %1...").arg(QString::fromStdString(package))); @@ -1694,9 +1894,16 @@ void MainWindow::performInstall(const std::string& package) { void MainWindow::performRemove(const std::string& package) { IPackageManager* provider = providerFor(m_selectedPackage.provider); if (!provider || !provider->canRemove()) return; - if (!ensureCredentials({provider})) return; + qCInfo(pacmgrOp) << "remove" << QString::fromStdString(package) + << "via" << QString::fromStdString(provider->getName()); + if (!tryAcquireOp()) return; + m_pendingRetryAction = "remove"; + if (!ensureCredentials({provider})) { + setBusy(false); + m_pendingRetryAction.clear(); + return; + } - setBusy(true); statusBar()->showMessage( QString("Suppression de %1...").arg(QString::fromStdString(package))); @@ -1728,6 +1935,9 @@ void MainWindow::performRemove(const std::string& package) { } void MainWindow::reloadCurrentView() { + // Installed state changed: drop the cached pacman details so the panel + // shows the fresh size/date after an install/remove/update. + m_detailsCache.clear(); if (m_browseMode == ModeInstalled) { loadInstalled(); } else if (m_browseMode == ModeUpdates) { @@ -1738,6 +1948,7 @@ void MainWindow::reloadCurrentView() { } void MainWindow::setBusy(bool busy) { + m_busy = busy; m_progressBar->setVisible(busy); m_installProgressBar->setVisible(busy); if (busy) { @@ -1750,6 +1961,18 @@ void MainWindow::setBusy(bool busy) { } } +// Single privileged pacman operation at a time: pacman locks its DB +// (/var/lib/pacman/db.lck), so a second concurrent op would fail with +// "verrouillage de la base de données impossible". +bool MainWindow::tryAcquireOp() { + if (m_busy) { + statusBar()->showMessage("Une opération est déjà en cours, patientez..."); + return false; + } + setBusy(true); + return true; +} + // A real download percentage reported by the provider fills the bottom bar as // a determinate progress. -1 (unknown) leaves the bar in its previous state. void MainWindow::onInstallProgress(int percent) { @@ -1821,6 +2044,7 @@ void MainWindow::loadLogs() { QFile logFile(logPath); if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + m_logsRaw.clear(); m_logsText->setPlainText( QString("Impossible d'ouvrir %1.\n" "Vérifiez que le fichier existe et que vous avez les droits de lecture.") @@ -1828,7 +2052,32 @@ void MainWindow::loadLogs() { return; } - m_logsText->setPlainText(QString::fromUtf8(logFile.readAll())); + m_logsRaw = QString::fromUtf8(logFile.readAll()); + applyLogsFilter(); +} + +void MainWindow::onLogsFilterChanged() { + applyLogsFilter(); +} + +// Renders m_logsRaw, keeping only the lines matching the filter box. Filtering +// in memory keeps typing instant even with a multi-megabyte pacman.log. +void MainWindow::applyLogsFilter() { + if (!m_logsText) return; + const QString needle = m_logsFilter ? m_logsFilter->text().trimmed() : QString(); + if (needle.isEmpty()) { + m_logsText->setPlainText(m_logsRaw); + } else { + QString filtered; + const QStringList lines = m_logsRaw.split(QLatin1Char('\n')); + for (const QString& line : lines) { + if (line.contains(needle, Qt::CaseInsensitive)) { + filtered += line; + filtered += QLatin1Char('\n'); + } + } + m_logsText->setPlainText(filtered); + } m_logsText->moveCursor(QTextCursor::End); } @@ -1869,6 +2118,12 @@ void MainWindow::refreshDashboard() { m_statUpdates->setStyleSheet(r.empty() ? QString() : QString("color: #e0af68;")); + // Notify once per distinct count, so the periodic dashboard refresh + // does not re-pop the tray message. + if (static_cast(r.size()) != m_lastNotifiedUpdates) { + m_lastNotifiedUpdates = static_cast(r.size()); + notifyUpdatesAvailable(static_cast(r.size())); + } }); connect(upd, &ListWorker::finished, this, [upd] { upd->wait(); upd->deleteLater(); }); upd->start(); @@ -2135,6 +2390,143 @@ void MainWindow::refreshPluginsTable() { // Starts an update check against the Gitea releases API. Used both at launch // (once per day) and from the Aide menu. +// --------------------------------------------------------------------------- +// System tray: optional, only created when the desktop actually provides one. +// Offers quick access to the pending updates from outside the window. +// --------------------------------------------------------------------------- +void MainWindow::setupTray() { + if (!QSystemTrayIcon::isSystemTrayAvailable()) return; + + m_tray = new QSystemTrayIcon(loadIcon("package"), this); + m_tray->setToolTip("PacManager"); + + QMenu* menu = new QMenu(this); + menu->addAction("Afficher PacManager", this, [this]() { + showNormal(); + raise(); + activateWindow(); + }); + menu->addSeparator(); + menu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates); + menu->addAction("Prévisualiser les mises à jour", this, &MainWindow::onPreviewUpdates); + menu->addAction("Tout mettre à jour", this, &MainWindow::onUpdateAll); + menu->addSeparator(); + menu->addAction("Quitter", this, &QWidget::close); + m_tray->setContextMenu(menu); + + connect(m_tray, &QSystemTrayIcon::activated, this, &MainWindow::onTrayActivated); + m_tray->show(); +} + +void MainWindow::onTrayActivated(QSystemTrayIcon::ActivationReason reason) { + // A click on the icon brings the window back from the background. + if (reason != QSystemTrayIcon::Trigger && reason != QSystemTrayIcon::DoubleClick) { + return; + } + showNormal(); + raise(); + activateWindow(); +} + +void MainWindow::notifyUpdatesAvailable(int count) { + if (!m_tray || count <= 0) return; + m_tray->showMessage("PacManager", + QString("%1 mise(s) à jour disponible(s)").arg(count), + QSystemTrayIcon::Information, 5000); +} + +// Keyboard shortcuts for the actions used most often. +void MainWindow::setupShortcuts() { + auto bind = [this](const QKeySequence& key, const std::function& action) { + QShortcut* shortcut = new QShortcut(key, this); + shortcut->setContext(Qt::WindowShortcut); + connect(shortcut, &QShortcut::activated, this, action); + }; + + bind(QKeySequence::Find, [this]() { + m_navGroup->button(1)->click(); + m_searchBar->setFocus(); + m_searchBar->selectAll(); + }); + bind(QKeySequence::Refresh, [this]() { onRefresh(); }); + bind(QKeySequence(Qt::Key_F5), [this]() { onRefresh(); }); + bind(QKeySequence(QStringLiteral("Ctrl+U")), [this]() { + m_navGroup->button(3)->click(); + }); + bind(QKeySequence(QStringLiteral("Ctrl+E")), [this]() { onExportPackageList(); }); + bind(QKeySequence::Quit, [this]() { close(); }); +} + +// Shows the pending updates without applying anything: jumps to the updates +// page, which lists every outdated package across the active providers. +void MainWindow::onPreviewUpdates() { + m_navGroup->button(3)->click(); + statusBar()->showMessage("Prévisualisation des mises à jour disponibles"); +} + +// Exports the currently displayed package list (search / installed / updates) +// to a semicolon-separated CSV usable in a spreadsheet. +void MainWindow::onExportPackageList() { + if (m_currentResults.empty()) { + statusBar()->showMessage("Aucune liste à exporter."); + return; + } + const QString path = QFileDialog::getSaveFileName( + this, "Exporter la liste des paquets", + QDir::homePath() + "/pacmanager-paquets.csv", "CSV (*.csv)"); + if (path.isEmpty()) return; + + QFile file(path); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { + QMessageBox::warning(this, "Export", + QString("Impossible d'écrire dans %1").arg(path)); + return; + } + QTextStream out(&file); + out << "Nom;Version;Depot;Fournisseur;Statut\n"; + for (const auto& pkg : m_currentResults) { + out << csvField(QString::fromStdString(pkg.name)) << ';' + << csvField(QString::fromStdString(pkg.version)) << ';' + << csvField(QString::fromStdString(pkg.repository)) << ';' + << csvField(providersLabel(m_pluginManager, pkg)) << ';' + << csvField(packageStatusText(pkg)) << '\n'; + } + statusBar()->showMessage( + QString("%1 paquet(s) exporté(s) vers %2") + .arg(static_cast(m_currentResults.size())).arg(path)); +} + +// Exports the recorded action history to CSV. +void MainWindow::onExportHistory() { + const auto& history = m_historyManager->getHistory(); + if (history.empty()) { + statusBar()->showMessage("Historique vide."); + return; + } + const QString path = QFileDialog::getSaveFileName( + this, "Exporter l'historique", + QDir::homePath() + "/pacmanager-historique.csv", "CSV (*.csv)"); + if (path.isEmpty()) return; + + QFile file(path); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { + QMessageBox::warning(this, "Export", + QString("Impossible d'écrire dans %1").arg(path)); + return; + } + QTextStream out(&file); + out << "Date;Action;Paquet;Gestionnaire;Statut\n"; + for (const auto& entry : history) { + out << csvField(QString::fromStdString(entry.timestamp)) << ';' + << csvField(QString::fromStdString(entry.action)) << ';' + << csvField(QString::fromStdString(entry.package)) << ';' + << csvField(QString::fromStdString(entry.plugin)) << ';' + << (entry.success ? "Succes" : "Echec") << '\n'; + } + statusBar()->showMessage( + QString("Historique exporté vers %1").arg(path)); +} + void MainWindow::onCheckForUpdates() { statusBar()->showMessage("Vérification des mises à jour..."); connect(m_updateManager, &UpdateManager::checkFinished, @@ -2162,9 +2554,12 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers } // Ask the user whether to update now or skip. The update runs in the - // background (git pull + rebuild from a checkout, or tarball download + - // rebuild + reinstall when installed); the running binary stays - // untouched until the next launch. + // background (git pull from a checkout, clone + rebuild, prebuilt unpack, + // or tarball rebuild); the running binary stays untouched until the next + // launch. + const UpdateManager::UpdateMethod method = m_updateManager->updateMethod(); + const QString targetDir = m_updateManager->binDir(); + QMessageBox box(this); box.setWindowTitle("Mise à jour disponible"); box.setIcon(QMessageBox::Information); @@ -2175,24 +2570,12 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers QPushButton* updateBtn = box.addButton("Mettre à jour", QMessageBox::AcceptRole); box.addButton("Plus tard", QMessageBox::RejectRole); - - if (!m_updateManager->canSelfUpdate()) { - // No source checkout and no tarball URL: fall back to the releases - // page instead of a disabled button. + if (method == UpdateManager::UpdateMethod::None) { + // No local way to update: offer the releases page instead of a button + // that would immediately fail. updateBtn->setText("Ouvrir la page des releases"); - box.setInformativeText( - "Le dépôt source n'est pas disponible sur ce système.\n" - "Téléchargez la nouvelle version depuis la page des releases."); - } else if (m_updateManager->repoPath().isEmpty()) { - // Installed mode: tarball download + local build + reinstall to the - // same prefix (sudo only for system prefixes). - box.setInformativeText( - QString("La mise à jour va télécharger les sources, les compiler " - "et réinstaller l'application dans %1.\n" - "Redémarrez PacManager ensuite pour utiliser la nouvelle version.") - .arg(m_updateManager->installPrefix())); } - + box.setInformativeText(UpdateManager::methodDescription(method, targetDir)); box.exec(); if (box.clickedButton() != updateBtn) { @@ -2200,23 +2583,21 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers return; } - if (!m_updateManager->canSelfUpdate()) { + if (method == UpdateManager::UpdateMethod::None) { QDesktopServices::openUrl(QUrl(m_updateManager->releasePageUrl())); return; } - // System prefixes (/usr, /usr/local) need sudo for `cmake --install`. - // Prompt once for the password; user prefixes install without sudo. + // Prompt for the sudo password only when the update must write into a + // root-owned directory (e.g. /usr/bin). Only the final copy is privileged: + // everything else builds in a temp directory owned by the user. QString sudoPassword; - const QString prefix = m_updateManager->installPrefix(); - const bool prefixWritable = - QFileInfo(prefix).isWritable() || QFileInfo(prefix + "/bin").isWritable(); - if (m_updateManager->repoPath().isEmpty() && !prefixWritable + if (m_updateManager->repoPath().isEmpty() && !QFileInfo(targetDir).isWritable() && m_pacman && m_pacman->isAvailable()) { bool ok = false; sudoPassword = QInputDialog::getText( this, "Mise à jour", - QString("Mot de passe sudo pour installer dans %1 :").arg(prefix), + QString("Mot de passe sudo pour installer dans %1 :").arg(targetDir), QLineEdit::Password, QString(), &ok); if (!ok) { statusBar()->showMessage("Mise à jour annulée."); @@ -2224,6 +2605,8 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers } } + qCInfo(pacmgrUpdate) << "applying update, method" << static_cast(method) + << "target" << targetDir; statusBar()->showMessage("Mise à jour en cours en arrière-plan..."); connect(m_updateManager, &UpdateManager::selfUpdateFinished, this, &MainWindow::onSelfUpdateFinished); diff --git a/src/plugin-manager.cpp b/src/plugin-manager.cpp index 73ce644..3ee839b 100644 --- a/src/plugin-manager.cpp +++ b/src/plugin-manager.cpp @@ -1,16 +1,25 @@ #include "plugin-manager.h" +#include "app-logging.h" #include #include #include // Plugin directories, checked in order. Bundled plugins ship next to the -// executable; user plugins live under the standard data directory so they -// survive application updates. +// executable (/bin/plugins after install); user plugins live under +// the standard data directory so they survive application updates. static QStringList pluginSearchPaths() { QStringList paths; paths << QCoreApplication::applicationDirPath() + "/plugins"; paths << QDir::homePath() + "/.local/share/PacManager/plugins"; + // System-wide plugins: /lib/PacManager/plugins for installs to + // /usr or /usr/local (covers both lib and lib64 layouts). + const QString appDir = QCoreApplication::applicationDirPath(); + QDir prefix(appDir); + if (prefix.dirName() == QLatin1String("bin") && prefix.cdUp()) { + paths << prefix.absoluteFilePath("lib/PacManager/plugins"); + paths << prefix.absoluteFilePath("lib64/PacManager/plugins"); + } return paths; } @@ -59,6 +68,8 @@ bool PluginManager::loadPluginFile(const QString& filePath) { // as long as the addon/manager instance created from it exists. QLibrary* library = new QLibrary(filePath); if (!library->load()) { + qCWarning(pacmgrPlugin) << "not a loadable plugin, skipping" << filePath + << library->errorString(); delete library; return false; } @@ -124,6 +135,8 @@ bool PluginManager::loadPluginFile(const QString& filePath) { info.available = manager->isAvailable(); m_plugins.push_back({std::move(info), nullptr, manager, library}); } + qCDebug(pacmgrPlugin) << "loaded" << (isAddon ? "addon" : "provider") + << filePath << "available" << m_plugins.back().info.available; return true; } diff --git a/src/update-manager.cpp b/src/update-manager.cpp index 4890bf7..38576bc 100644 --- a/src/update-manager.cpp +++ b/src/update-manager.cpp @@ -1,4 +1,5 @@ #include "update-manager.h" +#include "app-logging.h" #include #include @@ -9,6 +10,7 @@ #include #include #include +#include // Repository base URL used to query the Gitea API for releases. // The app is hosted at https://gitea.nocode-var.tech/FWS/FWS-PacManage. @@ -93,38 +95,127 @@ QString UpdateManager::tarballUrl() const { return m_tarballUrl; } +QString UpdateManager::prebuiltUrl() const { + return m_prebuiltUrl; +} + +bool UpdateManager::hasPrebuiltUpdate() const { + return !m_prebuiltUrl.isEmpty(); +} + QString UpdateManager::releasePageUrl() const { return m_releasePageUrl; } -QString UpdateManager::installPrefix() const { - // Infer the install prefix from the running binary location: - // /bin/PacManager -> . Falls back to ~/.local. - QDir dir(QCoreApplication::applicationDirPath()); - if (dir.dirName() == QLatin1String("bin")) { - dir.cdUp(); - return dir.absolutePath(); +// Cached `command -v` lookup. The update dialog queries several tools on +// every check; caching keeps that from spawning a shell per query. +bool UpdateManager::toolAvailable(const char* tool) { + static QHash cache; + const QString key = QString::fromLatin1(tool); + const auto it = cache.constFind(key); + if (it != cache.constEnd()) return it.value(); + const bool ok = QProcess::execute( + "/bin/sh", {"-c", QString("command -v %1 >/dev/null 2>&1").arg(key)}) == 0; + cache.insert(key, ok); + return ok; +} + +bool UpdateManager::compilerAvailable() { + return toolAvailable("g++") || toolAvailable("c++") || toolAvailable("clang++"); +} + +// Directory holding the running executable. Every install path writes the new +// binary here, so the update follows the user's copy instead of assuming a +// conventional prefix. +QString UpdateManager::binDir() const { + return QCoreApplication::applicationDirPath(); +} + +// ~/.local/share/PacManager/src (honouring XDG_DATA_HOME): the same user data +// directory as the drop-in plugins, so it is writable and independent of where +// the binary itself lives. +QString UpdateManager::sourceClonePath() const { + QString base = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); + if (base.isEmpty()) base = QDir::homePath() + "/.local/share"; + return base + "/PacManager/src"; +} + +// True when the checkout around the binary is usable and points at the FWS +// repo (otherwise we would build someone else's code on the user's machine). +static bool checkoutIsUsable(const QString& repoPath) { + if (repoPath.isEmpty()) return false; + QDir repo(repoPath); + if (!repo.exists(QLatin1String(".git"))) return false; + QFile config(repoPath + "/.git/config"); + if (!config.open(QIODevice::ReadOnly | QIODevice::Text)) return false; + return QString::fromUtf8(config.readAll()) + .contains(QLatin1String("FWS/FWS-PacManage")); +} + +UpdateManager::UpdateMethod UpdateManager::updateMethod() const { + UpdateCapabilities capabilities; + capabilities.checkoutUsable = checkoutIsUsable(m_repoPath); + capabilities.hasGit = toolAvailable("git"); + capabilities.hasCmake = toolAvailable("cmake"); + capabilities.hasCompiler = compilerAvailable(); + capabilities.hasPrebuilt = !m_prebuiltUrl.isEmpty(); + capabilities.hasTarball = !m_tarballUrl.isEmpty(); + return chooseUpdateMethod(capabilities); +} + +// Strategy, in order of preference: +// 1. Checkout: a source checkout is the developer's tree, pull + rebuild it; +// 2. Clone: rebuild from the real sources (git + cmake + compiler present), +// so an installed app follows the repo whatever its location; +// 3. Prebuilt: no toolchain, unpack the release's binary archive; +// 4. Tarball: no git but a compiler, build the release sources. +// Anything else cannot update locally and falls back to the releases page. +UpdateManager::UpdateMethod UpdateManager::chooseUpdateMethod( + const UpdateCapabilities& capabilities) { + if (capabilities.checkoutUsable) return UpdateMethod::Checkout; + if (capabilities.hasGit && capabilities.hasCmake && capabilities.hasCompiler) { + return UpdateMethod::Clone; } - return QDir::homePath() + "/.local"; + if (capabilities.hasPrebuilt) return UpdateMethod::Prebuilt; + if (capabilities.hasTarball && capabilities.hasCmake + && capabilities.hasCompiler) { + return UpdateMethod::Tarball; + } + return UpdateMethod::None; +} + +QString UpdateManager::methodDescription(UpdateMethod method, const QString& targetDir) { + switch (method) { + case UpdateMethod::Checkout: + return QStringLiteral( + "La mise à jour va récupérer le code (git pull), recompiler et " + "réinstaller.\nRedémarrez PacManager ensuite pour utiliser la " + "nouvelle version."); + case UpdateMethod::Clone: + return QStringLiteral( + "La mise à jour va cloner (puis mettre à jour) le dépôt source " + "et recompiler l'application dans %1.\nRedémarrez PacManager " + "ensuite pour utiliser la nouvelle version.").arg(targetDir); + case UpdateMethod::Prebuilt: + return QStringLiteral( + "La mise à jour va télécharger la version précompilée et " + "l'installer dans %1 (sans compilation).\nRedémarrez PacManager " + "ensuite pour utiliser la nouvelle version.").arg(targetDir); + case UpdateMethod::Tarball: + return QStringLiteral( + "La mise à jour va télécharger les sources, les compiler et " + "installer l'application dans %1.\nRedémarrez PacManager " + "ensuite pour utiliser la nouvelle version.").arg(targetDir); + case UpdateMethod::None: + return QStringLiteral( + "Le dépôt source n'est pas disponible sur ce système. " + "Téléchargez la nouvelle version depuis la page des releases."); + } + return {}; } bool UpdateManager::canSelfUpdate() const { - if (!m_repoPath.isEmpty()) { - QDir repo(m_repoPath); - if (!repo.exists(QLatin1String(".git"))) return !m_tarballUrl.isEmpty(); - - // The remote must point to the same FWS repo, otherwise we would build - // someone else's code on the user's machine. - QFile config(m_repoPath + "/.git/config"); - if (config.open(QIODevice::ReadOnly | QIODevice::Text)) { - const QString content = QString::fromUtf8(config.readAll()); - if (content.contains(QLatin1String("FWS/FWS-PacManage"))) { - return true; - } - } - } - // Installed mode: a tarball download + local build needs no git checkout. - return !m_tarballUrl.isEmpty(); + return updateMethod() != UpdateMethod::None; } void UpdateManager::loadState() { @@ -173,6 +264,7 @@ void UpdateManager::checkForUpdates() { reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { + qCWarning(pacmgrUpdate) << "release check failed:" << reply->errorString(); emit checkFinished(false, QString(), QStringLiteral("Impossible de contacter le serveur : %1") .arg(reply->errorString())); @@ -204,18 +296,33 @@ void UpdateManager::checkForUpdates() { tag = tag.mid(1); } - // Prefer an attached source archive; fall back to the auto-generated - // tarball Gitea always provides (releases here ship no assets). + // Prefer the prebuilt binary archive (no compiler needed on the user + // machine); fall back to an attached source archive, then to the + // auto-generated tarball Gitea always provides. QString tarball = obj.value("tarball_url").toString().trimmed(); + QString prebuilt; const QJsonArray assets = obj.value("assets").toArray(); for (const QJsonValue& v : assets) { - const QString dl = v.toObject().value("browser_download_url").toString().trimmed(); - if (dl.endsWith(QLatin1String(".tar.gz")) || dl.endsWith(QLatin1String(".zip"))) { - tarball = dl; + const QJsonObject a = v.toObject(); + const QString name = a.value("name").toString(); + const QString dl = a.value("browser_download_url").toString().trimmed(); + if (name.startsWith(QLatin1String("PacManager-")) + && dl.endsWith(QLatin1String(".tar.gz"))) { + prebuilt = dl; break; } } + if (prebuilt.isEmpty()) { + for (const QJsonValue& v : assets) { + const QString dl = v.toObject().value("browser_download_url").toString().trimmed(); + if (dl.endsWith(QLatin1String(".tar.gz")) || dl.endsWith(QLatin1String(".zip"))) { + tarball = dl; + break; + } + } + } m_tarballUrl = tarball; + m_prebuiltUrl = prebuilt; m_releasePageUrl = obj.value("html_url").toString().trimmed(); if (m_releasePageUrl.isEmpty()) { m_releasePageUrl = QStringLiteral("https://gitea.nocode-var.tech/FWS/FWS-PacManage/releases"); @@ -225,15 +332,20 @@ void UpdateManager::checkForUpdates() { bool hasUpdate = isNewerVersion(tag, currentVersion()); m_lastKnownRemoteVersion = tag; - m_latestVersion = tag; + qCInfo(pacmgrUpdate) << "remote version" << tag << "local" << currentVersion() + << "hasUpdate" << hasUpdate; emit checkFinished(hasUpdate, tag, QString()); }); } bool UpdateManager::isNewerVersion(const QString& remote, const QString& local) { // Simple dotted numeric comparison ("1.10.2" > "1.9.1"). Non-numeric - // components are treated as 0 so pre-release tags stay comparable. - auto parts = [](const QString& v) { + // components are treated as 0 so pre-release tags stay comparable, and a + // leading "v"/"V" (git tag style) is stripped so callers do not have to + // normalise before comparing. + auto parts = [](const QString& value) { + QString v = value.trimmed(); + if (v.startsWith('v') || v.startsWith('V')) v = v.mid(1); QVector out; for (const QString& chunk : v.split('.')) { bool ok = false; @@ -254,103 +366,200 @@ bool UpdateManager::isNewerVersion(const QString& remote, const QString& local) return false; } -// Rebuilds + reinstalls the app in the background. -// - Source checkout present: git pull + rebuild in place. -// - Installed without the repo: download the release tarball to /tmp, -// build it there and `cmake --install` to the prefix the running binary -// came from (sudo when that prefix is not user-writable). -// The new binary takes effect at the next launch; the running process is -// untouched. Exits non-zero on failure so the caller can report it. +// Rebuilds + reinstalls the app in the background, using the strategy picked +// by updateMethod(). The new binary takes effect at the next launch; the +// running process is untouched. Exits non-zero on failure so the caller can +// report it. void UpdateManager::performSelfUpdate(const QString& sudoPassword) { - if (!m_repoPath.isEmpty()) { - QString script = QStringLiteral( - "set -e\n" - "echo 'Mise à jour de PacManager...'\n" - "git pull --ff-only origin main 2>&1 || git pull --ff-only 2>&1\n" - "if [ -d build ]; then\n" - " cmake --build build -j$(nproc) 2>&1\n" - "else\n" - " cmake -B build -DCMAKE_BUILD_TYPE=Release . 2>&1\n" - " cmake --build build -j$(nproc) 2>&1\n" - "fi\n" - "cmake --install build 2>&1\n" - "echo 'Mise à jour terminée. Redémarrez PacManager pour utiliser la nouvelle version.'"); - - runShell(script, m_repoPath); - return; + const UpdateMethod method = updateMethod(); + qCInfo(pacmgrUpdate) << "starting self-update, method" + << static_cast(method) << "into" << binDir(); + switch (method) { + case UpdateMethod::Checkout: + performCheckoutUpdate(); + return; + case UpdateMethod::Clone: + performCloneUpdate(sudoPassword); + return; + case UpdateMethod::Prebuilt: + performPrebuiltUpdate(sudoPassword); + return; + case UpdateMethod::Tarball: + performTarballUpdate(sudoPassword); + return; + case UpdateMethod::None: + emit selfUpdateFinished( + false, QStringLiteral("Aucune méthode de mise à jour disponible.")); + return; } +} - if (m_tarballUrl.isEmpty() || m_latestVersion.isEmpty()) { - emit selfUpdateFinished(false, QStringLiteral("Dépôt source introuvable.")); - return; - } - - // Quote the password for the shell pipe; never log it. - QString quoted; - { - QString p = sudoPassword; - p.replace(QLatin1String("'"), QLatin1String("'\\''")); - quoted = QStringLiteral("'") + p + QStringLiteral("'"); - } - const bool useSudoPipe = !sudoPassword.isEmpty(); - - // Installed mode: fetch the release tarball, compile in /tmp, reinstall - // to the same prefix. `cmake --install` needs sudo only for system - // prefixes; ~/.local stays a plain user install. +// Checkout path (dev): pull the sources and rebuild in place, then install +// with whatever prefix the build directory was configured with. +void UpdateManager::performCheckoutUpdate() { QString script = QStringLiteral( "set -e\n" - "echo 'Mise à jour de PacManager...'\n" - "command -v cmake >/dev/null || { echo 'cmake est requis pour la mise à jour (pacman -S cmake)'; exit 1; }\n" + "echo 'Mise a jour de PacManager...'\n" + "export GIT_TERMINAL_PROMPT=0\n" + "git pull --ff-only origin main 2>&1 || git pull --ff-only 2>&1\n" + "if [ -d build ]; then\n" + " cmake --build build -j$(nproc) 2>&1\n" + "else\n" + " cmake -B build -DCMAKE_BUILD_TYPE=Release . 2>&1\n" + " cmake --build build -j$(nproc) 2>&1\n" + "fi\n" + "cmake --install build 2>&1\n" + "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); + runShell(script, m_repoPath); +} + +// Shared prologue for the installed (no checkout) paths: temp work directory +// with a cleanup trap, plus the paths the install step needs, exported so the +// sudo-wrapped `sh -c` copy can expand them. +QString UpdateManager::installedScriptPrologue() const { + return QStringLiteral( + "set -e\n" + "echo 'Mise a jour de PacManager...'\n" "WORK=$(mktemp -d /tmp/pacmanager-update-XXXXXX)\n" "trap 'rm -rf \"$WORK\"' EXIT\n" - "TARBALL_URL=%1\n" - "VERSION=%2\n" - "PREFIX=%3\n" - "ARCHIVE=\"$WORK/src.tar.gz\"\n" - "if command -v curl >/dev/null; then curl -fsSL -o \"$ARCHIVE\" \"$TARBALL_URL\" 2>&1;\n" - "elif command -v wget >/dev/null; then wget -O \"$ARCHIVE\" \"$TARBALL_URL\" 2>&1;\n" - "else echo 'curl ou wget est requis pour télécharger la mise à jour'; exit 1; fi\n" - "if ! tar xzf \"$ARCHIVE\" -C \"$WORK\" 2>/dev/null; then\n" - " command -v unzip >/dev/null || { echo 'unzip est requis pour cette archive'; exit 1; }\n" - " unzip -q \"$ARCHIVE\" -d \"$WORK\" 2>&1 || { echo 'Archive invalide'; exit 1; }\n" + "BIN_DIR=%1\n" + "STAGE=\"$WORK/stage\"\n" + "export WORK BIN_DIR STAGE\n" + "export GIT_TERMINAL_PROMPT=0\n") + .arg(quotedBinDir()); +} + +// Copies a staged install tree ($STAGE/bin, plugins under bin/plugins or +// plugins/ depending on the source) into the running binary's directory. +static QString stagedCopyAction() { + return QStringLiteral( + "set -e\n" + "mkdir -p \"$BIN_DIR\"\n" + "cp \"$STAGE/bin/PacManager\" \"$BIN_DIR/PacManager\"\n" + "if [ -f \"$STAGE/bin/version\" ]; then cp \"$STAGE/bin/version\" \"$BIN_DIR/version\"; fi\n" + "if [ -d \"$STAGE/bin/plugins\" ]; then SRC_PLUGINS=\"$STAGE/bin/plugins\";\n" + "elif [ -d \"$STAGE/plugins\" ]; then SRC_PLUGINS=\"$STAGE/plugins\";\n" + "else SRC_PLUGINS=\"\"; fi\n" + "if [ -n \"$SRC_PLUGINS\" ]; then\n" + " mkdir -p \"$BIN_DIR/plugins\"\n" + " cp \"$SRC_PLUGINS/\"*.so \"$BIN_DIR/plugins/\" 2>/dev/null || true\n" + "fi\n"); +} + +// Install command: the action runs in a child `sh` (so it may be a compound +// command and expands the exported paths), through sudo when a password was +// provided or the target directory is not writable. +QString UpdateManager::installCommand(const QString& quotedPassword, + const QString& action) const { + const QString quotedAction = quoteShell(action); + if (!quotedPassword.isEmpty()) { + // NOTE: single %s — QString::arg() only substitutes %1..%99. + return QStringLiteral("printf '%s\\n' %1 | sudo -S sh -c %2 2>&1\n") + .arg(quotedPassword, quotedAction); + } + if (QFileInfo(binDir()).isWritable()) { + return QStringLiteral("sh -c %1 2>&1\n").arg(quotedAction); + } + return QStringLiteral("sudo sh -c %1 2>&1\n").arg(quotedAction); +} + +QString UpdateManager::quotedBinDir() const { + return quoteShell(binDir()); +} + +QString UpdateManager::quoteShell(const QString& s) { + QString q = s; + q.replace(QLatin1String("'"), QLatin1String("'\\''")); + return QStringLiteral("'") + q + QStringLiteral("'"); +} + +QString UpdateManager::quotedPassword(const QString& sudoPassword) { + if (sudoPassword.isEmpty()) return {}; + QString p = sudoPassword; + p.replace(QLatin1String("'"), QLatin1String("'\\''")); + return QStringLiteral("'") + p + QStringLiteral("'"); +} + +// Clone path: used for an installed app with no checkout around the binary. +// The first update clones the repo into ~/.local/share/PacManager/src, later +// ones fast-forward it, then the app is rebuilt and installed where the +// running binary lives. +void UpdateManager::performCloneUpdate(const QString& sudoPassword) { + QString script = installedScriptPrologue(); + script += QStringLiteral( + "SRC=%1\n" + "export SRC\n" + "command -v git >/dev/null 2>&1 || { echo 'git est requis pour la mise a jour'; exit 1; }\n" + "command -v cmake >/dev/null 2>&1 || { echo 'cmake est requis pour la mise a jour'; exit 1; }\n" + "if [ -d \"$SRC/.git\" ]; then\n" + " echo 'Recuperation des sources...'\n" + " git -C \"$SRC\" fetch --depth 1 origin main 2>&1\n" + " git -C \"$SRC\" reset --hard FETCH_HEAD 2>&1\n" + "else\n" + " echo 'Clonage du depot...'\n" + " rm -rf \"$SRC\"\n" + " mkdir -p \"$(dirname \"$SRC\")\"\n" + " git clone --depth 1 --branch main %2 \"$SRC\" 2>&1\n" "fi\n" - // NOTE: single %h here — QString::arg() leaves %h untouched (only - // %1..%99 are placeholders), so find receives the correct -printf. - "SRC=$(find \"$WORK\" -maxdepth 2 -name CMakeLists.txt -printf '%h\\n' | head -n 1)\n" - "[ -n \"$SRC\" ] || { echo 'Archive invalide: CMakeLists.txt introuvable'; exit 1; }\n" + "cmake -S \"$SRC\" -B \"$SRC/build\" -DCMAKE_BUILD_TYPE=Release 2>&1\n" + "cmake --build \"$SRC/build\" -j$(nproc) 2>&1\n" + "cmake --install \"$SRC/build\" --prefix \"$STAGE\" 2>&1\n") + .arg(quoteShell(sourceClonePath()), quoteShell(QString::fromLatin1(kRepoUrl))); + script += installCommand(quotedPassword(sudoPassword), stagedCopyAction()); + script += QStringLiteral( + "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); + runShell(script, QDir::homePath()); +} + +// Prebuilt path: download the release archive (bin/ + plugins/) and unpack it +// straight into the running binary's directory. No compiler needed. +void UpdateManager::performPrebuiltUpdate(const QString& sudoPassword) { + QString script = installedScriptPrologue(); + script += QStringLiteral( + "URL=%1\n" + "ARCHIVE=\"$WORK/update.tar.gz\"\n" + "if command -v curl >/dev/null 2>&1; then curl -fsSL -o \"$ARCHIVE\" \"$URL\" 2>&1\n" + "elif command -v wget >/dev/null 2>&1; then wget -O \"$ARCHIVE\" \"$URL\" 2>&1\n" + "else echo 'curl ou wget est requis'; exit 1; fi\n" + "mkdir -p \"$WORK/unpacked\"\n" + "tar xzf \"$ARCHIVE\" -C \"$WORK/unpacked\" 2>&1\n" + "STAGE=\"$WORK/unpacked\"\n" + "export STAGE\n" + "[ -x \"$STAGE/bin/PacManager\" ] || { echo 'Archive invalide'; exit 1; }\n") + .arg(quoteShell(m_prebuiltUrl)); + script += installCommand(quotedPassword(sudoPassword), stagedCopyAction()); + script += QStringLiteral( + "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); + runShell(script, QDir::homePath()); +} + +// Source fallback: fetch the release tarball, build it in /tmp and install the +// result where the running binary lives. Used only when git is unavailable. +void UpdateManager::performTarballUpdate(const QString& sudoPassword) { + QString script = installedScriptPrologue(); + script += QStringLiteral( + "command -v cmake >/dev/null 2>&1 || { echo 'cmake est requis pour la mise a jour'; exit 1; }\n" + "URL=%1\n" + "ARCHIVE=\"$WORK/src.tar.gz\"\n" + "if command -v curl >/dev/null 2>&1; then curl -fsSL -o \"$ARCHIVE\" \"$URL\" 2>&1\n" + "elif command -v wget >/dev/null 2>&1; then wget -O \"$ARCHIVE\" \"$URL\" 2>&1\n" + "else echo 'curl ou wget est requis'; exit 1; fi\n" + "mkdir -p \"$WORK/src\"\n" + "if tar xzf \"$ARCHIVE\" -C \"$WORK/src\" 2>/dev/null; then :\n" + "else\n" + " command -v unzip >/dev/null 2>&1 || { echo 'unzip est requis pour cette archive'; exit 1; }\n" + " unzip -q \"$ARCHIVE\" -d \"$WORK/src\" 2>&1 || { echo 'Archive invalide'; exit 1; }\n" + "fi\n" + // NOTE: single %h — QString::arg() leaves %h untouched (only %1..%99 + // are placeholders), so find gets the correct -printf. + "SRC=$(find \"$WORK/src\" -maxdepth 2 -name CMakeLists.txt -printf '%h\\n' | head -n 1)\n" + "[ -n \"$SRC\" ] || { echo 'Archive invalide'; exit 1; }\n" "cmake -S \"$SRC\" -B \"$WORK/build\" -DCMAKE_BUILD_TYPE=Release 2>&1\n" "cmake --build \"$WORK/build\" -j$(nproc) 2>&1\n" - "if [ -w \"$PREFIX\" ] || [ -w \"$PREFIX/bin\" ]; then\n" - " cmake --install \"$WORK/build\" --prefix \"$PREFIX\" 2>&1\n" - "else\n" - "%4" - "fi\n" - "echo 'Mise à jour terminée. Redémarrez PacManager pour utiliser la nouvelle version.'"); - - // Install step: pipe the sudo password when provided, otherwise let sudo - // prompt on its own terminal (graphical sudo may pop up its dialog). - QString installStep; - if (useSudoPipe) { - // NOTE: single %s — QString::arg() only substitutes %1..%99, so - // printf keeps its format specifier intact. - installStep = QStringLiteral( - " printf '%s\\n' %1 | sudo -S cmake --install \"$WORK/build\" --prefix \"$PREFIX\" 2>&1\n") - .arg(quoted); - } else { - installStep = QStringLiteral( - " sudo cmake --install \"$WORK/build\" --prefix \"$PREFIX\" 2>&1\n"); - } - - auto quoteShell = [](const QString& s) { - QString q = s; - q.replace(QLatin1String("'"), QLatin1String("'\\''")); - return QStringLiteral("'") + q + QStringLiteral("'"); - }; - - script = script.arg(quoteShell(m_tarballUrl)) - .arg(quoteShell(m_latestVersion)) - .arg(quoteShell(installPrefix())) - .arg(installStep); - + "cmake --install \"$WORK/build\" --prefix \"$STAGE\" 2>&1\n") + .arg(quoteShell(m_tarballUrl)); + script += installCommand(quotedPassword(sudoPassword), stagedCopyAction()); + script += QStringLiteral( + "echo 'Mise a jour terminee. Redemarrez PacManager pour utiliser la nouvelle version.'"); runShell(script, QDir::homePath()); } \ No newline at end of file diff --git a/tests/update-manager.test.cpp b/tests/update-manager.test.cpp new file mode 100644 index 0000000..a87f902 --- /dev/null +++ b/tests/update-manager.test.cpp @@ -0,0 +1,127 @@ +// Unit tests for the pure parts of UpdateManager: version comparison and the +// update-strategy choice (no network, toolchain or filesystem needed). +#include +#include + +#include + +#include "update-manager.h" + +static int failures = 0; + +static void check(bool cond, const char* name) { + if (cond) { + std::cout << "PASS " << name << std::endl; + } else { + std::cout << "FAIL " << name << std::endl; + ++failures; + } +} + +using Caps = UpdateManager::UpdateCapabilities; +using Method = UpdateManager::UpdateMethod; + +static void testChooseMethod_checkoutWinsOverEverything() { + Caps caps; + caps.checkoutUsable = true; + caps.hasGit = caps.hasCmake = caps.hasCompiler = true; + caps.hasPrebuilt = caps.hasTarball = true; + check(UpdateManager::chooseUpdateMethod(caps) == Method::Checkout, + "method_checkout_wins"); +} + +static void testChooseMethod_cloneWhenToolchainPresent() { + Caps caps; + caps.hasGit = caps.hasCmake = caps.hasCompiler = true; + caps.hasPrebuilt = caps.hasTarball = true; + // The clone path is deliberately preferred over the prebuilt asset. + check(UpdateManager::chooseUpdateMethod(caps) == Method::Clone, + "method_clone_first"); +} + +static void testChooseMethod_cloneRequiresCompiler() { + Caps caps; + caps.hasGit = caps.hasCmake = true; // no compiler -> cannot rebuild + check(UpdateManager::chooseUpdateMethod(caps) == Method::None, + "method_clone_needs_compiler"); +} + +static void testChooseMethod_prebuiltWithoutToolchain() { + Caps caps; + caps.hasPrebuilt = caps.hasTarball = true; + check(UpdateManager::chooseUpdateMethod(caps) == Method::Prebuilt, + "method_prebuilt_without_tools"); +} + +static void testChooseMethod_prebuiltWithGitOnly() { + Caps caps; + caps.hasGit = true; // git alone cannot build + caps.hasPrebuilt = true; + check(UpdateManager::chooseUpdateMethod(caps) == Method::Prebuilt, + "method_prebuilt_git_only"); +} + +static void testChooseMethod_prebuiltPreferredOverTarball() { + Caps caps; + caps.hasCmake = caps.hasCompiler = true; // no git + caps.hasPrebuilt = caps.hasTarball = true; + check(UpdateManager::chooseUpdateMethod(caps) == Method::Prebuilt, + "method_prebuilt_over_tarball"); +} + +static void testChooseMethod_tarballWithoutGit() { + Caps caps; + caps.hasCmake = caps.hasCompiler = true; // no git + caps.hasTarball = true; + check(UpdateManager::chooseUpdateMethod(caps) == Method::Tarball, + "method_tarball_without_git"); +} + +static void testChooseMethod_tarballRequiresCompiler() { + Caps caps; + caps.hasCmake = true; // no compiler + caps.hasTarball = true; + check(UpdateManager::chooseUpdateMethod(caps) == Method::None, + "method_tarball_needs_compiler"); +} + +static void testChooseMethod_noneWhenNothingAvailable() { + Caps caps; + check(UpdateManager::chooseUpdateMethod(caps) == Method::None, + "method_none_without_anything"); +} + +int main() { + // Basic ordering + check(UpdateManager::isNewerVersion("1.3.2", "1.3.1") == true, "newer_patch"); + check(UpdateManager::isNewerVersion("1.3.1", "1.3.1") == false, "same_version"); + check(UpdateManager::isNewerVersion("1.3.0", "1.3.1") == false, "older_patch"); + check(UpdateManager::isNewerVersion("1.4.0", "1.3.9") == true, "newer_minor"); + check(UpdateManager::isNewerVersion("2.0.0", "1.9.9") == true, "newer_major"); + + // Leading v/V (git tags) is normalized + check(UpdateManager::isNewerVersion("v1.3.2", "1.3.1") == true, "tag_v_prefix"); + check(UpdateManager::isNewerVersion("V1.3.2", "1.3.1") == true, "tag_V_prefix"); + check(UpdateManager::isNewerVersion("v1.3.1", "1.3.1") == false, "tag_same"); + + // Different component counts: 1.3 == 1.3.0 + check(UpdateManager::isNewerVersion("1.3.1", "1.3") == true, "longer_newer"); + check(UpdateManager::isNewerVersion("1.3", "1.3.0") == false, "equal_implicit_zero"); + + // Empty remote never triggers an update prompt + check(UpdateManager::isNewerVersion("", "1.3.1") == false, "empty_remote"); + + // Update-strategy choice + testChooseMethod_checkoutWinsOverEverything(); + testChooseMethod_cloneWhenToolchainPresent(); + testChooseMethod_cloneRequiresCompiler(); + testChooseMethod_prebuiltWithoutToolchain(); + testChooseMethod_prebuiltWithGitOnly(); + testChooseMethod_prebuiltPreferredOverTarball(); + testChooseMethod_tarballWithoutGit(); + testChooseMethod_tarballRequiresCompiler(); + testChooseMethod_noneWhenNothingAvailable(); + + if (failures == 0) std::cout << "All update-manager tests passed" << std::endl; + return failures == 0 ? 0 : 1; +}