// update.cpp — self-update без git: манифест + пофайловые sha256 + кэш. // // Почему не git: пользователю не нужен git в PATH, не нужен .git в каталоге, // а обновление тянет только те файлы, которые реально изменились. Репозиторий // (Gitea) публикует updates/manifest.json: // // { // "version": "3.1.0", // "tag": "v3.1.0", // "files_base": "https://.../raw/branch/master", // "files": [ // {"path": "bin/Xenith", "sha256": "...", "size": 123, "mode": "755", // "platform": "linux-x64"} // ] // } // // Апдейтер считает sha256 локальных файлов, качает только отличающиеся, // проверяет хэш, кладёт в кэш по sha256 и атомарно подменяет файл. Ничего не // удаляет: файлы, которых нет в манифесте, остаются на месте. #include "update.h" #include "http_client.h" #include "platform.h" #include "sha256.h" #include "../ui/ui.h" #include #include #include #include #include #include #include #include #include #include #include #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; 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; if (a.pre.empty() && b.pre.empty()) return 0; if (a.pre.empty()) return 1; if (b.pre.empty()) return -1; std::vector A, B; for (const std::string* src : {&a.pre, &b.pre}) { std::vector& 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 "?"; } std::string current_platform() { #if defined(_WIN32) const char* os = "windows"; #elif defined(__APPLE__) const char* os = "macos"; #else const char* os = "linux"; #endif #if defined(__aarch64__) || defined(_M_ARM64) return std::string(os) + "-arm64"; #elif defined(__arm__) || defined(_M_ARM) return std::string(os) + "-arm"; #else return std::string(os) + "-x64"; #endif } // =========================================================================== // Манифест // =========================================================================== namespace { std::string strip_git(std::string 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; } std::string default_manifest_url(const UpdateSettings& s) { if (!s.manifest_url.empty()) return s.manifest_url; return strip_git(s.repo) + "/raw/branch/" + s.branch + "/updates/manifest.json"; } std::string default_files_base(const UpdateSettings& s) { if (!s.files_base.empty()) return s.files_base; return strip_git(s.repo) + "/raw/branch/" + s.branch; } bool platform_matches(const std::string& want) { if (want.empty() || want == "any" || want == "*") return true; return want == current_platform(); } // Безопасный относительный путь из манифеста: без "..", без абсолютных путей. bool safe_rel_path(const std::string& p) { if (p.empty() || p.size() > 4096) return false; if (p[0] == '/' || p[0] == '\\') return false; if (p.size() >= 2 && p[1] == ':') return false; // C:\... fs::path fp = path_from_utf8(p); for (const auto& part : fp) { if (part == "..") return false; } return true; } bool is_probably_hex64(const std::string& s) { if (s.size() != 64) return false; for (char c : s) if (!std::isxdigit((unsigned char)c)) return false; return true; } std::string lower_ascii(std::string s) { for (char& c : s) c = (char)std::tolower((unsigned char)c); return s; } std::string timestamp_dir() { const time_t t = time(nullptr); struct tm tmv; #ifdef _WIN32 localtime_s(&tmv, &t); #else localtime_r(&t, &tmv); #endif char buf[32]; strftime(buf, sizeof buf, "%Y%m%d-%H%M%S", &tmv); return buf; } // Каталог с учётом того, что относительный путь считается от install_dir. fs::path under(const std::string& base, const std::string& rel) { fs::path p = path_from_utf8(rel); if (p.is_absolute()) return p; return path_from_utf8(base) / p; } // Относительные install_dir/backup_dir/cache_dir разрешаем от каталога установки. std::string resolve_dir(const std::string& install_dir, const std::string& d) { if (d.empty()) return install_dir; fs::path p = path_from_utf8(d); if (p.is_absolute()) return path_to_utf8(p); return path_to_utf8(path_from_utf8(install_dir) / p); } } // namespace UpdateManifest fetch_update_manifest(const UpdateSettings& s, const std::string& platform) { UpdateManifest m; HttpOptions o; o.timeout_sec = s.timeout_sec > 0 ? s.timeout_sec : 15; o.verify_tls = s.verify_tls; const std::string url = default_manifest_url(s); HttpResponse r = http_get(url, o); if (!r.ok || r.status != 200 || r.body.empty()) { m.error = "не удалось получить манифест " + url + ": " + (r.error.empty() ? "HTTP " + std::to_string(r.status) : r.error); return m; } try { json j = json::parse(r.body); if (!j.is_object()) { m.error = "манифест — не JSON-объект"; return m; } m.version = j.value("version", ""); m.tag = j.value("tag", ""); m.published_at = j.value("published_at", ""); m.notes = j.value("notes", ""); m.files_base = j.value("files_base", ""); if (!j.contains("files") || !j["files"].is_array()) { m.error = "в манифесте нет массива files"; return m; } if (j["files"].size() > 20000) { m.error = "в манифесте слишком много файлов"; return m; } for (const auto& e : j["files"]) { if (!e.is_object()) continue; UpdateFile f; f.path = e.value("path", ""); f.sha256 = lower_ascii(e.value("sha256", "")); f.size = e.value("size", (uint64_t)0); f.url = e.value("url", ""); f.platform = e.value("platform", ""); f.mode = e.value("mode", ""); f.optional = e.value("optional", false); if (!safe_rel_path(f.path)) { m.error = "небезопасный путь в манифесте: '" + f.path + "'"; return m; } if (!is_probably_hex64(f.sha256)) { m.error = "плохой sha256 для '" + f.path + "'"; return m; } if (!platform.empty() && !platform_matches(f.platform)) continue; m.files.push_back(std::move(f)); } if (m.version.empty()) { m.error = "в манифесте нет version"; return m; } if (!semver_parse(m.version).valid) { m.error = "версия манифеста не SemVer: '" + m.version + "'"; return m; } if (m.files.empty()) { m.error = "манифест не содержит файлов для " + (platform.empty() ? current_platform() : platform); return m; } m.valid = true; } catch (const std::exception& e) { m.error = std::string("разбор манифеста: ") + e.what(); } return m; } // =========================================================================== // Проверка (совместимость: fallback на version.txt/API, если манифеста нет) // =========================================================================== 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) { return strip_git(s.repo) + "/raw/branch/" + s.branch + "/" + s.version_path; } 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(); if (c.contains("committer") && c["committer"].is_object() && c["committer"].contains("date") && c["committer"]["date"].is_string()) date = c["committer"]["date"].get(); } } catch (...) { return false; } return !sha.empty(); } 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; } // Считаем, какие файлы манифеста отличаются от локальных. Нужно и для // «сколько качать», и для dry-run. struct ChangedInfo { int total = 0; int changed = 0; uint64_t bytes = 0; }; ChangedInfo count_changes(const UpdateManifest& m, const std::string& install_dir) { ChangedInfo c; if (install_dir.empty()) return c; c.total = (int)m.files.size(); for (const auto& f : m.files) { const fs::path p = under(install_dir, f.path); std::error_code ec; if (!fs::exists(p, ec)) { if (!f.optional) { ++c.changed; c.bytes += f.size; } continue; } std::string h, err; if (!sha256_file(path_to_utf8(p), h, err) || h != f.sha256) { ++c.changed; c.bytes += f.size; } } return c; } } // namespace UpdateStatus check_for_update(const UpdateSettings& s, const std::string& local_version, const std::string& local_commit, const std::string& install_dir) { 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) Манифест — основной путь. Он не зависит от git и даёт пофайловые хэши. UpdateManifest m = fetch_update_manifest(s); if (m.valid) { st.manifest_used = true; st.via = "manifest"; st.remote = semver_parse(m.version); st.remote_tag = m.tag.empty() ? ("v" + semver_str(st.remote)) : m.tag; st.published_at = m.published_at; st.total_files = (int)m.files.size(); const ChangedInfo ci = count_changes(m, install_dir); st.changed_files = ci.changed; st.changed_bytes = ci.bytes; // HEAD ветки — справочно, не влияет на решение. std::string sha, date; if (fetch_branch_head(s, o, sha, date)) st.remote_commit = sha; const int c = semver_cmp(st.remote, st.local); if (c > 0) { st.result = UpdateResult::NewerAvailable; std::ostringstream msg; msg << "доступна версия " << semver_str(st.remote); if (!st.remote_tag.empty()) msg << " (тег " << st.remote_tag << ")"; msg << ", установлена " << semver_str(st.local); if (st.total_files > 0) { msg << "; файлов в манифесте " << st.total_files; if (!install_dir.empty()) msg << ", изменилось " << st.changed_files << " (" << (st.changed_bytes / 1024) << " КиБ)"; } st.message = msg.str(); } else if (c == 0) { st.result = UpdateResult::UpToDate; st.message = "установлена актуальная версия " + semver_str(st.local); if (!install_dir.empty() && st.changed_files > 0) st.message += " (файлы отличаются: " + std::to_string(st.changed_files) + ", но версия та же — не обновляюсь)"; } else { st.result = UpdateResult::LocalIsNewer; st.message = "локальная " + semver_str(st.local) + " новее, чем " + semver_str(st.remote) + " в репозитории"; } return st; } // 2) Манифеста нет — старый путь по version.txt + релизам Gitea. HttpResponse r = http_get(raw_url(s), o); if (!r.ok || r.status != 200 || r.body.empty()) { 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 = "не удалось получить ни манифест (" + m.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); if (have_release && semver_cmp(rv, st.remote) > 0) { st.remote = rv; st.remote_tag = tag; st.remote_prerelease = pre; st.published_at = published; } else { st.remote_tag = semver_str(st.remote); } } if (!st.remote.valid) { st.result = UpdateResult::CheckFailed; st.error = "не удалось разобрать удалённую версию '" + st.remote.raw + "'"; return st; } std::string sha, date; if (fetch_branch_head(s, o, sha, date)) st.remote_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) { 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; } // =========================================================================== // Установка по манифесту // =========================================================================== namespace { bool download_to(const std::string& url, const fs::path& dest, const HttpOptions& o, std::string& err) { std::error_code ec; if (!dest.parent_path().empty()) fs::create_directories(dest.parent_path(), ec); std::string via; if (!http_download(url, path_to_utf8(dest), o, err, &via)) return false; return true; } bool verify_file(const fs::path& p, const std::string& want, std::string& err) { std::string h; if (!sha256_file(path_to_utf8(p), h, err)) return false; if (h != lower_ascii(want)) { err = "sha256 не совпал: получен " + h + ", ожидался " + want; return false; } return true; } void set_mode(const fs::path& p, const std::string& mode) { if (mode.empty()) return; std::error_code ec; if (mode == "755" || mode == "0755" || mode == "777" || mode == "0777") { fs::permissions(p, fs::perms::owner_all | fs::perms::group_read | fs::perms::group_exec | fs::perms::others_read | fs::perms::others_exec, ec); } else if (mode == "644" || mode == "0644") { fs::permissions(p, fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read | fs::perms::others_read, ec); } } // Копирование/переименование с заменой. На Windows rename поверх файла // запрещён, поэтому сначала пытаемся rename, затем remove+copy. bool replace_file(const fs::path& src, const fs::path& dst, std::string& err) { std::error_code ec; fs::create_directories(dst.parent_path(), ec); ec.clear(); fs::rename(src, dst, ec); if (!ec) return true; ec.clear(); fs::remove(dst, ec); // запущенный бинарник на Linux удалять можно ec.clear(); fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec); if (ec) { err = "не удалось заменить " + path_to_utf8(dst) + ": " + ec.message(); return false; } fs::remove(src, ec); return true; } #ifdef _WIN32 // Запущенный .exe нельзя ни удалить, ни переименовать. Оставляем рядом // .xenith-new и запускаем маленький .bat, который дождётся выхода // процесса, подменит файл и перезапустит программу. bool schedule_self_replace(const fs::path& staged, const fs::path& dst, std::string& err) { const fs::path bat = dst.parent_path() / "xenith_update.bat"; std::ofstream f(bat, std::ios::binary | std::ios::trunc); if (!f) { err = "не удалось создать helper для замены exe"; return false; } f << "@echo off\r\n" << "chcp 65001 >NUL\r\n" << "ping -n 3 127.0.0.1 >NUL\r\n" << "move /Y \"" << path_to_utf8(staged) << "\" \"" << path_to_utf8(dst) << "\" >NUL\r\n" << "start \"\" \"" << path_to_utf8(dst) << "\"\r\n" << "del \"%~f0\" >NUL\r\n"; f.close(); const std::string cmd = "cmd /c start \"\" /b \"" + path_to_utf8(bat) + "\""; if (std::system(cmd.c_str()) != 0) { err = "не удалось запустить helper"; return false; } return true; } #endif } // namespace 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; } UpdateManifest m = fetch_update_manifest(s); if (!m.valid) { err = "нет манифеста обновления: " + m.error + "\n Обновление без git работает только по updates/manifest.json.\n" " Проверьте update.manifest_url / update.repo в config.yaml."; return UpdateResult::InstallFailed; } // Манифест мог обновиться между check и apply — доверяем свежему. const SemVer remote_now = semver_parse(m.version); if (!remote_now.valid || semver_cmp(remote_now, st.local) <= 0) { err = "манифест уже не новее локальной версии (" + m.version + ")"; return UpdateResult::UpToDate; } const std::string base = default_files_base(s); const std::string backup_root = resolve_dir(install_dir, s.backup_dir) + "/" + timestamp_dir(); const std::string cache_root = s.use_cache ? resolve_dir(install_dir, s.cache_dir) : ""; const fs::path cache_objects = cache_root.empty() ? fs::path() : path_from_utf8(cache_root) / "objects"; HttpOptions o; o.timeout_sec = s.timeout_sec > 0 ? s.timeout_sec : 60; o.verify_tls = s.verify_tls; int changed = 0, downloaded = 0, cached = 0; uint64_t bytes = 0; std::vector failed; for (const auto& f : m.files) { const fs::path dst = under(install_dir, f.path); std::error_code ec; const bool exists = fs::exists(dst, ec); // 1) Файл уже правильный — пропускаем. Это и есть «не менять всё». if (exists) { std::string h, herr; if (sha256_file(path_to_utf8(dst), h, herr) && h == f.sha256) continue; } else if (f.optional) { continue; } ++changed; bytes += f.size; if (dry_run) { printf(" [dry-run] %s %s (%llu байт)\n", exists ? "заменить" : "создать", f.path.c_str(), (unsigned long long)f.size); continue; } // 2) Объект в кэше по sha256? Тогда сеть не нужна. fs::path staged = dst; staged += ".xenith-new"; bool have = false; if (!cache_root.empty()) { const fs::path obj = cache_objects / f.sha256; if (fs::exists(obj, ec)) { std::string herr; if (verify_file(obj, f.sha256, herr)) { fs::create_directories(staged.parent_path(), ec); fs::copy_file(obj, staged, fs::copy_options::overwrite_existing, ec); have = !ec; if (have) ++cached; } } } // 3) Иначе — скачать и проверить. if (!have) { const std::string url = f.url.empty() ? (base + "/" + f.path) : f.url; std::string derr; if (!download_to(url, staged, o, derr)) { failed.push_back(f.path + ": " + derr); fs::remove(staged, ec); continue; } if (!verify_file(staged, f.sha256, derr)) { failed.push_back(f.path + ": " + derr); fs::remove(staged, ec); continue; } ++downloaded; if (!cache_root.empty()) { std::error_code ec2; fs::create_directories(cache_objects, ec2); fs::path obj = cache_objects / f.sha256; if (!fs::exists(obj, ec2)) fs::copy_file(staged, obj, fs::copy_options::overwrite_existing, ec2); } } // 4) Backup старого файла (плоское имя, чтобы не плодить деревья). if (exists) { std::error_code ec2; fs::create_directories(backup_root, ec2); const std::string flat = f.path; std::string safe = flat; std::replace(safe.begin(), safe.end(), '/', '_'); std::replace(safe.begin(), safe.end(), '\\', '_'); fs::copy_file(dst, path_from_utf8(backup_root) / safe, fs::copy_options::overwrite_existing, ec2); if (ec2) { failed.push_back(f.path + ": не удалось сделать backup: " + ec2.message()); fs::remove(staged, ec2); continue; } } // 5) Атомарная подмена (насколько это возможно кроссплатформенно). if (!replace_file(staged, dst, err)) { #ifdef _WIN32 // Запущенный Xenith.exe заблокирован — откладываем до перезапуска. if (dst.extension() == ".exe") { std::string serr; if (schedule_self_replace(staged, dst, serr)) { printf(" обновлён (после перезапуска) %s\n", f.path.c_str()); continue; } } #endif failed.push_back(f.path + ": " + err); continue; } set_mode(dst, f.mode); printf(" %s %s\n", exists ? "обновлён" : "создан", f.path.c_str()); } if (!failed.empty()) { std::ostringstream e; e << "не удалось обновить " << failed.size() << " файл(ов):\n"; for (size_t i = 0; i < failed.size() && i < 12; ++i) e << " - " << failed[i] << "\n"; if (failed.size() > 12) e << " ...\n"; e << "резервная копия: " << backup_root; err = e.str(); return UpdateResult::InstallFailed; } if (dry_run) { printf(" [dry-run] итого: %d файл(ов), %llu байт\n", changed, (unsigned long long)bytes); return UpdateResult::Installed; } printf(" %s обновлено файлов: %d (скачано %d, из кэша %d, всего %llu КиБ)%s\n", col::green(), changed, downloaded, cached, (unsigned long long)(bytes / 1024), col::reset()); (void)st; return UpdateResult::Installed; } // =========================================================================== // Генерация манифеста (для публикации релиза) // =========================================================================== bool write_update_manifest(const std::string& dir, const std::string& out, const std::string& version, const std::string& tag, const std::string& base_url, std::string& err) { std::error_code ec; const fs::path root = path_from_utf8(dir); if (!fs::is_directory(root, ec)) { err = "не каталог: " + dir; return false; } if (!semver_parse(version).valid) { err = "версия не SemVer: " + version; return false; } // Что не тащим в манифест: служебное, модели, кэш, бэкапы, конфиг. auto skip_name = [](const std::string& n) { return n == ".git" || n == "updates" || n == "tmp" || n == "models" || n == "logs" || n == "update-cache" || n == "__pycache__"; }; auto skip_file = [](const std::string& n) { if (n == "config.yaml" || n == "manifest.json") return true; if (n.size() > 4 && n.substr(n.size() - 4) == ".xnh") return true; if (n.size() > 5 && n.substr(n.size() - 5) == ".gguf") return true; return false; }; json files = json::array(); uint64_t total = 0; for (auto it = fs::recursive_directory_iterator(root, ec); !ec && it != fs::recursive_directory_iterator(); ++it) { const fs::path p = it->path(); const std::string name = path_to_utf8(p.filename()); if (it->is_directory(ec)) { if (skip_name(name)) it.disable_recursion_pending(); continue; } if (!it->is_regular_file(ec)) continue; if (skip_file(name)) continue; const std::string rel = path_to_utf8(fs::relative(p, root, ec)); if (ec || rel.empty() || rel.rfind("..", 0) == 0) { ec.clear(); continue; } std::string h; if (!sha256_file(path_to_utf8(p), h, err)) return false; const uint64_t sz = (uint64_t)fs::file_size(p, ec); if (ec) { ec.clear(); continue; } json e = {{"path", rel}, {"sha256", h}, {"size", sz}, {"platform", current_platform()}}; // права: исполняемые файлы помечаем 755 (на Windows поле игнорируется) const auto perms = fs::status(p, ec).permissions(); if (!ec && ((perms & fs::perms::owner_exec) != fs::perms::none)) e["mode"] = "755"; files.push_back(std::move(e)); total += sz; } if (ec) { err = "обход каталога: " + ec.message(); return false; } if (files.empty()) { err = "в каталоге нет файлов для манифеста"; return false; } std::sort(files.begin(), files.end(), [](const json& a, const json& b) { return a["path"].get() < b["path"].get(); }); json j = { {"version", version}, {"tag", tag.empty() ? ("v" + version) : tag}, {"platform", current_platform()}, {"generated_at", timestamp_dir()}, {"files_base", base_url}, {"files", files} }; if (base_url.empty()) j.erase("files_base"); std::error_code e2; fs::path outp = path_from_utf8(out); if (!outp.parent_path().empty()) fs::create_directories(outp.parent_path(), e2); std::ofstream f(outp, std::ios::binary | std::ios::trunc); if (!f) { err = "не открывается на запись: " + out; return false; } f << j.dump(2) << "\n"; if (!f) { err = "ошибка записи: " + out; return false; } printf("манифест: %s (%zu файлов, %.2f МиБ)\n", out.c_str(), files.size(), total / 1048576.0); return true; } // =========================================================================== 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()); } } } // namespace xt