feat(update): add self-update check via Gitea releases API
tests / build-test (push) Has been cancelled
tests / build-test (push) Has been cancelled
Adds an UpdateManager that queries the Gitea releases API once per day, stores the last check state in a JSON file, and offers to pull + rebuild the source repository when a newer version exists. The running binary is left untouched until the next launch. Also sets the app version from the version file at build time instead of the hardcoded 1.0.0, and copies the version file next to the executable.
This commit is contained in:
6 files changed
+424
-6
No files matched your search
+93
-3
@@ -188,6 +188,7 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
|
||||
m_pacman = dynamic_cast<PacmanManager*>(m_pluginManager->managerFor("pacman"));
|
||||
|
||||
m_historyManager = new HistoryManager();
|
||||
m_updateManager = new UpdateManager(this);
|
||||
|
||||
setupUI();
|
||||
setupMenuBar();
|
||||
@@ -214,11 +215,18 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
|
||||
|
||||
refreshDashboard();
|
||||
updateStatusBar();
|
||||
|
||||
// Check for app updates once per day (or on first launch). The delay lets
|
||||
// the window appear first so the status bar message is visible.
|
||||
if (m_updateManager->shouldCheck()) {
|
||||
QTimer::singleShot(1500, this, &MainWindow::onCheckForUpdates);
|
||||
}
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow() {
|
||||
delete m_pluginManager; // owns every provider, built-in and external
|
||||
delete m_historyManager;
|
||||
delete m_updateManager;
|
||||
}
|
||||
|
||||
void MainWindow::setupUI() {
|
||||
@@ -1050,11 +1058,13 @@ void MainWindow::setupMenuBar() {
|
||||
[this]() { applyCredentialMode(CredentialMode::AtLaunch); });
|
||||
|
||||
QMenu* helpMenu = menuBar->addMenu("Aide");
|
||||
helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates);
|
||||
helpMenu->addSeparator();
|
||||
helpMenu->addAction("À propos", [this]() {
|
||||
QMessageBox::about(this, "PacManager",
|
||||
"<h2>PacManager v1.0.0</h2>"
|
||||
"<p>Gestionnaire de paquets pour Arch Linux (pacman).</p>"
|
||||
);
|
||||
QString("<h2>PacManager v%1</h2>"
|
||||
"<p>Gestionnaire de paquets pour Arch Linux (pacman).</p>")
|
||||
.arg(UpdateManager::currentVersion()));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2087,3 +2097,83 @@ void MainWindow::refreshProvidersTable() {
|
||||
m_providerDescription->clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Starts an update check against the Gitea releases API. Used both at launch
|
||||
// (once per day) and from the Aide menu.
|
||||
void MainWindow::onCheckForUpdates() {
|
||||
statusBar()->showMessage("Vérification des mises à jour...");
|
||||
connect(m_updateManager, &UpdateManager::checkFinished,
|
||||
this, &MainWindow::onUpdateCheckFinished);
|
||||
m_updateManager->checkForUpdates();
|
||||
}
|
||||
|
||||
// Handles the result of a release check: offers to self-update when a newer
|
||||
// version exists, otherwise a status bar confirmation. Errors are reported
|
||||
// silently in the status bar so a network failure never blocks the app.
|
||||
void MainWindow::onUpdateCheckFinished(bool hasUpdate, const QString& latestVersion,
|
||||
const QString& errorMessage) {
|
||||
disconnect(m_updateManager, &UpdateManager::checkFinished,
|
||||
this, &MainWindow::onUpdateCheckFinished);
|
||||
|
||||
if (!errorMessage.isEmpty()) {
|
||||
statusBar()->showMessage(errorMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasUpdate) {
|
||||
statusBar()->showMessage(
|
||||
QString("PacManager est à jour (v%1)").arg(UpdateManager::currentVersion()));
|
||||
return;
|
||||
}
|
||||
|
||||
// Ask the user whether to update now or skip. When the source repo is
|
||||
// available the update runs in the background (git pull + build); the
|
||||
// running binary stays untouched until the next launch.
|
||||
QMessageBox box(this);
|
||||
box.setWindowTitle("Mise à jour disponible");
|
||||
box.setIcon(QMessageBox::Information);
|
||||
box.setTextFormat(Qt::RichText);
|
||||
box.setText(QString("<h3>PacManager v%1 est disponible</h3>"
|
||||
"<p>Vous utilisez actuellement la version %2.</p>")
|
||||
.arg(latestVersion, UpdateManager::currentVersion()));
|
||||
|
||||
QPushButton* updateBtn = box.addButton("Mettre à jour", QMessageBox::AcceptRole);
|
||||
QPushButton* skipBtn = box.addButton("Plus tard", QMessageBox::RejectRole);
|
||||
|
||||
if (!m_updateManager->canSelfUpdate()) {
|
||||
// No source checkout: only point to the releases page.
|
||||
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.");
|
||||
updateBtn->setEnabled(false);
|
||||
}
|
||||
|
||||
box.exec();
|
||||
|
||||
if (box.clickedButton() == updateBtn) {
|
||||
statusBar()->showMessage("Mise à jour en cours en arrière-plan...");
|
||||
connect(m_updateManager, &UpdateManager::selfUpdateFinished,
|
||||
this, &MainWindow::onSelfUpdateFinished);
|
||||
m_updateManager->performSelfUpdate();
|
||||
}
|
||||
// "Plus tard" (or closing the dialog) simply skips the update.
|
||||
}
|
||||
|
||||
// Called when the background git pull + build finishes. Reports the result in
|
||||
// a dialog so the user knows whether to restart the app.
|
||||
void MainWindow::onSelfUpdateFinished(bool success, const QString& message) {
|
||||
disconnect(m_updateManager, &UpdateManager::selfUpdateFinished,
|
||||
this, &MainWindow::onSelfUpdateFinished);
|
||||
|
||||
if (success) {
|
||||
QMessageBox::information(this, "Mise à jour terminée",
|
||||
QString("<h3>PacManager a été mis à jour</h3>"
|
||||
"<p>La nouvelle version sera active au prochain démarrage.</p>"
|
||||
"<pre>%1</pre>")
|
||||
.arg(message.toHtmlEscaped()));
|
||||
} else {
|
||||
QMessageBox::warning(this, "Échec de la mise à jour",
|
||||
QString("<p>La mise à jour a échoué :</p><pre>%1</pre>")
|
||||
.arg(message.toHtmlEscaped()));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1,10 +1,11 @@
|
||||
#include <QApplication>
|
||||
#include "main-window.h"
|
||||
#include "update-manager.h"
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
QApplication app(argc, argv);
|
||||
app.setApplicationName("PacManager");
|
||||
app.setApplicationVersion("1.0.0");
|
||||
app.setApplicationVersion(UpdateManager::currentVersion());
|
||||
app.setOrganizationName("Freebuff");
|
||||
|
||||
MainWindow window;
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
#include "update-manager.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QStandardPaths>
|
||||
#include <QDir>
|
||||
#include <QCoreApplication>
|
||||
#include <QProcessEnvironment>
|
||||
|
||||
// Repository base URL used to query the Gitea API for releases.
|
||||
// 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
|
||||
static const char* kRepoUrl =
|
||||
"https://gitea.nocode-var.tech/FWS/FWS-PacManage.git";
|
||||
|
||||
UpdateManager::UpdateManager(QObject* parent) : QObject(parent) {
|
||||
loadState();
|
||||
|
||||
// The running executable is expected to live in the build/ directory when
|
||||
// launched from a source checkout. Walk up two levels to find the repo.
|
||||
// When installed to ~/.local/bin there is no source tree, so update
|
||||
// becomes impossible and the dialog simply points to the releases page.
|
||||
QDir dir(QCoreApplication::applicationDirPath());
|
||||
if (dir.dirName() == QLatin1String("build")) {
|
||||
dir.cdUp();
|
||||
if (dir.exists(QLatin1String("CMakeLists.txt"))) {
|
||||
m_repoPath = dir.absolutePath();
|
||||
}
|
||||
}
|
||||
|
||||
connect(&m_process, &QProcess::finished, this, [this](int exitCode) {
|
||||
const QString msg = QString::fromUtf8(m_process.readAllStandardOutput())
|
||||
+ QString::fromUtf8(m_process.readAllStandardError());
|
||||
emit selfUpdateFinished(exitCode == 0, msg.trimmed());
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
QString UpdateManager::stateFilePath() {
|
||||
QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
|
||||
if (dir.isEmpty()) {
|
||||
dir = QDir::homePath() + "/.local/share/PacManager";
|
||||
}
|
||||
return dir + "/update-state.json";
|
||||
}
|
||||
|
||||
bool UpdateManager::shouldCheck() const {
|
||||
if (m_lastCheckDate.isEmpty()) return true;
|
||||
|
||||
QDateTime last = QDateTime::fromString(m_lastCheckDate, Qt::ISODate);
|
||||
if (!last.isValid()) return true;
|
||||
|
||||
// Only one network call per day keeps launch snappy and avoids hammering
|
||||
// the Gitea API on every start.
|
||||
return last.daysTo(QDateTime::currentDateTime()) >= 1;
|
||||
}
|
||||
|
||||
QString UpdateManager::lastKnownRemoteVersion() const {
|
||||
return m_lastKnownRemoteVersion;
|
||||
}
|
||||
|
||||
QString UpdateManager::repoPath() const {
|
||||
return m_repoPath;
|
||||
}
|
||||
|
||||
bool UpdateManager::canSelfUpdate() const {
|
||||
if (m_repoPath.isEmpty()) return false;
|
||||
|
||||
QDir repo(m_repoPath);
|
||||
if (!repo.exists(QLatin1String(".git"))) return false;
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void UpdateManager::loadState() {
|
||||
QFile file(stateFilePath());
|
||||
if (!file.open(QIODevice::ReadOnly)) return;
|
||||
|
||||
QJsonParseError err;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &err);
|
||||
if (err.error != QJsonParseError::NoError || !doc.isObject()) return;
|
||||
|
||||
QJsonObject obj = doc.object();
|
||||
m_lastCheckDate = obj.value("lastCheckDate").toString();
|
||||
m_lastKnownRemoteVersion = obj.value("latestRemoteVersion").toString();
|
||||
}
|
||||
|
||||
void UpdateManager::saveState(const QString& remoteVersion) {
|
||||
QJsonObject obj;
|
||||
obj["lastCheckDate"] = QDateTime::currentDateTime().toString(Qt::ISODate);
|
||||
obj["latestRemoteVersion"] = remoteVersion;
|
||||
|
||||
QString path = stateFilePath();
|
||||
QDir().mkpath(QFileInfo(path).absolutePath());
|
||||
|
||||
QFile file(path);
|
||||
if (!file.open(QIODevice::WriteOnly)) return;
|
||||
file.write(QJsonDocument(obj).toJson(QJsonDocument::Indented));
|
||||
}
|
||||
|
||||
void UpdateManager::runShell(const QString& script, const QString& workingDir) {
|
||||
m_process.setWorkingDirectory(workingDir);
|
||||
m_process.setProcessChannelMode(QProcess::MergedChannels);
|
||||
#if defined(Q_OS_WIN)
|
||||
m_process.start("cmd.exe", QStringList{"/C", script});
|
||||
#else
|
||||
m_process.start("/bin/sh", QStringList{"-c", script});
|
||||
#endif
|
||||
}
|
||||
|
||||
void UpdateManager::checkForUpdates() {
|
||||
QNetworkRequest request{QUrl(QString::fromLatin1(kApiUrl))};
|
||||
request.setHeader(QNetworkRequest::UserAgentHeader,
|
||||
QString("PacManager/%1").arg(currentVersion()));
|
||||
|
||||
QNetworkReply* reply = m_network.get(request);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
||||
reply->deleteLater();
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
emit checkFinished(false, QString(),
|
||||
QStringLiteral("Impossible de contacter le serveur : %1")
|
||||
.arg(reply->errorString()));
|
||||
return;
|
||||
}
|
||||
|
||||
const QByteArray data = reply->readAll();
|
||||
QJsonParseError err;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(data, &err);
|
||||
if (err.error != QJsonParseError::NoError || !doc.isObject()) {
|
||||
emit checkFinished(false, QString(),
|
||||
QStringLiteral("Réponse du serveur invalide."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Gitea returns the release tag (e.g. "V1.2.1") as `tag_name`.
|
||||
QString tag = doc.object().value("tag_name").toString().trimmed();
|
||||
if (tag.isEmpty()) {
|
||||
emit checkFinished(false, QString(),
|
||||
QStringLiteral("Aucune release trouvée sur le serveur."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalise tags like "V1.2.1" or "v1.2.1" to "1.2.1" for comparison.
|
||||
if (tag.startsWith('v') || tag.startsWith('V')) {
|
||||
tag = tag.mid(1);
|
||||
}
|
||||
|
||||
saveState(tag);
|
||||
|
||||
bool hasUpdate = isNewerVersion(tag, currentVersion());
|
||||
m_lastKnownRemoteVersion = tag;
|
||||
m_latestVersion = tag;
|
||||
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) {
|
||||
QVector<int> out;
|
||||
for (const QString& chunk : v.split('.')) {
|
||||
bool ok = false;
|
||||
int n = chunk.toInt(&ok);
|
||||
out.append(ok ? n : 0);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const QVector<int> r = parts(remote);
|
||||
const QVector<int> l = parts(local);
|
||||
const int n = qMax(r.size(), l.size());
|
||||
for (int i = 0; i < n; ++i) {
|
||||
int ri = i < r.size() ? r[i] : 0;
|
||||
int li = i < l.size() ? l[i] : 0;
|
||||
if (ri != li) return ri > li;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pulls the latest source and rebuilds the app in the background. The script
|
||||
// exits with a non-zero code on failure so the caller can report it. The new
|
||||
// binary replaces the old one only when the build completes — the currently
|
||||
// running process is untouched and picks it up on its next launch.
|
||||
void UpdateManager::performSelfUpdate() {
|
||||
if (m_repoPath.isEmpty()) {
|
||||
emit selfUpdateFinished(false, QStringLiteral("Dépôt source introuvable."));
|
||||
return;
|
||||
}
|
||||
|
||||
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"
|
||||
"echo 'Mise à jour terminée. Redémarrez PacManager pour utiliser la nouvelle version.'");
|
||||
|
||||
runShell(script, m_repoPath);
|
||||
}
|
||||
Reference in new issue
Block a user