#include "cli-application.h" #include "app-core.h" #include "cli-command.h" #include #include #include #include #include #include #include #include #include namespace { // ---- Output ----------------------------------------------------------------- // stdio rather than QTextStream: the command line is meant to be piped, and a // byte-per-byte fputs keeps the exit status and the stdout/stderr split exactly // what a shell script expects. void printLine(const QString& text) { std::fputs(text.toUtf8().constData(), stdout); std::fputc('\n', stdout); std::fflush(stdout); } void printErr(const QString& text) { std::fputs(text.toUtf8().constData(), stderr); std::fputc('\n', stderr); std::fflush(stderr); } QString providerName(const PackageInfo& package) { if (!package.provider.empty()) return QString::fromStdString(package.provider); if (!package.providers.empty()) return QString::fromStdString(package.providers.front()); return QStringLiteral("?"); } // ---- Terminal interaction --------------------------------------------------- // The password is read with echo off, the way sudo does, and never leaves the // process: it goes straight to the core and is dropped after the operation. QString readPassword(const QString& prompt) { std::fputs(prompt.toUtf8().constData(), stderr); std::fflush(stderr); const bool interactive = isatty(STDIN_FILENO) == 1; termios saved{}; const bool restore = interactive && tcgetattr(STDIN_FILENO, &saved) == 0; if (restore) { termios hidden = saved; hidden.c_lflag &= ~static_cast(ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &hidden); } std::string line; char buffer[256]; if (std::fgets(buffer, sizeof(buffer), stdin)) line = buffer; if (restore) { tcsetattr(STDIN_FILENO, TCSANOW, &saved); std::fputc('\n', stderr); } QString password = QString::fromUtf8(line.c_str()); password.remove(QLatin1Char('\n')); password.remove(QLatin1Char('\r')); return password; } // A confirmation is only asked on a terminal: a pipe that did not pass --yes is // refused rather than left waiting forever on stdin. bool confirm(const QString& question, bool assumeYes) { if (assumeYes) return true; if (isatty(STDIN_FILENO) != 1) { printErr(QStringLiteral("%1 — refusé : confirmez avec --yes dans un script.") .arg(question)); return false; } std::fputs((question + QStringLiteral(" [o/N] ")).toUtf8().constData(), stderr); std::fflush(stderr); char buffer[64]; if (!std::fgets(buffer, sizeof(buffer), stdin)) return false; const QString answer = QString::fromUtf8(buffer).trimmed().toLower(); return answer == QLatin1String("o") || answer == QLatin1String("oui") || answer == QLatin1String("y") || answer == QLatin1String("yes"); } // ---- Tables ----------------------------------------------------------------- void printPackages(const std::vector& packages, bool withRepository) { if (packages.empty()) { printLine(QStringLiteral("Aucun paquet.")); return; } // Seeded with the header labels so the columns line up even when every // value is shorter than its heading. int nameWidth = static_cast(QStringLiteral("NOM").size()); int versionWidth = static_cast(QStringLiteral("VERSION").size()); int providerWidth = static_cast(QStringLiteral("FOURNISSEUR").size()); int repoWidth = static_cast(QStringLiteral("DÉPÔT").size()); for (const PackageInfo& package : packages) { nameWidth = std::max(nameWidth, static_cast(package.name.size())); versionWidth = std::max(versionWidth, static_cast(package.version.size())); providerWidth = std::max(providerWidth, static_cast(providerName(package).size())); repoWidth = std::max(repoWidth, static_cast(package.repository.size())); } auto row = [&](const QString& name, const QString& version, const QString& provider, const QString& repository, const QString& state) { QString line = name.leftJustified(nameWidth) + QLatin1String(" ") + version.leftJustified(versionWidth) + QLatin1String(" ") + provider.leftJustified(providerWidth); if (withRepository) { line += QLatin1String(" ") + repository.leftJustified(repoWidth); } if (!state.isEmpty()) line += QLatin1String(" ") + state; return line; }; printLine(row(QStringLiteral("NOM"), QStringLiteral("VERSION"), QStringLiteral("FOURNISSEUR"), withRepository ? QStringLiteral("DÉPÔT") : QString(), QStringLiteral("ÉTAT"))); for (const PackageInfo& package : packages) { // A cleanup row carries its reason; a regular one its installed/outdated // state, so the same table serves every listing. QString state; if (!package.cleanupReason.empty()) { state = QString::fromStdString(package.cleanupReason); } else if (package.updateAvailable) { state = QStringLiteral("mise à jour dispo"); } else if (package.installed) { state = QStringLiteral("installé"); } printLine(row(QString::fromStdString(package.name), QString::fromStdString(package.version), providerName(package), QString::fromStdString(package.repository), state)); } } // ---- Waiting for the asynchronous core -------------------------------------- // AppCore reports through signals on the event loop; the command line waits for // the one it asked for. The loop is the connection's context, so every // connection is dropped as soon as the wait is over. bool collectSearch(AppCore& core, const QString& query, std::vector* results, QString* error) { QEventLoop loop; QObject::connect(&core, &AppCore::searchFinished, &loop, [&](std::vector found) { *results = std::move(found); loop.quit(); }); const AppCore::StartResult started = core.search(query); if (!started.started) { if (error) *error = started.error; return false; } loop.exec(); return true; } // Turns a name typed on the command line into the package the core can act on: // a search, then the exact match. The provider is the one that search tagged, // so `install` routes to pacman or Flatpak without the user naming either. bool resolvePackage(AppCore& core, const QString& name, PackageInfo* package, QString* error) { std::vector results; if (!collectSearch(core, name.trimmed(), &results, error)) return false; const QString wanted = name.trimmed().toLower(); for (const PackageInfo& candidate : results) { if (QString::fromStdString(candidate.name).toLower() == wanted) { *package = candidate; return true; } } if (error) { *error = QStringLiteral("Paquet introuvable : %1").arg(name); } return false; } struct Outcome { bool success = false; bool locked = false; QString error; }; // Starts an action, answers the sudo prompt when the core asks for one, and // waits for the verdict. Progress lines are forwarded so a long install reads // like a terminal session — the same output the journal keeps. Outcome runAction(AppCore& core, const QString& label, const std::function& start) { Outcome outcome; QEventLoop loop; QObject::connect(&core, &AppCore::actionProgress, &loop, [](const QString& message, int percent) { Q_UNUSED(percent); if (!message.isEmpty()) printLine(QStringLiteral(" %1").arg(message)); }); QObject::connect(&core, &AppCore::actionFinished, &loop, [&](const QString&, const QString&, bool success, const QString& error, bool locked) { outcome.success = success; outcome.error = error; outcome.locked = locked; loop.quit(); }); AppCore::StartResult started = start(); if (!started.started && started.needsPassword) { const QString password = readPassword(QStringLiteral("Mot de passe sudo pour %1 : ").arg(label)); if (password.isEmpty()) { outcome.error = QStringLiteral("Opération annulée : identifiants requis."); return outcome; } core.setSudoPassword(password); started = core.retryPendingRequest(); } if (!started.started) { // Refused before running: the reason is the one the window would show. outcome.error = started.error; outcome.locked = started.locked; return outcome; } loop.exec(); return outcome; } int reportAction(const Outcome& outcome, const QString& successText) { if (outcome.success) { printLine(successText); return 0; } if (outcome.locked) { printErr(QStringLiteral("Base pacman verrouillée : %1").arg(outcome.error)); } else if (!outcome.error.isEmpty()) { printErr(outcome.error); } else { printErr(QStringLiteral("L'opération a échoué.")); } return 1; } // ---- Commands --------------------------------------------------------------- int runSearch(AppCore& core, const cli::Parsed& parsed) { std::vector results; QString error; if (!collectSearch(core, parsed.operands.join(QLatin1Char(' ')), &results, &error)) { printErr(error); return 1; } printPackages(results, /*withRepository=*/true); return 0; } int runInstall(AppCore& core, const cli::Parsed& parsed) { for (const QString& name : parsed.operands) { PackageInfo package; QString error; if (!resolvePackage(core, name, &package, &error)) { printErr(error); return 1; } printLine(QStringLiteral("Installation de %1 via %2...") .arg(name, providerName(package))); const Outcome outcome = runAction(core, name, [&core, &package] { return core.install(package); }); if (reportAction(outcome, QStringLiteral("%1 installé.").arg(name)) != 0) return 1; } return 0; } int runRemove(AppCore& core, const cli::Parsed& parsed) { for (const QString& name : parsed.operands) { PackageInfo package; QString error; if (!resolvePackage(core, name, &package, &error)) { printErr(error); return 1; } if (!confirm(QStringLiteral("Supprimer %1 (%2) ?").arg(name, providerName(package)), parsed.assumeYes)) { printLine(QStringLiteral("Suppression annulée.")); continue; } printLine(QStringLiteral("Suppression de %1...").arg(name)); const Outcome outcome = runAction(core, name, [&core, &package] { return core.remove(package); }); if (reportAction(outcome, QStringLiteral("%1 supprimé.").arg(name)) != 0) return 1; } return 0; } int runUpdate(AppCore& core, const cli::Parsed& parsed) { // With no operand, everything is updated — the one shape that can take // minutes, so it is confirmed first. if (parsed.operands.isEmpty()) { if (!confirm(QStringLiteral("Mettre à jour tous les paquets ?"), parsed.assumeYes)) { printLine(QStringLiteral("Mise à jour annulée.")); return 0; } printLine(QStringLiteral("Mise à jour de tous les paquets...")); const Outcome outcome = runAction(core, QStringLiteral("tous les paquets"), [&core] { return core.updateAll(); }); return reportAction(outcome, QStringLiteral("Tous les paquets sont à jour.")); } const QString name = parsed.operands.first(); PackageInfo package; QString error; if (!resolvePackage(core, name, &package, &error)) { printErr(error); return 1; } printLine(QStringLiteral("Mise à jour de %1 via %2...").arg(name, providerName(package))); const Outcome outcome = runAction(core, name, [&core, &package] { return core.update(package); }); return reportAction(outcome, QStringLiteral("Mise à jour terminée.")); } int runList(AppCore& core, AppCore::ListMode mode, bool withRepository) { QEventLoop loop; std::vector results; QObject::connect(&core, &AppCore::listFinished, &loop, [&](AppCore::ListMode finished, std::vector found) { if (finished != mode) return; results = std::move(found); loop.quit(); }); const AppCore::StartResult started = mode == AppCore::ListMode::Installed ? core.loadInstalled() : mode == AppCore::ListMode::Updates ? core.loadUpdates() : core.loadCleanup(); if (!started.started) { printErr(started.error); return 1; } loop.exec(); printPackages(results, withRepository); return 0; } int runInfo(AppCore& core, const cli::Parsed& parsed) { const QString name = parsed.operands.first(); PackageInfo package; QString error; if (!resolvePackage(core, name, &package, &error)) { printErr(error); return 1; } printLine(QStringLiteral("%1 — %2").arg(QString::fromStdString(package.name), QString::fromStdString(package.version))); printLine(QStringLiteral("Fournisseur : %1").arg(providerName(package))); if (!package.repository.empty()) { printLine(QStringLiteral("Dépôt : %1").arg(QString::fromStdString(package.repository))); } printLine(package.installed ? QStringLiteral("État : installé") : QStringLiteral("État : non installé")); if (!package.description.empty()) { printLine(QString::fromStdString(package.description)); } // The extra block comes from pacman (-Qi / -Si) and is empty for providers // that do not expose it; the summary above is then all there is to show. const QString details = core.packageDetails(package); if (!details.isEmpty()) { printLine(QString()); printLine(details); } return 0; } int runRefresh(AppCore& core) { printLine(QStringLiteral("Rafraîchissement des bases de données...")); const Outcome outcome = runAction(core, QStringLiteral("sources"), [&core] { return core.refresh(); }); return reportAction(outcome, QStringLiteral("Sources rafraîchies.")); } } // namespace namespace cli { int run(const QStringList& args) { const Parsed parsed = parse(args); switch (parsed.command) { case Command::None: // Nothing to do: the caller only routes here when a command exists. return 0; case Command::Help: printLine(helpText()); return 0; case Command::Version: printLine(QStringLiteral("PacManager %1") .arg(QCoreApplication::applicationVersion())); return 0; case Command::Unknown: printErr(parsed.error); printErr(QStringLiteral("Essayez « pacmanager --help ».")); return 2; default: break; } AppCore core; if (!core.hasAvailableProvider()) { printErr(QStringLiteral("Aucun gestionnaire de paquets disponible sur ce système.")); return 1; } switch (parsed.command) { case Command::Search: return runSearch(core, parsed); case Command::Install: return runInstall(core, parsed); case Command::Remove: return runRemove(core, parsed); case Command::Update: return runUpdate(core, parsed); case Command::List: return runList(core, AppCore::ListMode::Installed, /*withRepository=*/true); case Command::Updates: return runList(core, AppCore::ListMode::Updates, /*withRepository=*/false); case Command::Cleanup: return runList(core, AppCore::ListMode::Cleanup, /*withRepository=*/false); case Command::Info: return runInfo(core, parsed); case Command::Refresh: return runRefresh(core); default: break; } return 0; } } // namespace cli