diff --git a/CMakeLists.txt b/CMakeLists.txt index eef050f..ef99ab4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,6 +7,13 @@ set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) +# The repo-root `version` file is the single source of truth for release +# versioning. It is compiled into the binaries as well as installed next to +# them, so a running app always reports the release it was built from instead +# of trusting a `version` file that an update may have left stale. +file(READ ${CMAKE_CURRENT_SOURCE_DIR}/version PACMANAGER_VERSION) +string(STRIP "${PACMANAGER_VERSION}" PACMANAGER_VERSION) + # Find Qt6 find_package(Qt6 REQUIRED COMPONENTS Widgets Network) @@ -39,6 +46,8 @@ add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) target_include_directories(${PROJECT_NAME} PRIVATE include) target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Widgets Qt6::Network) +target_compile_definitions(${PROJECT_NAME} PRIVATE + FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}") # Copy the version file next to the executable so UpdateManager can read the # running build's version at runtime. @@ -124,6 +133,8 @@ 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) +target_compile_definitions(update-manager-test PRIVATE + FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}") add_test(NAME update-manager-test COMMAND update-manager-test) # ---- Plugins ---- diff --git a/include/update-manager.h b/include/update-manager.h index f2c879a..e859c1b 100644 --- a/include/update-manager.h +++ b/include/update-manager.h @@ -13,7 +13,8 @@ // 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; +// - Checkout: a source checkout around the binary is pulled + rebuilt, then +// installed into the running binary's directory like the other methods; // - 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); @@ -25,7 +26,9 @@ class UpdateManager : public QObject { public: explicit UpdateManager(QObject* parent = nullptr); - // Current app version, read from the version file at build time. + // Current app version, compiled in from the repo-root `version` file (see + // CMakeLists.txt), falling back to the `version` file installed next to the + // executable when the build bypassed CMake. static QString currentVersion(); // Path of the state file storing the last check date and the latest @@ -135,13 +138,14 @@ private: void saveState(const QString& remoteVersion); void loadState(); void runShell(const QString& script, const QString& workingDir); - void performCheckoutUpdate(); + void performCheckoutUpdate(const QString& sudoPassword); 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; + // Shared script header for every update path: temp work dir, cleanup trap, + // the release being installed, and the export of the paths the install step + // needs. + QString updateScriptPrologue() 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, diff --git a/src/main-window.cpp b/src/main-window.cpp index 731b04c..5c07fb5 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -3009,10 +3009,11 @@ void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVers } // 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: + // root-owned directory (e.g. /usr/bin). Every method installs into the + // running binary's directory, and only that final copy is privileged: // everything else builds in a temp directory owned by the user. QString sudoPassword; - if (m_updateManager->repoPath().isEmpty() && !QFileInfo(targetDir).isWritable() + if (!QFileInfo(targetDir).isWritable() && m_pacman && m_pacman->isAvailable()) { bool ok = false; sudoPassword = QInputDialog::getText( diff --git a/src/update-manager.cpp b/src/update-manager.cpp index 14ae819..a698e78 100644 --- a/src/update-manager.cpp +++ b/src/update-manager.cpp @@ -16,7 +16,14 @@ // The app is hosted at https://gitea.nocode-var.tech/FWS/FWS-PacManage. static const char* kApiUrl = "https://gitea.nocode-var.tech/api/v1/repos/FWS/FWS-PacManage/releases/latest"; -static const char* kVersionToken = "FWSPACMANAGE_VERSION"; // replaced at build time + +// Version compiled in from the repo-root `version` file (see CMakeLists.txt). +// Empty when the build bypasses CMake, in which case the `version` file next to +// the executable is used instead. +#ifndef FWSPACMANAGE_VERSION +#define FWSPACMANAGE_VERSION "" +#endif + static const char* kRepoUrl = "https://gitea.nocode-var.tech/FWS/FWS-PacManage.git"; @@ -45,23 +52,21 @@ UpdateManager::UpdateManager(QObject* parent) : QObject(parent) { } QString UpdateManager::currentVersion() { - // The `version` file at the repo root is the single source of truth. It is - // read from the executable's directory so a running build always reports - // the same version the developer bumped in the repo. - QString version; - const QString localFile = QCoreApplication::applicationDirPath() + "/version"; - QFile f(localFile); - if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { - version = QString::fromUtf8(f.readAll()).trimmed(); - } + // The compiled-in version wins: it describes the code that is actually + // running, so a `version` file left behind (or never refreshed) by an + // update cannot make the app re-offer a release it already installed. + QString version = QStringLiteral(FWSPACMANAGE_VERSION).trimmed(); + + // Fallback for builds that bypass CMake: the `version` file installed next + // to the executable. if (version.isEmpty()) { - // CMake configure-time token; falls back to 1.0.0 when built without. - version = QString::fromLatin1(kVersionToken); - if (version == QLatin1String("FWSPACMANAGE_VERSION")) { - version = QStringLiteral("1.0.0"); + QFile f(QCoreApplication::applicationDirPath() + "/version"); + if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { + version = QString::fromUtf8(f.readAll()).trimmed(); } } - return version; + + return version.isEmpty() ? QStringLiteral("1.0.0") : version; } QString UpdateManager::stateFilePath() { @@ -390,7 +395,7 @@ void UpdateManager::performSelfUpdate(const QString& sudoPassword) { << static_cast(method) << "into" << binDir(); switch (method) { case UpdateMethod::Checkout: - performCheckoutUpdate(); + performCheckoutUpdate(sudoPassword); return; case UpdateMethod::Clone: performCloneUpdate(sudoPassword); @@ -408,13 +413,14 @@ void UpdateManager::performSelfUpdate(const QString& sudoPassword) { } } -// 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 a jour de PacManager...'\n" - "export GIT_TERMINAL_PROMPT=0\n" +// Checkout path (dev, or any tree built from a clone): pull, rebuild, then +// install into the directory that holds the running binary — like every other +// method. The build's configured prefix is deliberately not used: it generally +// points at a system directory the app cannot write, and installing there would +// leave the copy in use (and its version marker) untouched. +void UpdateManager::performCheckoutUpdate(const QString& sudoPassword) { + QString script = updateScriptPrologue(); + script += QStringLiteral( "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" @@ -422,15 +428,17 @@ void UpdateManager::performCheckoutUpdate() { " 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.'"); + "cmake --install build --prefix \"$STAGE\" 2>&1\n"); + script += installCommand(quotedPassword(sudoPassword), stagedInstallScript()); + script += QStringLiteral("echo 'Mise a jour terminee.'"); 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 { +// Shared prologue for every update path: temp work directory with a cleanup +// trap, and the paths the install step needs, exported so the sudo-wrapped +// `sh -c` copy can expand them. APP_VERSION is the release being installed; the +// checkout path sets it too, so all four methods stamp the same marker. +QString UpdateManager::updateScriptPrologue() const { return QStringLiteral( "set -e\n" "echo 'Mise a jour de PacManager...'\n" @@ -438,9 +446,10 @@ QString UpdateManager::installedScriptPrologue() const { "trap 'rm -rf \"$WORK\"' EXIT\n" "BIN_DIR=%1\n" "STAGE=\"$WORK/stage\"\n" - "export WORK BIN_DIR STAGE\n" + "APP_VERSION=%2\n" + "export WORK BIN_DIR STAGE APP_VERSION\n" "export GIT_TERMINAL_PROMPT=0\n") - .arg(quotedBinDir()); + .arg(quotedBinDir(), quoteShell(m_lastKnownRemoteVersion)); } // Copies a staged install tree ($STAGE/bin, plugins under bin/plugins or @@ -465,6 +474,12 @@ QString UpdateManager::stagedInstallScript() { "}\n" "mkdir -p \"$BIN_DIR\"\n" "install_file \"$STAGE/bin/PacManager\" \"$BIN_DIR/PacManager\"\n" + // The version marker has to follow the installed release: it is what + // the app reports and what the next update check compares against, so + // a stale one would offer the same release again at every launch. + "if [ -n \"$APP_VERSION\" ]; then\n" + " printf '%s\\n' \"$APP_VERSION\" > \"$STAGE/bin/version\"\n" + "fi\n" "if [ -f \"$STAGE/bin/version\" ]; then\n" " install_file \"$STAGE/bin/version\" \"$BIN_DIR/version\"\n" "fi\n" @@ -519,7 +534,7 @@ QString UpdateManager::quotedPassword(const QString& sudoPassword) { // 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(); + QString script = updateScriptPrologue(); script += QStringLiteral( "SRC=%1\n" "export SRC\n" @@ -548,7 +563,7 @@ void UpdateManager::performCloneUpdate(const QString& sudoPassword) { // 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(); + QString script = updateScriptPrologue(); script += QStringLiteral( "URL=%1\n" "ARCHIVE=\"$WORK/update.tar.gz\"\n" @@ -570,7 +585,7 @@ void UpdateManager::performPrebuiltUpdate(const QString& sudoPassword) { // 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(); + QString script = updateScriptPrologue(); script += QStringLiteral( "command -v cmake >/dev/null 2>&1 || { echo 'cmake est requis pour la mise a jour'; exit 1; }\n" "URL=%1\n" diff --git a/tests/update-manager.test.cpp b/tests/update-manager.test.cpp index d760574..f61182c 100644 --- a/tests/update-manager.test.cpp +++ b/tests/update-manager.test.cpp @@ -15,6 +15,12 @@ #include "update-manager.h" +// Defined by CMake from the repo-root `version` file; empty when the test is +// built without it. +#ifndef FWSPACMANAGE_VERSION +#define FWSPACMANAGE_VERSION "" +#endif + static int failures = 0; static void check(bool cond, const char* name) { @@ -113,6 +119,14 @@ static void testChooseMethod_noneWhenNothingAvailable() { "method_none_without_anything"); } +// The version the app reports is the one compiled into it, so a stale `version` +// file next to the executable can never make it re-offer an installed update. +static void testCurrentVersion_isCompiledIn() { + check(UpdateManager::currentVersion() == QStringLiteral(FWSPACMANAGE_VERSION), + "current_version_compiled_in"); + check(!UpdateManager::currentVersion().isEmpty(), "current_version_not_empty"); +} + // The staged install must replace an executable that is currently running, // which is exactly the situation of the app updating itself: opening the busy // file for writing fails with ETXTBSY ("Text file busy"), so the script copies @@ -181,6 +195,47 @@ static void testStagedInstall_replacesRunningExecutable() { running.kill(); running.waitForFinished(2000); } + +// The version marker has to end up describing the release that was installed: +// it is what the app reports at launch and what the next update check compares +// against, so a stale marker makes the app offer the same update again. +static void testStagedInstall_writesReleaseVersionMarker() { + QTemporaryDir tmp; + check(tmp.isValid(), "version_marker_tmpdir"); + if (!tmp.isValid()) return; + + const QString binDir = tmp.path() + "/bin"; + const QString stage = tmp.path() + "/stage"; + QDir().mkpath(binDir); + QDir().mkpath(stage + "/bin"); + + // The target holds an outdated marker, and the staged tree has none at all + // (a prebuilt archive built without the file, or an install script that + // staged only the binary). + check(writeFile(binDir + "/version", "1.3.1"), "version_marker_seed"); + check(QFile::copy("/bin/echo", stage + "/bin/PacManager"), + "version_marker_stage_binary"); + + QProcess sh; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert("BIN_DIR", binDir); + env.insert("STAGE", stage); + env.insert("APP_VERSION", "9.9.9"); + sh.setProcessEnvironment(env); + sh.start("/bin/sh", {"-c", UpdateManager::stagedInstallScript()}); + const bool finished = sh.waitForFinished(15000); + check(finished && sh.exitCode() == 0, "version_marker_exit_zero"); + + QFile marker(binDir + "/version"); + const bool readable = marker.open(QIODevice::ReadOnly); + check(readable, "version_marker_readable"); + if (readable) { + check(QString::fromUtf8(marker.readAll()).trimmed() == "9.9.9", + "version_marker_updated"); + } + check(QDir(binDir).entryList(QStringList() << "*.new", QDir::Files).isEmpty(), + "version_marker_no_leftover_temp"); +} #endif // !Q_OS_WIN // The restart after a successful update must point at the binary the update @@ -240,6 +295,9 @@ int main() { // Empty remote never triggers an update prompt check(UpdateManager::isNewerVersion("", "1.3.1") == false, "empty_remote"); + // Reported version + testCurrentVersion_isCompiledIn(); + // Update-strategy choice testChooseMethod_checkoutWinsOverEverything(); testChooseMethod_cloneWhenToolchainPresent(); @@ -253,6 +311,7 @@ int main() { #if !defined(Q_OS_WIN) testStagedInstall_replacesRunningExecutable(); + testStagedInstall_writesReleaseVersionMarker(); #endif testRestartProgram_findsInstalledBinary();