473 lines
22 KiB
C++
473 lines
22 KiB
C++
// update.cpp — проверка и установка обновлений по ВЕРСИИ, а не по факту коммитов.
|
|
#include "update.h"
|
|
#include "http_client.h"
|
|
#include "../ui/ui.h"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <ctime>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
|
|
#include "../libs/json-3.12.0/nlohmann/json.hpp"
|
|
|
|
using json = nlohmann::json;
|
|
namespace fs = std::filesystem;
|
|
|
|
namespace xt {
|
|
|
|
// ===========================================================================
|
|
// SemVer
|
|
// ===========================================================================
|
|
SemVer semver_parse(const std::string& s_in) {
|
|
SemVer v;
|
|
v.raw = s_in;
|
|
std::string s = s_in;
|
|
while (!s.empty() && (s.front() == 'v' || s.front() == 'V')) s.erase(s.begin());
|
|
while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) s.pop_back();
|
|
if (s.empty()) return v;
|
|
|
|
// отделяем build-метаданные (+...) и pre-release (-...)
|
|
const size_t plus = s.find('+');
|
|
if (plus != std::string::npos) s = s.substr(0, plus);
|
|
const size_t dash = s.find('-');
|
|
if (dash != std::string::npos) { v.pre = s.substr(dash + 1); s = s.substr(0, dash); }
|
|
|
|
int parts[3] = {0, 0, 0};
|
|
int idx = 0;
|
|
std::string cur;
|
|
auto flush = [&]() {
|
|
if (idx < 3) {
|
|
try { parts[idx] = std::stoi(cur.empty() ? "0" : cur); } catch (...) { parts[idx] = 0; }
|
|
++idx;
|
|
}
|
|
cur.clear();
|
|
};
|
|
for (char c : s) { if (c == '.') flush(); else cur += c; }
|
|
flush();
|
|
|
|
// версия должна состоять только из цифр и точек
|
|
for (char c : s) if (!std::isdigit((unsigned char)c) && c != '.') return v;
|
|
|
|
v.major = parts[0]; v.minor = parts[1]; v.patch = parts[2];
|
|
v.valid = true;
|
|
return v;
|
|
}
|
|
|
|
static int cmp_num(int a, int b) { return (a > b) - (a < b); }
|
|
|
|
int semver_cmp(const SemVer& a, const SemVer& b) {
|
|
if (int c = cmp_num(a.major, b.major)) return c;
|
|
if (int c = cmp_num(a.minor, b.minor)) return c;
|
|
if (int c = cmp_num(a.patch, b.patch)) return c;
|
|
// pre-release: пустая строка (= релиз) СТАРШЕ любой pre-версии
|
|
if (a.pre.empty() && b.pre.empty()) return 0;
|
|
if (a.pre.empty()) return 1;
|
|
if (b.pre.empty()) return -1;
|
|
// лексикографически по компонентам, разделённым точкой
|
|
std::vector<std::string> A, B;
|
|
for (const std::string* src : {&a.pre, &b.pre}) {
|
|
std::vector<std::string>& dst = (src == &a.pre) ? A : B;
|
|
std::string cur;
|
|
for (char c : *src) { if (c == '.') { dst.push_back(cur); cur.clear(); } else cur += c; }
|
|
dst.push_back(cur);
|
|
}
|
|
const size_t n = std::max(A.size(), B.size());
|
|
for (size_t i = 0; i < n; ++i) {
|
|
if (i >= A.size()) return -1;
|
|
if (i >= B.size()) return 1;
|
|
const bool an = !A[i].empty() && std::all_of(A[i].begin(), A[i].end(),
|
|
[](char c){ return std::isdigit((unsigned char)c); });
|
|
const bool bn = !B[i].empty() && std::all_of(B[i].begin(), B[i].end(),
|
|
[](char c){ return std::isdigit((unsigned char)c); });
|
|
if (an && bn) { if (int c = cmp_num(std::stoi(A[i]), std::stoi(B[i]))) return c; }
|
|
else if (an) return -1; // числовое поле младше строкового
|
|
else if (bn) return 1;
|
|
else if (int c = A[i].compare(B[i])) return c < 0 ? -1 : 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
std::string semver_str(const SemVer& v) {
|
|
if (!v.valid) return v.raw.empty() ? std::string("<не разобрана>") : v.raw;
|
|
std::string s = std::to_string(v.major) + "." + std::to_string(v.minor) + "." + std::to_string(v.patch);
|
|
if (!v.pre.empty()) s += "-" + v.pre;
|
|
return s;
|
|
}
|
|
|
|
const char* update_result_name(UpdateResult r) {
|
|
switch (r) {
|
|
case UpdateResult::UpToDate: return "актуальная версия";
|
|
case UpdateResult::NewerAvailable: return "доступна новая версия";
|
|
case UpdateResult::LocalIsNewer: return "локальная версия новее";
|
|
case UpdateResult::CheckFailed: return "проверка не удалась";
|
|
case UpdateResult::SameVersionNewCommits:return "версия та же, есть новые коммиты";
|
|
case UpdateResult::Installed: return "обновление установлено";
|
|
case UpdateResult::InstallFailed: return "ошибка установки";
|
|
}
|
|
return "?";
|
|
}
|
|
|
|
// ===========================================================================
|
|
// Проверка
|
|
// ===========================================================================
|
|
namespace {
|
|
|
|
std::string url_join(const std::string& base, const std::string& path) {
|
|
if (base.empty()) return path;
|
|
if (base.back() == '/') return base + path;
|
|
return base + "/" + path;
|
|
}
|
|
|
|
std::string raw_url(const UpdateSettings& s) {
|
|
std::string repo = s.repo;
|
|
while (!repo.empty() && repo.back() == '/') repo.pop_back();
|
|
if (repo.size() > 4 && repo.compare(repo.size() - 4, 4, ".git") == 0)
|
|
repo = repo.substr(0, repo.size() - 4);
|
|
return repo + "/raw/branch/" + s.branch + "/" + s.version_path;
|
|
}
|
|
|
|
// HEAD ветки: sha и дата
|
|
bool fetch_branch_head(const UpdateSettings& s, const HttpOptions& o,
|
|
std::string& sha, std::string& date) {
|
|
const std::string u = url_join(s.api_base, "branches/" + s.branch);
|
|
HttpResponse r = http_get(u, o);
|
|
if (!r.ok || r.status != 200) return false;
|
|
try {
|
|
json j = json::parse(r.body);
|
|
if (j.contains("commit") && j["commit"].is_object()) {
|
|
const json& c = j["commit"];
|
|
if (c.contains("id") && c["id"].is_string()) sha = c["id"].get<std::string>();
|
|
if (c.contains("committer") && c["committer"].is_object() &&
|
|
c["committer"].contains("date") && c["committer"]["date"].is_string())
|
|
date = c["committer"]["date"].get<std::string>();
|
|
}
|
|
} catch (...) { return false; }
|
|
return !sha.empty();
|
|
}
|
|
|
|
// Последний релиз, УДОТВЕТВОРЯЮЩИЙ политике allow_prerelease.
|
|
// Важно: если allow_prerelease=false, prerelease-релизы не учитываются вовсе —
|
|
// иначе «доступна новая версия» могла бы указывать на тег, который ставить нельзя.
|
|
bool fetch_latest_release(const UpdateSettings& s, const HttpOptions& o,
|
|
SemVer& ver, std::string& tag, bool& prerelease, std::string& published) {
|
|
const std::string u = url_join(s.api_base, "releases");
|
|
HttpResponse r = http_get(u, o);
|
|
if (!r.ok || r.status != 200) return false;
|
|
try {
|
|
json j = json::parse(r.body);
|
|
if (!j.is_array()) return false;
|
|
for (const auto& rel : j) {
|
|
if (!rel.is_object()) continue;
|
|
const bool is_pre = rel.value("prerelease", false) || rel.value("draft", false);
|
|
if (is_pre && !s.allow_prerelease) continue;
|
|
const std::string t = rel.value("tag_name", "");
|
|
if (t.empty()) continue;
|
|
const SemVer v = semver_parse(t);
|
|
if (!v.valid) continue;
|
|
if (!ver.valid || semver_cmp(v, ver) > 0) {
|
|
ver = v; tag = t; prerelease = is_pre;
|
|
published = rel.value("published_at", "");
|
|
}
|
|
}
|
|
} catch (...) { return false; }
|
|
return ver.valid;
|
|
}
|
|
|
|
// Сколько коммитов между нашим и HEAD
|
|
int fetch_commits_between(const UpdateSettings& s, const HttpOptions& o,
|
|
const std::string& from_sha, const std::string& to_sha) {
|
|
if (from_sha.empty() || to_sha.empty() || from_sha == to_sha) return 0;
|
|
std::string u = s.api_base;
|
|
while (!u.empty() && u.back() == '/') u.pop_back();
|
|
u += "/compare/" + from_sha + "..." + to_sha;
|
|
HttpResponse r = http_get(u, o);
|
|
if (!r.ok || r.status != 200) return -1; // -1 = не удалось определить
|
|
try {
|
|
json j = json::parse(r.body);
|
|
if (j.contains("commits") && j["commits"].is_array())
|
|
return (int)j["commits"].size();
|
|
if (j.contains("ahead_by") && j["ahead_by"].is_number_integer())
|
|
return j["ahead_by"].get<int>();
|
|
if (j.contains("total_commits") && j["total_commits"].is_number_integer())
|
|
return j["total_commits"].get<int>();
|
|
} catch (...) {}
|
|
return -1;
|
|
}
|
|
|
|
std::string timestamp_dir() {
|
|
const time_t t = time(nullptr);
|
|
struct tm tmv;
|
|
localtime_r(&t, &tmv);
|
|
char buf[32];
|
|
strftime(buf, sizeof buf, "%Y%m%d-%H%M%S", &tmv);
|
|
return buf;
|
|
}
|
|
|
|
bool run(const std::string& cmd, std::string* out = nullptr) {
|
|
if (!out) return std::system(cmd.c_str()) == 0;
|
|
std::array<char, 256> buf{};
|
|
std::string res;
|
|
FILE* p = ::popen(cmd.c_str(), "r");
|
|
if (!p) return false;
|
|
while (fgets(buf.data(), (int)buf.size(), p)) res += buf.data();
|
|
const int rc = ::pclose(p);
|
|
while (!res.empty() && (res.back() == '\n' || res.back() == '\r')) res.pop_back();
|
|
*out = res;
|
|
return rc == 0;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
// ---------------------------------------------------------------------------
|
|
UpdateStatus check_for_update(const UpdateSettings& s, const std::string& local_version,
|
|
const std::string& local_commit) {
|
|
UpdateStatus st;
|
|
st.local = semver_parse(local_version);
|
|
st.local_commit = local_commit;
|
|
|
|
HttpOptions o;
|
|
o.timeout_sec = s.timeout_sec > 0 ? s.timeout_sec : 15;
|
|
o.verify_tls = s.verify_tls;
|
|
|
|
// 1) версия из ветки
|
|
HttpResponse r = http_get(raw_url(s), o);
|
|
if (!r.ok || r.status != 200 || r.body.empty()) {
|
|
// 2) запасной вариант — релизы
|
|
SemVer rv; std::string tag; bool pre = false; std::string published;
|
|
if (!fetch_latest_release(s, o, rv, tag, pre, published)) {
|
|
st.result = UpdateResult::CheckFailed;
|
|
st.error = "не удалось получить версию: " +
|
|
(r.error.empty() ? "HTTP " + std::to_string(r.status) : r.error);
|
|
return st;
|
|
}
|
|
st.remote = rv; st.remote_tag = tag; st.remote_prerelease = pre; st.published_at = published;
|
|
} else {
|
|
std::string body = r.body;
|
|
while (!body.empty() && (body.back() == '\n' || body.back() == '\r' || body.back() == ' '))
|
|
body.pop_back();
|
|
st.remote = semver_parse(body);
|
|
st.via = r.via;
|
|
|
|
// Узнаём последний релиз, удовлетворяющий политике.
|
|
SemVer rv; std::string tag; bool pre = false; std::string published;
|
|
const bool have_release = fetch_latest_release(s, o, rv, tag, pre, published);
|
|
|
|
// remote_version — это ТО, что мы реально поставим. Тег обязан ему
|
|
// соответствовать, иначе apply_update скачает другую версию.
|
|
if (have_release && semver_cmp(rv, st.remote) > 0) {
|
|
// Релиз новее HEAD ветки (ветка просто отстала) — берём релиз и его тег.
|
|
st.remote = rv;
|
|
st.remote_tag = tag;
|
|
st.remote_prerelease = pre;
|
|
st.published_at = published;
|
|
} else {
|
|
// HEAD ветки не старше релиза → ставим по тегу, совпадающему с версией.
|
|
// Ошибка прошлой версии этого кода: здесь проставлялся тег СТАРОГО
|
|
// релиза, и обновление откатывало пользователя назад.
|
|
st.remote_tag = semver_str(st.remote);
|
|
}
|
|
}
|
|
|
|
if (!st.remote.valid) {
|
|
st.result = UpdateResult::CheckFailed;
|
|
st.error = "не удалось разобрать удалённую версию '" + st.remote.raw + "'";
|
|
return st;
|
|
}
|
|
|
|
// HEAD ветки и расстояние в коммитах — справочно
|
|
std::string sha, date;
|
|
if (fetch_branch_head(s, o, sha, date)) {
|
|
st.remote_commit = sha;
|
|
st.commits_behind = fetch_commits_between(s, o, local_commit, sha);
|
|
}
|
|
|
|
// --- решение принимается ИСКЛЮЧИТЕЛЬНО по версии ---
|
|
const int c = semver_cmp(st.remote, st.local);
|
|
if (c > 0) {
|
|
st.result = UpdateResult::NewerAvailable;
|
|
st.message = "доступна версия " + semver_str(st.remote) +
|
|
(st.remote_tag.empty() ? "" : " (тег " + st.remote_tag + ")") +
|
|
", установлена " + semver_str(st.local);
|
|
} else if (c == 0) {
|
|
if (st.commits_behind > 0) {
|
|
st.result = UpdateResult::SameVersionNewCommits;
|
|
st.message = "версия та же (" + semver_str(st.local) + "), но в репозитории на " +
|
|
std::to_string(st.commits_behind) + " комм. дальше — НЕ обновляемся";
|
|
} else {
|
|
st.result = UpdateResult::UpToDate;
|
|
st.message = "установлена актуальная версия " + semver_str(st.local);
|
|
}
|
|
} else {
|
|
st.result = UpdateResult::LocalIsNewer;
|
|
st.message = "локальная " + semver_str(st.local) + " новее, чем " +
|
|
semver_str(st.remote) + " в репозитории";
|
|
}
|
|
return st;
|
|
}
|
|
|
|
// ===========================================================================
|
|
// Установка
|
|
// ===========================================================================
|
|
UpdateResult apply_update(const UpdateSettings& s, const UpdateStatus& st,
|
|
const std::string& install_dir, std::string& err, bool dry_run) {
|
|
if (st.result != UpdateResult::NewerAvailable) {
|
|
err = "обновление не требуется: " + st.message;
|
|
return UpdateResult::UpToDate;
|
|
}
|
|
if (st.remote_tag.empty()) {
|
|
// новая версия не помечена тегом — ставить нечего
|
|
err = "в репозитории нет тега для версии " + semver_str(st.remote) +
|
|
" — установка невозможна (обновляемся только по тегам релизов)";
|
|
return UpdateResult::InstallFailed;
|
|
}
|
|
|
|
std::string out;
|
|
if (!run("command -v git >/dev/null 2>&1")) {
|
|
err = "для обновления нужен git, но он не найден в PATH";
|
|
return UpdateResult::InstallFailed;
|
|
}
|
|
|
|
const std::string tmp = "/tmp/xenith_update_" + timestamp_dir();
|
|
std::string repo = s.repo;
|
|
if (repo.size() > 4 && repo.compare(repo.size() - 4, 4, ".git") != 0) repo += ".git";
|
|
|
|
const std::string clone_cmd = "git clone --quiet --depth 1 --branch " +
|
|
shell_quote(st.remote_tag) + " " + shell_quote(repo) + " " +
|
|
shell_quote(tmp) + " 2>&1";
|
|
if (dry_run) {
|
|
printf(" [dry-run] %s\n", clone_cmd.c_str());
|
|
printf(" [dry-run] замена содержимого %s (сохраняем: ", install_dir.c_str());
|
|
for (size_t i = 0; i < s.keep.size(); ++i) printf("%s%s", i ? ", " : "", s.keep[i].c_str());
|
|
printf(")\n");
|
|
return UpdateResult::Installed;
|
|
}
|
|
|
|
// --- 1. клонируем нужный тег (один вызов, вывод перехватываем) ---
|
|
std::string clone_log;
|
|
run(clone_cmd, &clone_log);
|
|
std::error_code ec0;
|
|
if (!fs::exists(tmp, ec0) || !fs::is_directory(tmp, ec0)) {
|
|
err = "git clone не удался: " + (clone_log.empty() ? "нет вывода, проверь сеть и тег" : clone_log);
|
|
fs::remove_all(tmp, ec0);
|
|
return UpdateResult::InstallFailed;
|
|
}
|
|
|
|
// в архиве Gitea верхний каталог может быть как "xenith", так и "<repo>-<tag>"
|
|
fs::path src = tmp;
|
|
{
|
|
std::error_code ec;
|
|
std::vector<fs::path> kids;
|
|
for (auto& e : fs::directory_iterator(tmp, ec)) {
|
|
if (e.path().filename() == ".git") continue; // служебный каталог клона
|
|
kids.push_back(e.path());
|
|
}
|
|
if (kids.size() == 1 && fs::is_directory(kids[0])) src = kids[0];
|
|
}
|
|
// .git клона в установку не тащим
|
|
{ std::error_code ecg; fs::remove_all(src / ".git", ecg); }
|
|
|
|
// --- 2. резервная копия текущего каталога ---
|
|
std::error_code ec;
|
|
const std::string backup = (s.backup_dir.empty() ? std::string("tmp/backup") : s.backup_dir)
|
|
+ "/" + timestamp_dir();
|
|
fs::create_directories(backup, ec);
|
|
if (ec) { err = "не удалось создать каталог резервной копии " + backup + ": " + ec.message();
|
|
fs::remove_all(tmp); return UpdateResult::InstallFailed; }
|
|
|
|
const auto is_kept = [&](const std::string& name) {
|
|
return std::find(s.keep.begin(), s.keep.end(), name) != s.keep.end();
|
|
};
|
|
|
|
// В резерв КОПИРУЕМ (не переносим!) только то, что сейчас будет заменено.
|
|
//
|
|
// Прежнее поведение было противоположным: в backup УЕЗЖАЛО всё, чего нет в
|
|
// новом дереве. Поскольку bin/ в .gitignore и в релизном теге его нет,
|
|
// рабочий бинарник Xenith объявлялся «лишним», переносился в резерв и
|
|
// исчезал из каталога установки, а вместо него насыпались исходники
|
|
// (main.cpp, xenith/, README.md). Программа при этом рапортовала
|
|
// «✓ Перезапусти xenith, чтобы подхватить новый бинарник».
|
|
//
|
|
// Теперь правило простое: обновление ЗАМЕНЯЕТ файлы новой версии и
|
|
// НИКОГДА не удаляет то, чего в новой версии нет.
|
|
for (auto& e : fs::directory_iterator(src, ec)) {
|
|
const std::string name = e.path().filename().string();
|
|
if (name == ".git") continue;
|
|
if (is_kept(name) && fs::exists(fs::path(install_dir) / name, ec)) continue;
|
|
const fs::path cur = fs::path(install_dir) / name;
|
|
if (!fs::exists(cur, ec)) continue;
|
|
fs::copy(cur, fs::path(backup) / name,
|
|
fs::copy_options::recursive | fs::copy_options::overwrite_existing, ec);
|
|
ec.clear();
|
|
}
|
|
|
|
// Честно предупреждаем, если в релизе нет собранного бинарника:
|
|
// обновление исходниками само по себе рабочую программу не заменяет.
|
|
bool has_binary = false;
|
|
for (auto& cand : {"bin/Xenith", "bin/xenith", "Xenith"})
|
|
if (fs::exists(src / cand, ec)) { has_binary = true; break; }
|
|
if (!has_binary)
|
|
printf(" %sв релизе %s нет собранного бинарника (bin/ в .gitignore) — "
|
|
"обновятся только исходники.%s\n Пересобери: cmake -B build && cmake --build build -j\n",
|
|
col::yellow(), st.remote_tag.c_str(), col::reset());
|
|
|
|
// --- 3. копируем новую версию поверх ---
|
|
// cp -a сохраняет права; исполняемый файл, который сейчас запущен, нельзя
|
|
// перезаписать (ETXTBSY), поэтому сначала удаляем его — на Linux это законно.
|
|
std::string cp_err;
|
|
for (auto& e : fs::directory_iterator(src, ec)) {
|
|
const std::string name = e.path().filename().string();
|
|
if (name == ".git") continue;
|
|
if (is_kept(name) && fs::exists(fs::path(install_dir) / name, ec)) continue;
|
|
const fs::path dst = fs::path(install_dir) / name;
|
|
// сначала пробуем удалить существующее (снимает ETXTBSY с бинарника)
|
|
std::error_code ec2;
|
|
if (fs::exists(dst, ec2)) fs::remove_all(dst, ec2);
|
|
const std::string cmd = "cp -a " + shell_quote(e.path().string()) + " " +
|
|
shell_quote(dst.string()) + " 2>&1";
|
|
std::string log;
|
|
if (!run(cmd, &log)) { cp_err += name + ": " + log + "; "; }
|
|
}
|
|
if (!cp_err.empty()) {
|
|
err = "не все файлы скопированы: " + cp_err +
|
|
" (резервная копия в " + backup + ")";
|
|
fs::remove_all(tmp);
|
|
return UpdateResult::InstallFailed;
|
|
}
|
|
|
|
// --- 4. права на бинарник ---
|
|
for (auto& cand : {"bin/Xenith", "bin/xenith", "Xenith"}) {
|
|
const fs::path p = fs::path(install_dir) / cand;
|
|
if (fs::exists(p, ec)) { fs::permissions(p, fs::perms::owner_all | fs::perms::group_read |
|
|
fs::perms::group_exec | fs::perms::others_read |
|
|
fs::perms::others_exec, ec); }
|
|
}
|
|
|
|
fs::remove_all(tmp);
|
|
return UpdateResult::Installed;
|
|
}
|
|
|
|
// ===========================================================================
|
|
void maybe_notify_update(const AppConfig& cfg) {
|
|
if (!cfg.update.enabled || cfg.update.policy == UpdatePolicy::None) return;
|
|
if (!cfg.update.check_on_start) return;
|
|
|
|
UpdateStatus st = check_for_update(cfg.update, cfg.version, cfg.commit);
|
|
if (st.result == UpdateResult::NewerAvailable) {
|
|
printf("%s%s%s доступна версия %s%s%s (установлена %s). Обновить: %sxenith update%s\n",
|
|
col::yellow(), sym::warn(), col::reset(),
|
|
col::bold(), semver_str(st.remote).c_str(), col::reset(),
|
|
semver_str(st.local).c_str(),
|
|
col::cyan(), col::reset());
|
|
} else if (st.result == UpdateResult::SameVersionNewCommits && st.commits_behind > 0) {
|
|
LOGD("в репозитории на %d комм. дальше, но версия та же (%s) — не обновляемся",
|
|
st.commits_behind, semver_str(st.local).c_str());
|
|
}
|
|
}
|
|
|
|
} // namespace xt
|