Files
opu/src/cli/main.cpp
T
yann64andClaude Opus 5.5 384aaf78c6 gtk: interface GTK4, préférences, versions, traductions, licence MIT
- interface gtkmm-4 : véhicules, ajout par VIN, mises à jour, dossier,
  téléchargement avec reprise et arrêt, choix de la clé, confirmation,
  écriture avec progression, fin avec guide d'installation ; travail
  dans un thread, résultats renvoyés via Glib::Dispatcher
- préférences : dossier de téléchargement, langue (système par défaut),
  recherche automatique de nouvelle version d'OpenPU
- recherche de nouvelle version (releases GitHub, format tags Gitea
  accepté) avec ouverture de la page dans le navigateur ;
  openpu-cli app-update
- versions : project(VERSION) + git describe régénéré à chaque build,
  openpu-cli --version, À propos, User-Agent, CHANGELOG, tools/release.sh
  (étiquette annotée, push vers tous les remotes, release GitHub)
- traductions gettext : textes anglais, fr.po complet (96 chaînes),
  extracteur de secours sans xgettext
- core : module job (téléchargement licence/fw/carte), liens des guides
  PDF, ordre des véhicules conservé (ordered_json)
- licence MIT (LICENSE, en-têtes SPDX) ; dépôt principal sur GitHub
- validé dans WSLg : parcours complet jusqu'à l'écriture d'une clé loop
  (FAT32 propre, fichiers téléchargés supprimés)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
2026-11-28 19:54:04 +01:00

449 lines
16 KiB
C++

// SPDX-License-Identifier: MIT
// openpu-cli — command-line front-end of libopenpu.
#include "openpu/api_client.hpp"
#include "openpu/app_update.hpp"
#include "openpu/archive.hpp"
#include "openpu/download.hpp"
#include "openpu/storage.hpp"
#include "openpu/usb.hpp"
#include "openpu/version.hpp"
#include "openpu/vin.hpp"
#include <algorithm>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace {
namespace fs = std::filesystem;
openpu::CancelToken gCancel;
extern "C" void onSignal(int /*sig*/)
{
gCancel.cancel();
}
void usage()
{
std::cerr << "usage: openpu-cli [--verbose] <command> [args]\n"
" openpu-cli --version\n"
"\n"
"commands:\n"
" check <VIN> identify the head unit and list available updates\n"
" download <VIN> [--dir D] [--firmware] [--map]\n"
" download license + updates (both kinds by default),\n"
" resuming partial files\n"
" verify <file.tar> check the integrity of an update archive\n"
" extract <file.tar> <dir> extract an update archive (skips UpdateInfo.xml)\n"
" usb-list list removable USB drives\n"
" write-usb <device> [--license F] [--label L] [--yes] [--no-eject] <archive.tar>...\n"
" ERASE <device>, format FAT32 and write the update\n"
" write-dir <dir> [--license F] <archive.tar>...\n"
" write the update into an existing directory\n"
" app-update check for a newer OpenPU (exit status 10 if any)\n"
" raw-devices <VIN> print the raw devices/{VIN} response\n"
" raw-updates <VIN> print the raw getAvailableUpdate response\n"
"\n"
"environment: OPENPU_DEVICES_URL, OPENPU_UPDATES_URL, OPENPU_CLIENT_ID,\n"
" http_proxy, https_proxy, no_proxy\n";
}
std::string humanSize(std::uint64_t bytes)
{
const char* units[] = {"B", "KB", "MB", "GB", "TB"};
auto value = static_cast<double>(bytes);
std::size_t unit = 0;
while (value >= 1000.0 && unit + 1 < std::size(units)) {
value /= 1000.0;
++unit;
}
char buf[32];
(void)std::snprintf(buf, sizeof buf, unit == 0 ? "%.0f %s" : "%.2f %s", value, units[unit]);
return buf;
}
std::string duration(std::chrono::seconds s)
{
const auto total = static_cast<long long>(s.count());
char buf[32];
(void)std::snprintf(buf, sizeof buf, "%lld:%02lld:%02lld", total / 3600, (total / 60) % 60, total % 60);
return buf;
}
void printUpdate(const char* label, const std::optional<openpu::UpdateInfo>& u)
{
if (!u) {
std::cout << label << ": none\n";
return;
}
std::cout << label << ": " << u->version << " (" << u->softwareType << ", " << humanSize(u->size) << ", "
<< (u->date.empty() ? "no date" : u->date) << ")\n";
}
int printRaw(const openpu::HttpResponse& r)
{
std::cerr << "HTTP " << r.status << '\n';
std::cout << r.body << '\n';
return r.status >= 200 && r.status < 300 ? 0 : 1;
}
void progressLine(const std::string& label, std::uint64_t done, std::uint64_t total, const std::string& extra)
{
const double pct = total > 0 ? 100.0 * static_cast<double>(done) / static_cast<double>(total) : 0.0;
(void)std::fprintf(stderr, "\r%s %5.1f%% %s / %s %s ", label.c_str(), pct, humanSize(done).c_str(),
humanSize(total).c_str(), extra.c_str());
(void)std::fflush(stderr);
}
struct Context {
std::unique_ptr<openpu::Transport> transport;
std::unique_ptr<openpu::ApiClient> api;
};
/// Identifies the vehicle; prints a message and returns Unknown when it cannot be updated.
openpu::HeadUnitType identify(openpu::ApiClient& api, const std::string& vin)
{
const openpu::VehicleCheck check = api.checkVehicle(vin);
if (!check.exists) {
std::cout << "vehicle not found\n";
return openpu::HeadUnitType::Unknown;
}
if (check.type == openpu::HeadUnitType::Unknown) {
std::cout << "vehicle found, but its head unit is not supported\n";
return check.type;
}
std::cout << "head unit: " << openpu::headUnitTypeName(check.type) << "\nguide: " << check.guideKey << '\n';
return check.type;
}
int cmdCheck(Context& ctx, const std::string& vin)
{
const auto type = identify(*ctx.api, vin);
if (type == openpu::HeadUnitType::Unknown)
return 1;
const openpu::AvailableUpdates updates = ctx.api->getUpdates(vin, type);
printUpdate("firmware", updates.firmware);
printUpdate("map", updates.map);
return 0;
}
int cmdDownload(Context& ctx, const std::string& vin, const std::vector<std::string>& opts)
{
fs::path dir;
bool wantFirmware = false;
bool wantMap = false;
for (std::size_t i = 0; i < opts.size(); ++i) {
if (opts[i] == "--dir" && i + 1 < opts.size()) {
dir = opts[++i];
} else if (opts[i] == "--firmware") {
wantFirmware = true;
} else if (opts[i] == "--map") {
wantMap = true;
} else {
usage();
return 2;
}
}
if (!wantFirmware && !wantMap)
wantFirmware = wantMap = true;
if (dir.empty())
dir = openpu::Settings::load(openpu::paths::configDir() / "config.json").effectiveDownloadDir();
const auto type = identify(*ctx.api, vin);
if (type == openpu::HeadUnitType::Unknown)
return 1;
const openpu::AvailableUpdates updates = ctx.api->getUpdates(vin, type);
printUpdate("firmware", updates.firmware);
printUpdate("map", updates.map);
std::vector<std::pair<std::string, openpu::UpdateInfo>> jobs;
if (wantFirmware && updates.firmware)
jobs.emplace_back("firmware", *updates.firmware);
if (wantMap && updates.map)
jobs.emplace_back("map", *updates.map);
if (jobs.empty()) {
std::cout << "nothing to download\n";
return 0;
}
std::error_code ec;
fs::create_directories(dir, ec);
const auto space = fs::space(dir, ec);
std::uint64_t needed = 0;
for (const auto& j : jobs)
needed += j.second.size;
needed += needed / 10; // same 10 % margin as the official app (partial files not deducted)
if (!ec && space.available < needed)
std::cerr << "warning: " << humanSize(space.available) << " available in " << dir << ", about "
<< humanSize(needed) << " needed\n";
openpu::Downloader downloader(*ctx.transport);
for (const auto& [label, update] : jobs) {
if (!update.licenseUrl.empty()) {
const auto lic = downloader.downloadSmall(update.licenseUrl, dir, std::nullopt, &gCancel);
std::cout << "license: " << lic.file.string() << '\n';
}
const std::string name = label;
const auto result = downloader.downloadResumable(
update.url, dir,
[&name](const openpu::DownloadProgress& p) {
const auto eta = p.remaining();
std::string extra = p.resumedFrom > 0 ? "resumed " : "";
if (eta)
extra += "ETA " + duration(*eta);
if (p.attempt > 0)
extra += " retry " + std::to_string(p.attempt);
progressLine(name, p.done, p.total, extra);
},
&gCancel);
(void)std::fprintf(stderr, "\n");
std::cout << label << ": " << result.file.string() << (result.alreadyComplete ? " (already complete)" : "")
<< '\n';
}
return 0;
}
openpu::ArchiveProgressCallback archiveProgress(const std::string& label)
{
return [label](const openpu::ArchiveProgress& p) {
progressLine(label, p.processed, p.total, std::to_string(p.entries) + " entries");
};
}
int cmdVerify(const fs::path& tar)
{
openpu::verifyTar(tar, archiveProgress("verify"), &gCancel);
(void)std::fprintf(stderr, "\n");
std::cout << "ok: " << humanSize(openpu::tarPayloadSize(tar)) << " to extract\n";
return 0;
}
int cmdExtract(const fs::path& tar, const fs::path& dest)
{
openpu::extractTar(tar, dest, archiveProgress("extract"), &gCancel);
(void)std::fprintf(stderr, "\n");
std::cout << "extracted to " << dest.string() << '\n';
return 0;
}
const char* stepName(openpu::UsbStep s)
{
switch (s) {
case openpu::UsbStep::Verifying: return "verify ";
case openpu::UsbStep::Formatting: return "format ";
case openpu::UsbStep::CopyingLicense: return "license";
case openpu::UsbStep::Extracting: return "write ";
case openpu::UsbStep::Ejecting: return "eject ";
case openpu::UsbStep::Done: return "done ";
}
return "";
}
openpu::UsbProgressCallback usbProgress()
{
return [last = openpu::UsbStep::Done](const openpu::UsbProgress& p) mutable {
if (p.step != last && last != openpu::UsbStep::Done)
(void)std::fprintf(stderr, "\n");
last = p.step;
std::string label = stepName(p.step);
if (p.archiveCount > 1 && (p.step == openpu::UsbStep::Verifying || p.step == openpu::UsbStep::Extracting))
label += " " + std::to_string(p.archiveIndex + 1) + "/" + std::to_string(p.archiveCount);
if (p.total > 0)
progressLine(label, p.done, p.total, "");
else
(void)std::fprintf(stderr, "\r%s %s ", label.c_str(), p.detail.c_str());
};
}
/// Parses "[--license F] [--label L] [--yes] [--no-eject] archives..." options.
struct WriteOptions {
openpu::UsbWritePlan plan;
std::string label;
bool yes = false;
bool eject = true;
bool ok = true;
};
WriteOptions parseWriteOptions(const std::vector<std::string>& opts)
{
WriteOptions w;
for (std::size_t i = 0; i < opts.size(); ++i) {
if (opts[i] == "--license" && i + 1 < opts.size())
w.plan.license = fs::path(opts[++i]);
else if (opts[i] == "--label" && i + 1 < opts.size())
w.label = opts[++i];
else if (opts[i] == "--yes")
w.yes = true;
else if (opts[i] == "--no-eject")
w.eject = false;
else if (opts[i].rfind("--", 0) == 0)
w.ok = false;
else
w.plan.archives.emplace_back(opts[i]);
}
if (w.plan.archives.empty() && !w.plan.license)
w.ok = false;
return w;
}
int cmdUsbList()
{
auto backend = openpu::makeUsbBackend();
const auto drives = backend->list();
if (drives.empty())
std::cout << "no removable USB drive found\n";
for (const auto& d : drives) {
std::cout << d.device << " " << d.description() << (d.label.empty() ? "" : " label=" + d.label);
for (const auto& mp : d.mountPoints)
std::cout << " mounted=" << mp.string();
std::cout << '\n';
}
return 0;
}
int cmdWriteUsb(const std::string& target, const std::vector<std::string>& opts)
{
WriteOptions w = parseWriteOptions(opts);
if (!w.ok) {
usage();
return 2;
}
auto backend = openpu::makeUsbBackend();
const auto drives = backend->list();
const auto it = std::find_if(drives.begin(), drives.end(),
[&](const openpu::UsbDrive& d) { return d.device == target || d.id == target; });
if (it == drives.end()) {
std::cerr << "error: " << target << " is not a removable USB drive (see usb-list)\n";
return 1;
}
const std::uint64_t payload = w.plan.payloadSize();
if (it->size < openpu::withMargin(payload)) {
std::cerr << "error: " << it->description() << " is too small: " << humanSize(openpu::withMargin(payload))
<< " needed (a " << humanSize(openpu::minimumStickSize(payload)) << " stick)\n";
return 1;
}
const std::string label = openpu::sanitizeLabel(w.label.empty() ? it->label : w.label);
if (!w.yes) {
std::cout << "ALL DATA ON " << it->description() << " WILL BE ERASED.\n"
<< "It will be formatted FAT32 with label " << label << ". Type YES to continue: " << std::flush;
std::string answer;
std::getline(std::cin, answer);
if (answer != "YES") {
std::cout << "aborted\n";
return 1;
}
}
openpu::writeToUsb(*backend, *it, label, w.plan, usbProgress(), &gCancel, w.eject);
(void)std::fprintf(stderr, "\n");
std::cout << "the USB stick is ready" << (w.eject ? " and can be removed" : "") << '\n';
return 0;
}
int cmdWriteDir(const fs::path& dir, const std::vector<std::string>& opts)
{
WriteOptions w = parseWriteOptions(opts);
if (!w.ok) {
usage();
return 2;
}
openpu::writePayload(dir, w.plan, usbProgress(), &gCancel);
(void)std::fprintf(stderr, "\n");
std::cout << "written to " << dir.string() << '\n';
return 0;
}
int run(std::vector<std::string> args)
{
openpu::CurlOptions curlOptions;
if (!args.empty() && args.front() == "--verbose") {
curlOptions.verbose = true;
args.erase(args.begin());
}
if (args.size() == 1 && (args[0] == "--version" || args[0] == "version")) {
std::cout << "openpu-cli " << openpu::versionDescription() << '\n';
return 0;
}
if (args.size() == 1 && args[0] == "app-update") {
auto transport = openpu::makeCurlTransport(curlOptions);
const auto release = openpu::checkForNewerRelease(*transport, openpu::AppUpdateConfig::fromEnvironment(),
openpu::version());
if (!release) {
std::cout << "OpenPU " << openpu::version() << " is up to date\n";
return 0;
}
std::cout << "OpenPU " << release->version.toString() << " is available (this is " << openpu::version()
<< "): " << release->pageUrl << '\n';
return 10;
}
if (args.size() == 1 && args[0] == "usb-list")
return cmdUsbList();
if (args.size() < 2) {
usage();
return 2;
}
const std::string command = args[0];
if (command == "write-usb")
return cmdWriteUsb(args[1], {args.begin() + 2, args.end()});
if (command == "write-dir")
return cmdWriteDir(args[1], {args.begin() + 2, args.end()});
if (command == "verify" && args.size() == 2)
return cmdVerify(args[1]);
if (command == "extract" && args.size() == 3)
return cmdExtract(args[1], args[2]);
const std::string vin = openpu::normalizeVin(args[1]);
if (!openpu::isValidVin(vin)) {
std::cerr << "error: invalid VIN (expected V[FR]3 followed by 14 letters/digits)\n";
return 2;
}
Context ctx;
ctx.transport = openpu::makeCurlTransport(curlOptions);
ctx.api = std::make_unique<openpu::ApiClient>(*ctx.transport, openpu::ApiConfig::fromEnvironment());
if (command == "check" && args.size() == 2)
return cmdCheck(ctx, vin);
if (command == "download")
return cmdDownload(ctx, vin, {args.begin() + 2, args.end()});
if (command == "raw-devices" && args.size() == 2)
return printRaw(ctx.api->rawDevices(vin));
if (command == "raw-updates" && args.size() == 2)
return printRaw(ctx.api->rawUpdates(vin, openpu::software::all()));
usage();
return 2;
}
} // namespace
int main(int argc, char** argv)
{
(void)std::signal(SIGINT, onSignal);
(void)std::signal(SIGTERM, onSignal);
try {
return run({argv + 1, argv + argc});
} catch (const openpu::Cancelled&) {
std::cerr << "\ncancelled\n";
return 130;
} catch (const openpu::ApiError& e) {
std::cerr << "error: " << e.what() << '\n';
} catch (const openpu::DownloadError& e) {
std::cerr << "\ndownload error: " << e.what() << '\n';
} catch (const openpu::ArchiveError& e) {
std::cerr << "\narchive error (" << (e.kind() == openpu::ArchiveError::Kind::Corrupt ? "corrupt" : "I/O")
<< "): " << e.what() << '\n';
} catch (const openpu::UsbError& e) {
std::cerr << "\nUSB error: " << e.what() << '\n';
} catch (const openpu::NetworkError& e) {
std::cerr << "network error: " << e.what() << '\n';
} catch (const std::runtime_error& e) { // StorageError, ParseError, app-update errors...
std::cerr << "error: " << e.what() << '\n';
}
return 1;
}