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.
This commit is contained in:
11 files changed
+1055
-5
No files matched your search
@@ -0,0 +1,450 @@
|
||||
#include "cli-application.h"
|
||||
|
||||
#include "app-core.h"
|
||||
#include "cli-command.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QEventLoop>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
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<tcflag_t>(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<PackageInfo>& 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<int>(QStringLiteral("NOM").size());
|
||||
int versionWidth = static_cast<int>(QStringLiteral("VERSION").size());
|
||||
int providerWidth = static_cast<int>(QStringLiteral("FOURNISSEUR").size());
|
||||
int repoWidth = static_cast<int>(QStringLiteral("DÉPÔT").size());
|
||||
for (const PackageInfo& package : packages) {
|
||||
nameWidth = std::max(nameWidth, static_cast<int>(package.name.size()));
|
||||
versionWidth = std::max(versionWidth, static_cast<int>(package.version.size()));
|
||||
providerWidth = std::max(providerWidth, static_cast<int>(providerName(package).size()));
|
||||
repoWidth = std::max(repoWidth, static_cast<int>(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<PackageInfo>* results,
|
||||
QString* error) {
|
||||
QEventLoop loop;
|
||||
QObject::connect(&core, &AppCore::searchFinished, &loop,
|
||||
[&](std::vector<PackageInfo> 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<PackageInfo> 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<AppCore::StartResult()>& 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<PackageInfo> 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<PackageInfo> results;
|
||||
QObject::connect(&core, &AppCore::listFinished, &loop,
|
||||
[&](AppCore::ListMode finished, std::vector<PackageInfo> 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
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <QStringList>
|
||||
|
||||
// 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
|
||||
@@ -0,0 +1,212 @@
|
||||
#include "cli-command.h"
|
||||
|
||||
#include <QHash>
|
||||
|
||||
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<QString, cli::Command>& keywords() {
|
||||
static const QHash<QString, cli::Command> 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 <commande> [paquet...] [--yes]\n"
|
||||
"\n"
|
||||
"Commandes :\n"
|
||||
" recherche <terme> chercher des paquets\n"
|
||||
" install <paquet...> installer un ou plusieurs paquets\n"
|
||||
" supprimer <paquet...> 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 <paquet> 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
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
// Command-line front-end: what `pacmanager <commande>` 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
|
||||
Reference in new issue
Block a user