From 3e4ed92c0ac644ac3da8512a86b3af4360c87049 Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Sat, 3 Oct 2026 22:53:47 +0200 Subject: [PATCH] feat(cli): add a simplified command line over the logic layer The window needs a display, which kept the package manager out of a script and off a headless machine. The command line runs the same operations through AppCore, before any widget exists, so providers, the pacman lock, the journal and the history behave exactly as in the window. Refs #22. --- CMakeLists.txt | 15 +- README.md | 16 ++ app/main.cpp | 49 +++- cli/cli-application.cpp | 450 +++++++++++++++++++++++++++++++++++++ cli/cli-application.h | 14 ++ cli/cli-command.cpp | 212 +++++++++++++++++ cli/cli-command.h | 58 +++++ doc/README.md | 2 + doc/cli.md | 103 +++++++++ doc/tests.md | 1 + tests/cli-command.test.cpp | 140 ++++++++++++ 11 files changed, 1055 insertions(+), 5 deletions(-) create mode 100644 cli/cli-application.cpp create mode 100644 cli/cli-application.h create mode 100644 cli/cli-command.cpp create mode 100644 cli/cli-command.h create mode 100644 doc/cli.md create mode 100644 tests/cli-command.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e6f89c7..79c085e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,6 +30,9 @@ find_package(ZLIB REQUIRED) set(SOURCES app/main.cpp app/main-window.cpp + # Command-line front-end: parsing, then the runner over the logic layer. + cli/cli-command.cpp + cli/cli-application.cpp providers/pacman-manager.cpp plugins/plugin-manager.cpp history/history-manager.cpp @@ -60,6 +63,8 @@ set(SOURCES set(HEADERS include/sdk/package-manager.h + cli/cli-command.h + cli/cli-application.h providers/pacman-manager.h plugins/plugin-manager.h include/sdk/provider-plugin.h @@ -97,7 +102,7 @@ add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) set_target_properties(${PROJECT_NAME} PROPERTIES ENABLE_EXPORTS ON) target_include_directories(${PROJECT_NAME} PRIVATE - include pages pages/base pages/packages pages/overview pages/system pages/extensions include/sdk logging preferences history archive update plugins providers core app) + include pages pages/base pages/packages pages/overview pages/system pages/extensions include/sdk logging preferences history archive update plugins providers core app cli) target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Widgets Qt6::Network ZLIB::ZLIB) target_compile_definitions(${PROJECT_NAME} PRIVATE FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}" @@ -250,6 +255,14 @@ target_compile_definitions(language-manager-test PRIVATE PACMANAGER_TRANSLATIONS_DIR="${CMAKE_CURRENT_SOURCE_DIR}/translations") add_test(NAME language-manager-test COMMAND language-manager-test) +# The command-line grammar: which arguments ask for the command line rather than +# the window, and what each keyword parses into. Pure parsing — no package +# manager, no display, nothing spawned (the runner is exercised by hand). +add_executable(cli-command-test tests/cli-command.test.cpp cli/cli-command.cpp) +target_include_directories(cli-command-test PRIVATE include include/sdk logging preferences history archive update plugins providers core app cli) +target_link_libraries(cli-command-test PRIVATE Qt6::Core) +add_test(NAME cli-command-test COMMAND cli-command-test) + # ---- Translations ---- # # The language setting loads a catalogue named .json out of a diff --git a/README.md b/README.md index a4efd73..3e1417c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,22 @@ Gestionnaire de paquets pour **Arch Linux** basé sur **pacman**, avec interface - 📥 **Fichiers Flatpak** : glissez-déposez un `.flatpakref`, `.flatpakrepo` ou `.flatpak` sur la fenêtre (ou clic droit → **Ouvrir avec PacManager** dans le gestionnaire de fichiers) pour l'installer directement — avec les octets réellement téléchargés et le temps écoulé affichés en direct, flatpak n'imprimant rien pendant le téléchargement d'un runtime - 🔁 **Installations multiples** : une application installée en utilisateur *et* en système, ou depuis deux dépôts, reste **une seule ligne** ; la fiche de détail énumère les copies et **Supprimer** ouvre une case par installation pour choisir celles à retirer - ⚙️ **Paramètres** : quand demander le mot de passe administrateur, **où** et à quelle taille maximale écrire le journal, activer ou désactiver le glisser-déposer Flatpak, la langue de l'interface, et la politique de mise à jour de PacManager (vérification automatique, blocage 1 h / 24 h / 7 jours / jusqu'à annulation) +- ⌨️ **Ligne de commande** : `pacmanager recherche vlc` puis `pacmanager install vlc` — la même logique que la fenêtre, sans écran (voir [doc/cli.md](doc/cli.md)) + +## Ligne de commande + +La même logique que la fenêtre s'utilise sans ouvrir d'interface : + +```bash +pacmanager recherche vlc +pacmanager install vlc +pacmanager maj-dispo +``` + +Commandes : `recherche`, `install`, `supprimer`, `maj`, `liste`, `maj-dispo`, +`info`, `refresh`, `nettoyage`, `aide`, `version` (alias anglais acceptés). +`-y` / `--yes` saute les confirmations, `--help` affiche l'aide. Le détail est +dans [doc/cli.md](doc/cli.md). ## Architecture diff --git a/app/main.cpp b/app/main.cpp index 97f3694..21b27d6 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -1,15 +1,57 @@ #include +#include #include #include #include #include "app-settings.h" +#include "cli-application.h" +#include "cli-command.h" #include "language-manager.h" #include "log-manager.h" #include "main-window.h" #include "update-manager.h" +namespace { + +// The arguments as the command-line grammar wants them: program name excluded. +QStringList commandLineArguments(int argc, char* argv[]) { + QStringList arguments; + if (argc > 1) arguments.reserve(argc - 1); + for (int i = 1; i < argc; ++i) { + arguments << QString::fromLocal8Bit(argv[i]); + } + return arguments; +} + +} // namespace + int main(int argc, char* argv[]) { + const QStringList arguments = commandLineArguments(argc, argv); + + // The command line is decided before any widget exists: `pacmanager install + // vlc` has to work on a machine with no display, so it runs on a + // QCoreApplication and never builds the window. + if (cli::isCliInvocation(arguments)) { + QCoreApplication app(argc, argv); + app.setApplicationName("PacManager"); + app.setApplicationVersion(UpdateManager::currentVersion()); + app.setOrganizationName("Freebuff"); + + LogManager::installQtMessageHandler(); + LogManager::instance().logEvent( + QStringLiteral("app"), + QCoreApplication::translate("main", "session démarrée (v%1)") + .arg(UpdateManager::currentVersion())); + + const int code = cli::run(arguments); + + LogManager::instance().logEvent( + QStringLiteral("app"), + QCoreApplication::translate("main", "session terminée (code %1)").arg(code)); + return code; + } + QApplication app(argc, argv); app.setApplicationName("PacManager"); app.setApplicationVersion(UpdateManager::currentVersion()); @@ -44,10 +86,9 @@ int main(int argc, char* argv[]) { // Files the desktop handed over ("Ouvrir avec PacManager", the desktop // entry declares %U): installed once the event loop runs, so the window is // visible and any dialog has a parent. - const QStringList fileArgs = app.arguments().mid(1); - if (!fileArgs.isEmpty()) { - QTimer::singleShot(0, &window, [&window, fileArgs] { - window.installLocalFiles(fileArgs); + if (!arguments.isEmpty()) { + QTimer::singleShot(0, &window, [&window, arguments] { + window.installLocalFiles(arguments); }); } diff --git a/cli/cli-application.cpp b/cli/cli-application.cpp new file mode 100644 index 0000000..e993519 --- /dev/null +++ b/cli/cli-application.cpp @@ -0,0 +1,450 @@ +#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 diff --git a/cli/cli-application.h b/cli/cli-application.h new file mode 100644 index 0000000..a5ceb11 --- /dev/null +++ b/cli/cli-application.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +// Runs a parsed command line against the logic layer (AppCore) and prints the +// result. No widget is built: the command line works on a machine without a +// display, and the operations are exactly the ones the window runs. +namespace cli { + +// `args` is the command line, program name excluded. Returns the process exit +// code: 0 on success, 1 when an operation failed, 2 on a usage error. +int run(const QStringList& args); + +} // namespace cli diff --git a/cli/cli-command.cpp b/cli/cli-command.cpp new file mode 100644 index 0000000..7ae7fee --- /dev/null +++ b/cli/cli-command.cpp @@ -0,0 +1,212 @@ +#include "cli-command.h" + +#include + +namespace { + +// Every keyword a command answers to, French first. Kept in one table so the +// help text and the parser cannot drift apart. +const QHash& keywords() { + static const QHash table = { + {QStringLiteral("recherche"), cli::Command::Search}, + {QStringLiteral("search"), cli::Command::Search}, + {QStringLiteral("cherche"), cli::Command::Search}, + + {QStringLiteral("install"), cli::Command::Install}, + {QStringLiteral("installer"), cli::Command::Install}, + + {QStringLiteral("supprimer"), cli::Command::Remove}, + {QStringLiteral("remove"), cli::Command::Remove}, + {QStringLiteral("uninstall"), cli::Command::Remove}, + {QStringLiteral("désinstaller"), cli::Command::Remove}, + {QStringLiteral("desinstaller"), cli::Command::Remove}, + + {QStringLiteral("maj"), cli::Command::Update}, + {QStringLiteral("update"), cli::Command::Update}, + {QStringLiteral("upgrade"), cli::Command::Update}, + + {QStringLiteral("liste"), cli::Command::List}, + {QStringLiteral("list"), cli::Command::List}, + + {QStringLiteral("maj-dispo"), cli::Command::Updates}, + {QStringLiteral("updates"), cli::Command::Updates}, + + {QStringLiteral("info"), cli::Command::Info}, + {QStringLiteral("détails"), cli::Command::Info}, + {QStringLiteral("details"), cli::Command::Info}, + + {QStringLiteral("refresh"), cli::Command::Refresh}, + {QStringLiteral("rafraîchir"), cli::Command::Refresh}, + {QStringLiteral("rafraichir"), cli::Command::Refresh}, + {QStringLiteral("sync"), cli::Command::Refresh}, + + {QStringLiteral("nettoyage"), cli::Command::Cleanup}, + {QStringLiteral("cleanup"), cli::Command::Cleanup}, + + {QStringLiteral("aide"), cli::Command::Help}, + {QStringLiteral("help"), cli::Command::Help}, + + {QStringLiteral("version"), cli::Command::Version}, + }; + return table; +} + +bool isYesFlag(const QString& token) { + return token == QLatin1String("--yes") || token == QLatin1String("-y"); +} + +bool isHelpFlag(const QString& token) { + return token == QLatin1String("--help") || token == QLatin1String("-h") + || token == QLatin1String("-?"); +} + +bool isVersionFlag(const QString& token) { + return token == QLatin1String("--version") || token == QLatin1String("-V") + || token == QLatin1String("-v"); +} + +cli::Command commandFor(const QString& token) { + const auto it = keywords().constFind(token.toLower()); + return it == keywords().constEnd() ? cli::Command::Unknown : it.value(); +} + +cli::Parsed refuse(const QString& error) { + cli::Parsed parsed; + parsed.command = cli::Command::Unknown; + parsed.error = error; + return parsed; +} + +} // namespace + +namespace cli { + +bool isCliInvocation(const QStringList& args) { + if (args.isEmpty()) return false; + + const QString first = args.first(); + // Any leading option, or a known keyword, is aimed at the command line. + if (first.startsWith(QLatin1Char('-')) || commandFor(first) != Command::Unknown) { + return true; + } + + // A path, or a file with one of the extensions the window knows how to + // install, is what the desktop hands over ("Ouvrir avec PacManager", the + // desktop entry declares %U): the window is wanted for those. + const QString lower = first.toLower(); + const bool looksLikePath = first.contains(QLatin1Char('/')) + || first.startsWith(QLatin1Char('~')); + const bool looksLikeFile = lower.endsWith(QLatin1String(".flatpak")) + || lower.endsWith(QLatin1String(".flatpakref")) + || lower.endsWith(QLatin1String(".flatpakrepo")) + || lower.endsWith(QLatin1String(".fwspacm")); + if (looksLikePath || looksLikeFile) return false; + + // A bare word that is not a command is a mistyped command: the command line + // says so, which is friendlier than opening a window that can do nothing + // with it. + return true; +} + +Parsed parse(const QStringList& args) { + Parsed parsed; + if (args.isEmpty()) return parsed; // Command::None: the window + + // --help/--version win wherever they stand, like every command line. + for (const QString& token : args) { + if (isHelpFlag(token)) { + parsed.command = Command::Help; + return parsed; + } + if (isVersionFlag(token)) { + parsed.command = Command::Version; + return parsed; + } + } + + QStringList tokens; + for (const QString& token : args) { + // -y is a modifier, not an operand: it is read wherever it appears. + if (isYesFlag(token)) { + parsed.assumeYes = true; + continue; + } + tokens << token; + } + + const QString first = tokens.takeFirst(); + parsed.command = commandFor(first); + if (parsed.command == Command::Unknown) { + if (first.startsWith(QLatin1Char('-'))) { + return refuse(QStringLiteral("Option inconnue : %1").arg(first)); + } + return refuse(QStringLiteral("Commande inconnue : %1").arg(first)); + } + + parsed.operands = tokens; + + // What each command needs to be runnable, checked here so the runner never + // has to guess what a missing operand means. + const int count = tokens.size(); + switch (parsed.command) { + case Command::Search: + case Command::Install: + case Command::Remove: + if (count == 0) { + return refuse( + QStringLiteral("« %1 » attend au moins un nom de paquet.").arg(first)); + } + break; + case Command::Info: + if (count != 1) { + return refuse(QStringLiteral("« %1 » attend un nom de paquet.").arg(first)); + } + break; + case Command::Update: + if (count > 1) { + return refuse(QStringLiteral( + "« %1 » ne met à jour qu'un paquet à la fois (ou tous sans nom).") + .arg(first)); + } + break; + case Command::List: + case Command::Updates: + case Command::Refresh: + case Command::Cleanup: + case Command::Help: + case Command::Version: + if (count != 0) { + return refuse(QStringLiteral("« %1 » n'accepte pas d'argument.").arg(first)); + } + break; + case Command::None: + case Command::Unknown: + break; + } + + return parsed; +} + +QString helpText() { + return QStringLiteral( + "PacManager — gestionnaire de paquets en ligne de commande\n" + "\n" + "Usage : pacmanager [paquet...] [--yes]\n" + "\n" + "Commandes :\n" + " recherche chercher des paquets\n" + " install installer un ou plusieurs paquets\n" + " supprimer supprimer un ou plusieurs paquets\n" + " maj [paquet] mettre à jour un paquet, ou tout sans nom\n" + " liste lister les paquets installés\n" + " maj-dispo lister les mises à jour disponibles\n" + " info détails d'un paquet\n" + " refresh rafraîchir les bases de données\n" + " nettoyage lister les paquets inutilisés et legacy\n" + " aide | version cette aide, ou la version installée\n" + "\n" + "Alias anglais : search, remove, update, list, updates, details, cleanup, help.\n" + " -y, --yes ne pas demander confirmation (suppression, maj globale)"); +} + +} // namespace cli diff --git a/cli/cli-command.h b/cli/cli-command.h new file mode 100644 index 0000000..571a567 --- /dev/null +++ b/cli/cli-command.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include + +// Command-line front-end: what `pacmanager ` asks for, parsed apart +// from everything that runs it so the grammar can be unit-tested without a +// package manager, a display or a single process spawned. +// +// The wording is the one of the issue that asked for it: a simplified pacman, +// `pacmanager recherche vlc` then `pacmanager install vlc`. French is the +// language the rest of the interface is written in, so its keywords come first; +// the English ones are accepted as aliases because the second half of that same +// sentence is English. +namespace cli { + +enum class Command { + // No argument at all: the window is wanted. + None, + Search, + Install, + Remove, + // No operand updates everything; one operand updates that package. + Update, + List, + Updates, + Info, + Refresh, + Cleanup, + Help, + Version, + // Something was typed that is not a command: `error` says what. + Unknown, +}; + +struct Parsed { + Command command = Command::None; + // Package names, or the search term for Search. + QStringList operands; + // Skip the confirmation of a destructive command. + bool assumeYes = false; + // Why parsing refused, when command == Unknown. + QString error; +}; + +// True when the arguments ask for the command line rather than the window. +// The absence of a known keyword is what keeps +// "pacmanager /chemin/app.flatpak" opening the window, the way the desktop +// entry hands a file over. +bool isCliInvocation(const QStringList& args); + +// Parses the arguments, program name excluded. +Parsed parse(const QStringList& args); + +// The text `pacmanager --help` prints. +QString helpText(); + +} // namespace cli diff --git a/doc/README.md b/doc/README.md index 85e6717..c8e2890 100644 --- a/doc/README.md +++ b/doc/README.md @@ -16,6 +16,7 @@ déboguer ou brancher un plugin. | [installation.md](installation.md) | Dépendances, compilation, options CMake, installation dans le bureau, fichiers créés sur le système | | [architecture.md](architecture.md) | La coupure logique / interface, le flux d'un appel, où ajouter du code | | [interface.md](interface.md) | Les écrans, la navigation, les raccourcis clavier, le thème (tokens du site FWS) | +| [cli.md](cli.md) | La ligne de commande : commandes, résolution du fournisseur, mot de passe, codes de sortie | | [operations.md](operations.md) | Le déroulé d'une opération : sudo, verrou pacman, progression, providers multiples | | [plugins.md](plugins.md) | Fournisseurs et extensions : contrats, ABI C, emplacements, écriture d'un plugin | | [paquets-de-plugin.md](paquets-de-plugin.md) | Les paquets `.fwspacm` : format du manifeste, dépôt d'un fichier, sécurité, création | @@ -29,6 +30,7 @@ déboguer ou brancher un plugin. | --- | --- | | `core/app-core.h`, `core/app-core.cpp` | **La logique** : providers, workers, historique, plugins, sudo, verrou pacman, auto-update. Aucun widget. | | `app/main-window.h`, `app/main-window.cpp` | **Le cadre** : barre latérale, en-tête, barre de statut, menus, tray, dialogues, feuille de style. | +| `cli/cli-command.*`, `cli/cli-application.*` | **La ligne de commande** : la grammaire (testée) puis l'exécution sur `AppCore`, sans widget. | | `pages/` | **Les écrans**, un fichier par écran, plus `page.h` (contrat) et `ui-kit.*` (widgets partagés). | | `include/sdk/progress-tracker.h` | La progression d'une opération, lue dans la sortie des outils. | | `plugins/plugin-package.h`, `plugins/plugin-package.cpp` | L'installation d'un paquet de plugin `.fwspacm` (avec `zip-archive.*` pour lire l'archive). | diff --git a/doc/cli.md b/doc/cli.md new file mode 100644 index 0000000..fa0fb8b --- /dev/null +++ b/doc/cli.md @@ -0,0 +1,103 @@ +# Ligne de commande + +PacManager a une **ligne de commande simplifiée**, en plus de la fenêtre : le +même paquet se cherche et s'installe sans ouvrir d'interface, ce qui rend le +gestionnaire utilisable dans un script ou sur une machine sans écran. + +```bash +pacmanager recherche vlc +pacmanager install vlc +``` + +## Comment elle est branchée + +Le choix se fait dans `app/main.cpp`, **avant qu'aucun widget n'existe** : +`cli::isCliInvocation()` reconnaît une commande ou une option, et l'exécution +part alors sur un `QCoreApplication`. Une machine sans serveur graphique peut +donc lancer une opération ; aucune fenêtre n'est construite. + +C'est exactement la même logique que l'interface : la commande parle à +`AppCore` (`core/app-core.h`) et rien d'autre. Elle bénéficie donc des mêmes +providers (pacman, Flatpak, AUR…), du même verrou pacman, du même journal et du +même historique. + +| Fichier | Rôle | +| --- | --- | +| `cli/cli-command.h/.cpp` | **La grammaire** : quels arguments demandent la ligne de commande, et ce que chaque mot-clé donne. Pur, sans processus lancé — c'est ce que teste `cli-command-test`. | +| `cli/cli-application.h/.cpp` | **L'exécution** : lancer la commande sur `AppCore`, attendre la fin (signaux + boucle d'événements), afficher le résultat. | + +## Commandes + +Les mots-clés français viennent en premier (le reste de l'interface est écrit +dans cette langue) ; les alias anglais sont acceptés. + +| Commande | Alias | Effet | +| --- | --- | --- | +| `recherche ` | `search`, `cherche` | Cherche dans tous les fournisseurs et affiche une ligne par paquet. | +| `install ` | `installer` | Installe un ou plusieurs paquets. | +| `supprimer ` | `remove`, `uninstall`, `désinstaller` | Supprime (confirmation demandée). | +| `maj [paquet]` | `update`, `upgrade` | Met à jour un paquet ; **sans nom, tout** (confirmation demandée). | +| `liste` | `list` | Liste les paquets installés. | +| `maj-dispo` | `updates` | Liste les mises à jour disponibles. | +| `info ` | `détails`, `details` | Détails d'un paquet (`-Qi` / `-Si` quand le fournisseur les expose). | +| `refresh` | `rafraîchir`, `sync` | Rafraîchit les bases de données. | +| `nettoyage` | `cleanup` | Liste les paquets inutilisés (orphelins) et legacy. | +| `aide` | `help`, `-h`, `--help` | L'aide. | +| `version` | `-v`, `--version` | La version installée. | + +Options : + +- `-y`, `--yes` : ne pas demander confirmation (suppression, mise à jour + globale). Sans cette option, une commande destructive lancée depuis un tube + (pas de terminal) est **refusée** plutôt que laissée à attendre sur `stdin`. + +## Résolution du paquet et du fournisseur + +`install`, `supprimer`, `maj` et `info` prennent un **nom de paquet**, pas un +identifiant de fournisseur : le nom est cherché, puis comparé **exactement** +(insensible à la casse) à un résultat. Le fournisseur retenu est celui que la +recherche a associé au paquet, donc `install vlc` part vers pacman et une +application Flatpak vers Flatpak, sans que l'utilisateur ait à le dire. + +Un nom introuvable est une erreur (« Paquet introuvable : … »), avec le code de +sortie 1. + +## Mot de passe et sortie + +- Le mot de passe sudo est demandé **sur le terminal**, avec l'écho coupé comme + `sudo` ; il n'est jamais relu depuis un tube et n'est pas conservé après + l'opération. +- La sortie des commandes (ce que pacman imprime) est retransmise au fil de + l'eau, préfixée de deux espaces, exactement comme dans le journal. +- Les données (tableaux, résultats) vont sur **stdout** ; les messages du + journal Qt et les invites (`Mot de passe…`, confirmations) vont sur + **stderr** : `pacmanager recherche vlc 2>/dev/null` ne laisse que le tableau. + +## Codes de sortie + +| Code | Sens | +| --- | --- | +| `0` | Commande réussie. | +| `1` | Échec d'une opération, ou paquet introuvable. | +| `2` | Erreur d'usage (commande ou option inconnue, argument manquant). | + +## Ce qu'elle ne fait pas (volontairement) + +- Ce n'est **pas** pacman : pas de `-Syu`, pas d'options brutes, pas de + résolution de dépendances fine. C'est un raccourci pour les gestes courants. +- Pas de menus interactifs : chaque commande fait une chose et se termine. +- Le nettoyage **liste** les candidats ; la suppression groupée reste le fait de + l'interface (et de `supprimer`, paquet par paquet). + +## Tester + +```bash +./build/PacManager --help +./build/PacManager recherche vlc +./build/PacManager info vlc +``` + +Les commandes de lecture (`recherche`, `liste`, `maj-dispo`, `info`, +`nettoyage`) ne modifient rien et se testent sans risque ; `install` et +`supprimer` demandent le mot de passe et modifient le système. La grammaire +est couverte par `ctest -R cli-command`. diff --git a/doc/tests.md b/doc/tests.md index 32b47a4..1690bb1 100644 --- a/doc/tests.md +++ b/doc/tests.md @@ -26,6 +26,7 @@ lance qu'une partie (`ctest -R progress`). | `update-manager-test` | Comparaison de versions, choix de la méthode de mise à jour, et le script d'installation, exécuté pour de vrai contre un binaire en cours d'exécution. | Qt Core + Network. | | `language-manager-test` | La langue : ce que le réglage résout (un code connu, un code inconnu, « système » suivant `LC_ALL`/`LC_MESSAGES`/`LANG` puis `/etc/locale.conf`, le suffixe `@mod` ignoré, une locale non couverte qui retombe sur la langue d'écriture) ; le catalogue JSON en'core (installé, chaîne traduite, chaîne inconnue qui retombe sur la source, une clé seule servie à tous les contextes) ; un catalogue cassé ou sans chaîne **refusé**, l'interface restant entière ; et la couverture : le catalogue anglais doit contenir **toute** chaîne que le code demande, sinon une chaîne se lirait en français dans une interface anglaise. | Qt Core + les ressources, aucun affichage. | | `app-settings-test` | Les préférences : valeurs par défaut, valeurs refusées (dossier vide, langue inconnue, taille de journal aberrante), persistance après relecture, un réglage qui n'émet que s'il change, la politique de blocage des mises à jour (durée, expiration, indefini) et — pour de vrai — le **journal** : il atterrit dans le dossier choisi, accompagne un changement de dossier, tourne au plafond de taille et garde une version précédente. | Qt Core seulement. | +| `cli-command-test` | La **grammaire de la ligne de commande** : ce qui demande la CLI plutôt que la fenêtre (mot-clé ou option, contre un chemin ou un fichier `.flatpak`/`.fwspacm`) et ce que chaque mot-clé donne — recherche à plusieurs mots, install/suppression de plusieurs paquets, `maj` avec ou sans nom, commandes de lecture sans argument, `-y` lu partout, `--help`/`--version` prioritaires, commande ou option inconnue. | Qt Core seulement, rien n'est lancé. | ### Pourquoi `app-core-test` ne lie pas QtWidgets diff --git a/tests/cli-command.test.cpp b/tests/cli-command.test.cpp new file mode 100644 index 0000000..2a0696f --- /dev/null +++ b/tests/cli-command.test.cpp @@ -0,0 +1,140 @@ +// Unit tests for the command-line grammar (cli/cli-command.*): which arguments +// ask for the command line rather than the window, and what each keyword parses +// into. Pure parsing — no package manager, no display, nothing spawned. +#include +#include + +#include +#include +#include + +#include "cli-command.h" + +static QStringList args(std::initializer_list words) { + QStringList list; + for (const char* word : words) list << QString::fromUtf8(word); + return list; +} + +static void testInvocationRouting() { + // No arguments, or a file the desktop handed over: the window is wanted. + assert(!cli::isCliInvocation({})); + assert(!cli::isCliInvocation(args({"/home/user/app.flatpak"}))); + assert(!cli::isCliInvocation(args({"app.flatpakref"}))); + assert(!cli::isCliInvocation(args({"./bundle.fwspacm"}))); + + // A keyword, or any leading option, is aimed at the command line. + assert(cli::isCliInvocation(args({"recherche", "vlc"}))); + assert(cli::isCliInvocation(args({"install", "vlc"}))); + assert(cli::isCliInvocation(args({"search", "vlc"}))); + assert(cli::isCliInvocation(args({"--help"}))); + assert(cli::isCliInvocation(args({"-y", "install", "vlc"}))); + + // A bare word that is not a path is a mistyped command, not a file: the + // command line reports it instead of opening a window that cannot use it. + assert(cli::isCliInvocation(args({"frobnicate"}))); +} + +static void testSearchParsing() { + const cli::Parsed parsed = cli::parse(args({"recherche", "vlc"})); + assert(parsed.command == cli::Command::Search); + assert(parsed.operands == args({"vlc"})); + + // The search word may hold spaces: the term is everything that follows. + const cli::Parsed multi = cli::parse(args({"search", "gtk", "theme"})); + assert(multi.command == cli::Command::Search); + assert(multi.operands.join(QLatin1Char(' ')) == QLatin1String("gtk theme")); + + // The keyword is not a search term on its own. + const cli::Parsed missing = cli::parse(args({"recherche"})); + assert(missing.command == cli::Command::Unknown); + assert(!missing.error.isEmpty()); +} + +static void testInstallAndRemoveParsing() { + const cli::Parsed install = cli::parse(args({"install", "vlc"})); + assert(install.command == cli::Command::Install); + assert(install.operands == args({"vlc"})); + + const cli::Parsed several = cli::parse(args({"installer", "vlc", "vim"})); + assert(several.command == cli::Command::Install); + assert(several.operands == args({"vlc", "vim"})); + + const cli::Parsed remove = cli::parse(args({"supprimer", "-y", "vlc"})); + assert(remove.command == cli::Command::Remove); + assert(remove.assumeYes); + assert(remove.operands == args({"vlc"})); + + assert(cli::parse(args({"remove"})).command == cli::Command::Unknown); +} + +static void testUpdateParsing() { + // No operand means everything; one operand means that package. + const cli::Parsed all = cli::parse(args({"maj"})); + assert(all.command == cli::Command::Update); + assert(all.operands.isEmpty()); + + const cli::Parsed one = cli::parse(args({"update", "vlc"})); + assert(one.command == cli::Command::Update); + assert(one.operands == args({"vlc"})); + + assert(cli::parse(args({"maj", "vlc", "vim"})).command == cli::Command::Unknown); +} + +static void testReadOnlyCommands() { + assert(cli::parse(args({"liste"})).command == cli::Command::List); + assert(cli::parse(args({"list"})).command == cli::Command::List); + assert(cli::parse(args({"maj-dispo"})).command == cli::Command::Updates); + assert(cli::parse(args({"cleanup"})).command == cli::Command::Cleanup); + assert(cli::parse(args({"refresh"})).command == cli::Command::Refresh); + + const cli::Parsed info = cli::parse(args({"info", "vlc"})); + assert(info.command == cli::Command::Info); + assert(info.operands == args({"vlc"})); + assert(cli::parse(args({"info"})).command == cli::Command::Unknown); + + // A listing takes no operand. + assert(cli::parse(args({"liste", "vlc"})).command == cli::Command::Unknown); +} + +static void testHelpAndVersion() { + assert(cli::parse(args({"--help"})).command == cli::Command::Help); + assert(cli::parse(args({"aide"})).command == cli::Command::Help); + // An option wins wherever it stands. + assert(cli::parse(args({"install", "--help"})).command == cli::Command::Help); + + assert(cli::parse(args({"--version"})).command == cli::Command::Version); + assert(cli::parse(args({"-v"})).command == cli::Command::Version); + + // The help names the keywords the parser accepts. + assert(cli::helpText().contains(QLatin1String("recherche"))); + assert(cli::helpText().contains(QLatin1String("install"))); +} + +static void testUnknownCommands() { + const cli::Parsed word = cli::parse(args({"frobnicate"})); + assert(word.command == cli::Command::Unknown); + assert(word.error.contains(QLatin1String("frobnicate"))); + + const cli::Parsed option = cli::parse(args({"--nope"})); + assert(option.command == cli::Command::Unknown); + assert(option.error.contains(QLatin1String("--nope"))); + + // No argument at all is not an error: it is the window. + assert(cli::parse({}).command == cli::Command::None); +} + +int main(int argc, char* argv[]) { + QCoreApplication app(argc, argv); + + testInvocationRouting(); + testSearchParsing(); + testInstallAndRemoveParsing(); + testUpdateParsing(); + testReadOnlyCommands(); + testHelpAndVersion(); + testUnknownCommands(); + + std::cout << "All cli-command tests passed" << std::endl; + return 0; +}