diff --git a/apps/ll-builder/src/main.cpp b/apps/ll-builder/src/main.cpp index 58214529f..dbebff1f6 100644 --- a/apps/ll-builder/src/main.cpp +++ b/apps/ll-builder/src/main.cpp @@ -9,6 +9,7 @@ #include "linglong/builder/config.h" #include "linglong/builder/linglong_builder.h" #include "linglong/cli/cli.h" +#include "linglong/common/global/initialize.h" #include "linglong/package/architecture.h" #include "linglong/package/version.h" #include "linglong/repo/client_factory.h" @@ -16,7 +17,6 @@ #include "linglong/repo/migrate.h" #include "linglong/utils/error/error.h" #include "linglong/utils/gettext.h" -#include "linglong/utils/global/initialize.h" #include "linglong/utils/log/log.h" #include "linglong/utils/namespace.h" #include "linglong/utils/serialize/yaml.h" @@ -136,18 +136,18 @@ getProjectYAMLPath(const std::filesystem::path &projectDir, const std::string &u int handleCreate(const CreateCommandOptions &options) { - qInfo() << "Handling create for project:" << QString::fromStdString(options.projectName); + LogI("Handling create for project: {}", options.projectName); auto name = QString::fromStdString(options.projectName); QDir projectDir = QDir::current().absoluteFilePath(name); if (projectDir.exists()) { - qCritical() << name << "project dir already exists"; + LogE("{} project dir already exists", options.projectName); return -1; } auto ret = projectDir.mkpath("."); if (!ret) { - qCritical() << "create project dir failed:" << projectDir.absolutePath(); + LogE("create project dir failed: {}", projectDir.absolutePath().toStdString()); return -1; } @@ -156,23 +156,25 @@ int handleCreate(const CreateCommandOptions &options) if (!QFileInfo::exists(templateFilePath)) { templateFilePath = ":/example.yaml"; // Use Qt resource fallback - qInfo() << "Using template file from Qt resources:" << templateFilePath; + LogI("Using template file from Qt resources: {}", templateFilePath); } else { - qInfo() << "Using template file from system path:" << templateFilePath; + LogI("Using template file from system path: {}", templateFilePath); } QFile templateFile(templateFilePath); QFile configFile(configFilePath); if (!templateFile.open(QIODevice::ReadOnly)) { - qCritical() << "Failed to open template file:" << templateFilePath - << "Error:" << templateFile.errorString(); + LogE("Failed to open template file {}: {}", + templateFilePath, + templateFile.errorString().toStdString()); return -1; } if (!configFile.open(QIODevice::WriteOnly)) { - qCritical() << "Failed to open config file for writing:" << configFilePath - << "Error:" << configFile.errorString(); + LogE("Failed to open config file {} for writing: {}", + configFilePath.toStdString(), + configFile.errorString().toStdString()); return -1; } @@ -180,18 +182,21 @@ int handleCreate(const CreateCommandOptions &options) rawData.replace("@ID@", name.toUtf8()); if (configFile.write(rawData) <= 0) { - qCritical() << "Failed to write config file:" << configFilePath - << "Error:" << configFile.errorString(); + LogE("Failed to write config file {}: {}", + configFilePath.toStdString(), + configFile.errorString().toStdString()); return -1; } - qInfo() << "Project" << name << "created successfully at" << projectDir.absolutePath(); + LogI("Project {} created successfully at {}", + options.projectName, + projectDir.absolutePath().toStdString()); return 0; } int handleBuild(linglong::builder::Builder &builder, const BuildCommandOptions &options) { - qInfo() << "Handling build command"; + LogI("Handling build command"); auto cfg = builder.getConfig(); @@ -219,11 +224,11 @@ int handleBuild(linglong::builder::Builder &builder, const BuildCommandOptions & ret = builder.build(); } if (!ret) { - qCritical() << "Build failed: " << ret.error(); + LogE("Build failed: {}", ret.error()); return ret.error().code(); } - qInfo() << "Build completed successfully."; + LogI("Build completed successfully."); return 0; } @@ -260,14 +265,14 @@ int handleExport(linglong::builder::Builder &builder, const ExportCommandOptions auto exportOpts = options.exportSpecificOptions; // layer 默认使用lz4, 保持和之前版本的兼容 if (exportOpts.compressor.empty()) { - qInfo() << "Compressor not specified, defaulting to lz4 for layer export."; + LogI("Compressor not specified, defaulting to lz4 for layer export."); exportOpts.compressor = "lz4"; } if (options.layerMode) { auto result = builder.exportLayer(exportOpts); if (!result) { - qCritical() << "Export layer failed: " << result.error(); + LogE("Export layer failed: {}", result.error()); return result.error().code(); } @@ -276,7 +281,7 @@ int handleExport(linglong::builder::Builder &builder, const ExportCommandOptions auto result = builder.exportUAB(exportOpts, options.outputFile); if (!result) { - qCritical() << "Export UAB failed: " << result.error(); + LogE("Export UAB failed: {}", result.error()); return result.error().code(); } @@ -285,22 +290,21 @@ int handleExport(linglong::builder::Builder &builder, const ExportCommandOptions int handlePush(linglong::builder::Builder &builder, const PushCommandOptions &options) { - qInfo() << "Handling push command"; + LogI("Handling push command"); const auto &repoOpts = options.repoOptions; for (const auto &module : options.pushModules) { - qInfo() << "Pushing module:" << QString::fromStdString(module); + LogI("Pushing module: {}", module); auto result = builder.push(module, repoOpts.repoUrl, repoOpts.repoName); if (!result) { - qCritical() << "Push failed for module" << QString::fromStdString(module) << ":" - << result.error(); + LogE("Push failed for module {}: {}", module, result.error()); return result.error().code(); } - qInfo() << "Module" << QString::fromStdString(module) << "pushed successfully."; + LogI("Module {} pushed successfully.", module); } - qInfo() << "All modules pushed successfully."; + LogI("All modules pushed successfully."); return 0; } @@ -352,18 +356,20 @@ int handleImportDir(linglong::repo::OSTreeRepo &repo, const ImportDirCommandOpti int handleExtract(const ExtractCommandOptions &options) { + LogI("Handling extract command for layer file: {} to directory: {}", + options.layerFile, + options.dir); + QString layerFile = QString::fromStdString(options.layerFile); QString targetDir = QString::fromStdString(options.dir); - qInfo() << "Handling extract command for layer file:" << layerFile - << "to directory:" << targetDir; auto result = linglong::builder::Builder::extractLayer(layerFile, targetDir); if (!result) { - qCritical() << "Extract layer failed: " << result.error(); + LogE("Extract layer failed: {}", result.error()); return result.error().code(); } - qInfo() << "Layer extraction completed successfully."; + LogI("Layer extraction completed successfully."); return 0; } @@ -400,7 +406,7 @@ int handleRepoAdd(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOptions & return r.alias.value_or(r.name) == alias; }); if (isExist) { - std::cerr << "repo " + alias + " already exist." << std::endl; + LogE("repo {} already exist.", alias); return -1; } @@ -448,7 +454,7 @@ int handleRepoRemove(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOption return -1; } - qInfo() << "Repository" << QString::fromStdString(alias) << "removed successfully."; + LogI("Repository {} removed successfully.", alias); return 0; } @@ -480,7 +486,7 @@ int handleRepoUpdate(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOption return -1; } - qInfo() << "Repository" << QString::fromStdString(alias) << "updated successfully."; + LogI("Repository {} updated successfully.", alias); return 0; } @@ -506,9 +512,9 @@ int handleRepoSetDefault(linglong::repo::OSTreeRepo &repo, linglong::cli::RepoOp std::cerr << ret.error().message() << std::endl; return -1; } - qInfo() << "Default repository set to" << QString::fromStdString(alias) << "successfully."; + LogI("Default repository set to {} successfully.", alias); } else { - qInfo() << QString::fromStdString(alias) << "is already the default repository."; + LogI("{} is already the default repository.", alias); } return 0; @@ -639,34 +645,35 @@ std::vector getProjectModule(const linglong::api::types::v1::Builde std::optional backupFailedMigrationRepo(const std::filesystem::path &repoPath) { - qWarning() << "Repository migration failed. Attempting to back up the old repository:" - << QString::fromStdString(repoPath.string()); + LogW("Repository migration failed. Attempting to back up the old repository {}", + repoPath.string()); auto backupDirPattern = (repoPath.parent_path() / "linglong-builder.old-XXXXXX").string(); std::error_code ec; char *backupDir = ::mkdtemp(backupDirPattern.data()); if (backupDir == nullptr) { - qCritical() << "we couldn't generate a temporary directory for migrate, old repo will " - "be removed."; + LogE("we couldn't generate a temporary directory for migrate, old repo will be removed."); std::filesystem::remove_all(repoPath, ec); // Use remove_all for directories if (ec) { - qCritical() << "failed to remove the old repo:" << QString::fromStdString(repoPath); + LogE("failed to remove the old repo: {}", repoPath); } return std::nullopt; } std::filesystem::rename(repoPath, backupDir, ec); if (ec) { - qCritical() << "Failed to move the old repository to the backup location (" << backupDir - << "). Error:" << ec.message().c_str() << "Please move or remove it manually:" - << QString::fromStdString(repoPath.string()); + LogE("Failed to move the old repository to the backup location ({}): {}\nPlease move or " + "remove it manually: {}", + backupDir, + ec.message(), + repoPath.string()); // Attempt to clean up the created backup directory if rename failed return std::nullopt; } - qInfo() << "Old repository successfully backed up to:" << backupDir - << ". All data will need to be pulled again."; + LogI("Old repository successfully backed up to: {}. All data will need to be pulled again.", + backupDir); return backupDir; } @@ -680,8 +687,8 @@ int main(int argc, char **argv) // 初始化 qt qrc Q_INIT_RESOURCE(builder_releases); // 初始化应用,builder在非tty环境也输出日志 - linglong::utils::global::applicationInitialize(true); - linglong::utils::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Console); + linglong::common::global::applicationInitialize(); + linglong::common::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Console); CLI::App commandParser{ _("linyaps builder CLI \n" "A CLI program to build linyaps application\n") }; @@ -1008,7 +1015,7 @@ You can report bugs to the linyaps team under this project: https://github.com/O linglong::repo::loadConfig({ QString::fromStdString(builderCfg->repo + "/config.yaml"), LINGLONG_DATA_DIR "/config.yaml" }); if (!repoCfg) { - qCritical() << repoCfg.error(); + LogE("{}", repoCfg.error()); return -1; } @@ -1021,7 +1028,7 @@ You can report bugs to the linyaps team under this project: https://github.com/O auto repoRoot = QDir{ QString::fromStdString(builderCfg->repo) }; if (!repoRoot.exists() && !repoRoot.mkpath(".")) { - qCritical() << "failed to create the repository of builder."; + LogE("failed to create the repository of builder."); return -1; } @@ -1063,7 +1070,7 @@ You can report bugs to the linyaps team under this project: https://github.com/O auto path = QStandardPaths::findExecutable(ociRuntimeCLI); if (path.isEmpty()) { - qCritical() << ociRuntimeCLI << "not found"; + LogE("{} not found", ociRuntimeCLI.toStdString()); return -1; } diff --git a/apps/ll-cli/src/main.cpp b/apps/ll-cli/src/main.cpp index 516979f16..7601985ce 100644 --- a/apps/ll-cli/src/main.cpp +++ b/apps/ll-cli/src/main.cpp @@ -12,12 +12,12 @@ #include "linglong/cli/json_printer.h" #include "linglong/cli/terminal_notifier.h" #include "linglong/common/error.h" +#include "linglong/common/global/initialize.h" #include "linglong/repo/config.h" #include "linglong/repo/ostree_repo.h" #include "linglong/runtime/container_builder.h" #include "linglong/utils/finally/finally.h" #include "linglong/utils/gettext.h" -#include "linglong/utils/global/initialize.h" #include "linglong/utils/log/log.h" #include "ocppi/cli/crun/Crun.hpp" @@ -56,10 +56,10 @@ void startProcess(const QString &program, const QStringList &args = {}) qint64 pid = 0; process.startDetached(&pid); - qDebug() << "Start" << program << args << "as" << pid; + LogD("start {} {} as {}", program.toStdString(), args.join(" ").toStdString(), pid); QObject::connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, [pid]() { - qDebug() << "Kill" << pid; + LogD("kill {}", pid); kill(pid, SIGTERM); }); } @@ -79,7 +79,7 @@ std::vector transformOldExec(int argc, char **argv) noexcept if ((exec + 1) == res.rend() || (exec + 2) != res.rend()) { *exec = "--"; - qDebug() << "replace `--exec` with `--`"; + LogD("replace `--exec` with `--`"); return res; } @@ -89,8 +89,7 @@ std::vector transformOldExec(int argc, char **argv) noexcept }); if (auto ret = wordexp((exec + 1)->c_str(), &words, 0); ret != 0) { - qCritical() << "wordexp on" << (exec + 1)->c_str() << "failed with" << ret - << "transform old exec arguments failed."; + LogE("wordexp on {} failed with {} transform old exec arguments failed.", *(exec + 1), ret); return res; } @@ -128,7 +127,7 @@ int lockCheck() noexcept .l_pid = 0 }; if (::fcntl(fd, F_GETLK, &lock_info) == -1) { - qCritical() << "failed to get lock" << lock; + LogE("failed to get lock {}", lock); return -1; } @@ -610,8 +609,6 @@ void addInspectCommand(CLI::App &commandParser, } // namespace -using namespace linglong::utils::global; - // 初始化仓库 linglong::utils::error::Result initOSTreeRepo() { @@ -626,7 +623,7 @@ linglong::utils::error::Result initOSTreeRepo() // check repo root auto repoRoot = QDir(LINGLONG_ROOT); if (!repoRoot.exists()) { - return LINGLONG_ERR("repo root doesn't exist" + repoRoot.absolutePath()); + return LINGLONG_ERR("repo root doesn't exist" + repoRoot.absolutePath().toStdString()); } // create repo @@ -735,15 +732,15 @@ You can report bugs to the linyaps team under this project: https://github.com/O while (true) { auto lockOwner = lockCheck(); if (lockOwner == -1) { - qCritical() << "lock check failed"; + LogE("lock check failed"); return -1; } if (lockOwner > 0) { - qInfo() << "\r\33[K" - << "\033[?25l" - << "repository is being operated by another process, waiting for" << lockOwner - << "\033[?25h"; + std::cerr << "\r\33[K" + << "\033[?25l" + << "repository is being operated by another process, waiting for" << lockOwner + << "\033[?25h" << std::endl; using namespace std::chrono_literals; std::this_thread::sleep_for(1s); continue; @@ -762,11 +759,11 @@ You can report bugs to the linyaps team under this project: https://github.com/O // if --no-dbus flag is set, start package manager in sudo mode if (*noDBusFlag) { if (getuid() != 0) { - qCritical() << "--no-dbus should only be used by root user."; + LogE("--no-dbus should only be used by root user."); return -1; } - qInfo() << "some subcommands will failed in --no-dbus mode."; + LogW("some subcommands will failed in --no-dbus mode."); const auto pkgManAddress = QString("unix:path=/tmp/linglong-package-manager.socket"); startProcess("sudo", { "--user", @@ -779,7 +776,8 @@ You can report bugs to the linyaps team under this project: https://github.com/O pkgManConn = QDBusConnection::connectToPeer(pkgManAddress, "ll-package-manager"); if (!pkgManConn.isConnected()) { - qCritical() << "Failed to connect to ll-package-manager:" << pkgManConn.lastError(); + LogE("Failed to connect to ll-package-manager: {}", + pkgManConn.lastError().message().toStdString()); return -1; } @@ -795,8 +793,8 @@ You can report bugs to the linyaps team under this project: https://github.com/O auto reply = peer.Ping(); reply.waitForFinished(); if (!reply.isValid()) { - qCritical() << "Failed to activate org.deepin.linglong.PackageManager1" - << reply.error(); + LogE("Failed to activate org.deepin.linglong.PackageManager1: {}", + reply.error().message().toStdString()); return -1; } } @@ -818,7 +816,7 @@ You can report bugs to the linyaps team under this project: https://github.com/O // check oci runtime auto path = QStandardPaths::findExecutable(ociRuntimeCLI, { BINDIR }); if (path.isEmpty()) { - qCritical() << ociRuntimeCLI << "not found"; + LogE("{} not found", ociRuntimeCLI.toStdString()); return -1; } @@ -842,19 +840,18 @@ You can report bugs to the linyaps team under this project: https://github.com/O try { notifier = std::make_unique(); } catch (std::runtime_error &err) { - qInfo() << "initialize DBus notifier failed:" << err.what() - << "try to fallback to terminal notifier."; + LogW("initialize DBus notifier failed: {} try to fallback to terminal notifier.", + err.what()); } } if (!notifier) { - qInfo() << "Using DummyNotifier, expected interactions and prompts will not be " - "displayed."; + LogW("Using DummyNotifier, expected interactions and prompts will not be displayed."); notifier = std::make_unique(); } auto repo = initOSTreeRepo(); if (!repo.has_value()) { - qCritical() << "initOSTreeRepo failed" << repo.error(); + LogE("initOSTreeRepo failed: {}", repo.error()); return -1; } // create cli @@ -873,7 +870,7 @@ You can report bugs to the linyaps team under this project: https://github.com/O cli, &Cli::cancelCurrentTask) == nullptr) { - qCritical() << "failed to connect signal: aboutToQuit"; + LogE("failed to connect signal: aboutToQuit"); return -1; } @@ -939,8 +936,8 @@ int main(int argc, char **argv) QCoreApplication app(argc, argv); // application initialize - applicationInitialize(); - initLinyapsLogSystem(linglong::utils::log::LogBackend::Journal); + linglong::common::global::applicationInitialize(); + linglong::common::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Journal); // invoke method auto ret = QMetaObject::invokeMethod( diff --git a/apps/ll-driver-detect/CMakeLists.txt b/apps/ll-driver-detect/CMakeLists.txt index 7481a2f01..454ff7b6c 100644 --- a/apps/ll-driver-detect/CMakeLists.txt +++ b/apps/ll-driver-detect/CMakeLists.txt @@ -17,4 +17,5 @@ pfl_add_executable( LINK_LIBRARIES PRIVATE CLI11::CLI11 + linglong::linglong linglong::utils) diff --git a/apps/ll-driver-detect/src/dbus_notifier.cpp b/apps/ll-driver-detect/src/dbus_notifier.cpp index fada0cb7b..d4c65077d 100644 --- a/apps/ll-driver-detect/src/dbus_notifier.cpp +++ b/apps/ll-driver-detect/src/dbus_notifier.cpp @@ -33,7 +33,7 @@ utils::error::Result DBusNotifier::init() this, SLOT(forwardActionInvoked(quint32, QString)))) { return LINGLONG_ERR("couldn't connect to signal ActionInvoked:" - + connection.lastError().message()); + + connection.lastError().message().toStdString()); } if (!connection.connect(dbusInterface_.service(), @@ -43,7 +43,7 @@ utils::error::Result DBusNotifier::init() this, SLOT(forwardNotificationClosed(quint32, quint32)))) { return LINGLONG_ERR("couldn't connect to signal NotificationClosed:" - + connection.lastError().message()); + + connection.lastError().message().toStdString()); } return LINGLONG_OK; } @@ -172,7 +172,7 @@ utils::error::Result DBusNotifier::sendDBusNotification(const QString & .call("Notify", appName, replaceId, icon, summary, body, actions, hints, timeout); if (message.type() == QDBusMessage::ErrorMessage) { - return LINGLONG_ERR(QString("Failed to send notification: %1").arg(message.errorMessage())); + return LINGLONG_ERR("Failed to send notification: " + message.errorMessage().toStdString()); } if (message.arguments().isEmpty()) { diff --git a/apps/ll-driver-detect/src/driver_detection_manager.h b/apps/ll-driver-detect/src/driver_detection_manager.h index a0374f0fd..3761f4a1f 100644 --- a/apps/ll-driver-detect/src/driver_detection_manager.h +++ b/apps/ll-driver-detect/src/driver_detection_manager.h @@ -6,6 +6,7 @@ #include "driver_detector.h" +#include #include #include diff --git a/apps/ll-driver-detect/src/main.cpp b/apps/ll-driver-detect/src/main.cpp index 258ebf00a..5ea5d8527 100644 --- a/apps/ll-driver-detect/src/main.cpp +++ b/apps/ll-driver-detect/src/main.cpp @@ -8,10 +8,10 @@ #include "driver_detection_config.h" #include "driver_detection_manager.h" #include "driver_detector.h" +#include "linglong/common/global/initialize.h" #include "linglong/utils/cmd.h" #include "linglong/utils/error/error.h" #include "linglong/utils/gettext.h" -#include "linglong/utils/global/initialize.h" #include "tl/expected.hpp" #include @@ -130,8 +130,8 @@ int main(int argc, char *argv[]) bindtextdomain(PACKAGE_LOCALE_DOMAIN, PACKAGE_LOCALE_DIR); textdomain(PACKAGE_LOCALE_DOMAIN); - linglong::utils::global::applicationInitialize(); - linglong::utils::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Console); + linglong::common::global::applicationInitialize(); + linglong::common::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Console); DriverDetectOptions options; CLI::App cliApp{ "Linglong Graphics Driver Detection Tool" }; diff --git a/apps/ll-driver-detect/src/nvidia_driver_detector.cpp b/apps/ll-driver-detect/src/nvidia_driver_detector.cpp index 3eb5f72e0..b5c663ccd 100644 --- a/apps/ll-driver-detect/src/nvidia_driver_detector.cpp +++ b/apps/ll-driver-detect/src/nvidia_driver_detector.cpp @@ -8,6 +8,7 @@ #include "linglong/utils/error/error.h" #include "linglong/utils/log/log.h" +#include #include #include diff --git a/apps/ll-package-manager/src/main.cpp b/apps/ll-package-manager/src/main.cpp index e478e2db6..8c763cf50 100644 --- a/apps/ll-package-manager/src/main.cpp +++ b/apps/ll-package-manager/src/main.cpp @@ -7,11 +7,11 @@ #include "configure.h" #include "linglong/adaptors/package_manager/package_manager1.h" #include "linglong/common/dbus/register.h" +#include "linglong/common/global/initialize.h" #include "linglong/package_manager/package_manager.h" #include "linglong/repo/config.h" #include "linglong/repo/migrate.h" #include "linglong/repo/ostree_repo.h" -#include "linglong/utils/global/initialize.h" #include "ocppi/cli/CLI.hpp" #include "ocppi/cli/crun/Crun.hpp" @@ -19,36 +19,33 @@ #include -using namespace linglong::common::dbus; -using namespace linglong::utils::global; - namespace { void withDBusDaemon(ocppi::cli::CLI &cli) { auto config = linglong::repo::loadConfig( { LINGLONG_ROOT "/config.yaml", LINGLONG_DATA_DIR "/config.yaml" }); if (!config.has_value()) { - qCritical() << config.error(); + LogE("load config failed: {}", config.error()); QCoreApplication::exit(-1); return; } auto repoRoot = QDir(LINGLONG_ROOT); if (!repoRoot.exists() && !repoRoot.mkpath(".")) { - qCritical() << "failed to create repository directory" << repoRoot.absolutePath(); + LogE("failed to create repository directory {}", repoRoot.absolutePath().toStdString()); std::abort(); } auto ret = linglong::repo::tryMigrate(LINGLONG_ROOT, *config); if (ret == linglong::repo::MigrateResult::Failed) { - qCritical() << "failed to migrate repository"; + LogE("failed to migrate repository"); QCoreApplication::exit(-1); } auto *ostreeRepo = new linglong::repo::OSTreeRepo(repoRoot, *config); ostreeRepo->setParent(QCoreApplication::instance()); auto result = ostreeRepo->fixExportAllEntries(); if (!result.has_value()) { - qCritical() << result.error().message(); + LogE("fix export all entries failed: {}", result.error()); } auto *containerBuilder = new linglong::runtime::ContainerBuilder(cli); @@ -59,47 +56,51 @@ void withDBusDaemon(ocppi::cli::CLI &cli) *containerBuilder, QCoreApplication::instance()); new linglong::adaptors::package_manger::PackageManager1(packageManager); - result = registerDBusObject(conn, "/org/deepin/linglong/PackageManager1", packageManager); + result = linglong::common::dbus::registerDBusObject(conn, + "/org/deepin/linglong/PackageManager1", + packageManager); if (!result.has_value()) { - qCritical().noquote() << "Launching failed:" << Qt::endl << result.error().message(); + LogE("register dbus object failed: {}", result.error()); QCoreApplication::exit(-1); return; } QObject::connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, [conn] { - unregisterDBusObject(conn, "/org/deepin/linglong/PackageManager1"); + linglong::common::dbus::unregisterDBusObject(conn, "/org/deepin/linglong/PackageManager1"); }); - result = registerDBusService(conn, "org.deepin.linglong.PackageManager1"); + result = + linglong::common::dbus::registerDBusService(conn, "org.deepin.linglong.PackageManager1"); if (!result.has_value()) { - qCritical().noquote() << "Launching failed:" << Qt::endl << result.error().message(); + LogE("register dbus service failed: {}", result.error()); QCoreApplication::exit(-1); return; } QObject::connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, [conn] { - auto result = unregisterDBusService(conn, - // FIXME: use cmake option - "org.deepin.linglong.PackageManager1"); + auto result = + linglong::common::dbus::unregisterDBusService(conn, + // FIXME: use cmake option + "org.deepin.linglong.PackageManager1"); if (!result.has_value()) { - qWarning().noquote() << "During exiting:" << Qt::endl << result.error().message(); + LogW("unregister dbus service failed: {}", result.error()); } }); } void withoutDBusDaemon(ocppi::cli::CLI &cli) { - qInfo() << "Running linglong package manager without dbus daemon..."; + LogI("Running linglong package manager without dbus daemon..."); auto config = linglong::repo::loadConfig( { LINGLONG_ROOT "/config.yaml", LINGLONG_DATA_DIR "/config.yaml" }); if (!config.has_value()) { - qCritical() << config.error(); + LogE("load config failed: {}", config.error()); QCoreApplication::exit(-1); return; } auto repoRoot = QDir(LINGLONG_ROOT); if (!repoRoot.exists() && !repoRoot.mkpath(".")) { - qCritical() << "failed to create repository directory" << repoRoot.absolutePath(); + LogE("failed to create repository directory {}", repoRoot.absolutePath().toStdString()); std::abort(); } @@ -107,7 +108,7 @@ void withoutDBusDaemon(ocppi::cli::CLI &cli) ostreeRepo->setParent(QCoreApplication::instance()); auto result = ostreeRepo->fixExportAllEntries(); if (!result.has_value()) { - qCritical() << result.error().message(); + LogE("fix export all entries failed: {}", result.error()); } auto *containerBuilder = new linglong::runtime::ContainerBuilder(cli); @@ -121,7 +122,7 @@ void withoutDBusDaemon(ocppi::cli::CLI &cli) auto server = new QDBusServer("unix:path=/tmp/linglong-package-manager.socket", QCoreApplication::instance()); if (!server->isConnected()) { - qCritical() << "listen on socket:" << server->lastError(); + LogE("listen on socket: {}", server->lastError().message().toStdString()); QCoreApplication::exit(-1); return; } @@ -129,17 +130,21 @@ void withoutDBusDaemon(ocppi::cli::CLI &cli) if (QDir::root().remove("/tmp/linglong-package-manager.socket")) { return; } - qCritical() << "failed to remove /tmp/linglong-package-manager.socket."; + LogE("failed to remove /tmp/linglong-package-manager.socket."); }); QObject::connect(server, &QDBusServer::newConnection, [packageManager](QDBusConnection conn) { - auto res = registerDBusObject(conn, "/org/deepin/linglong/PackageManager1", packageManager); + auto res = + linglong::common::dbus::registerDBusObject(conn, + "/org/deepin/linglong/PackageManager1", + packageManager); if (!res.has_value()) { - qCritical() << res.error().code() << res.error().message(); + LogE("register dbus object failed: {}", res.error()); return; } QObject::connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, [conn]() { - unregisterDBusObject(conn, "/org/deepin/linglong/PackageManager1"); + linglong::common::dbus::unregisterDBusObject(conn, + "/org/deepin/linglong/PackageManager1"); }); }); } @@ -150,8 +155,8 @@ auto main(int argc, char *argv[]) -> int { QCoreApplication app(argc, argv); - applicationInitialize(); - initLinyapsLogSystem(linglong::utils::log::LogBackend::Journal); + linglong::common::global::applicationInitialize(); + linglong::common::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Journal); auto ociRuntimeCLI = qgetenv("LINGLONG_OCI_RUNTIME"); if (ociRuntimeCLI.isEmpty()) { @@ -160,7 +165,7 @@ auto main(int argc, char *argv[]) -> int auto path = QStandardPaths::findExecutable(ociRuntimeCLI); if (path.isEmpty()) { - qCritical() << ociRuntimeCLI << "not found"; + LogE("{} not found", ociRuntimeCLI.toStdString()); return -1; } diff --git a/libs/linglong/CMakeLists.txt b/libs/linglong/CMakeLists.txt index 416bf8dc7..4d9ce95cb 100644 --- a/libs/linglong/CMakeLists.txt +++ b/libs/linglong/CMakeLists.txt @@ -42,6 +42,8 @@ pfl_add_library( src/linglong/common/formatter.cpp src/linglong/common/formatter.h src/linglong/common/gkeyfile_wrapper.h + src/linglong/common/global/initialize.cpp + src/linglong/common/global/initialize.h src/linglong/common/serialize/json.cpp src/linglong/common/serialize/json.h src/linglong/extension/extension.cpp @@ -119,6 +121,7 @@ pfl_add_library( linglong::dbus-api linglong::utils linglong::api + PkgConfig::glib2 PkgConfig::ostree1 PkgConfig::systemd PkgConfig::ELF diff --git a/libs/linglong/src/linglong/builder/linglong_builder.cpp b/libs/linglong/src/linglong/builder/linglong_builder.cpp index 3c832d76e..32f6b690f 100644 --- a/libs/linglong/src/linglong/builder/linglong_builder.cpp +++ b/libs/linglong/src/linglong/builder/linglong_builder.cpp @@ -10,6 +10,7 @@ #include "linglong/api/types/v1/ExportDirs.hpp" #include "linglong/api/types/v1/Generators.hpp" #include "linglong/builder/printer.h" +#include "linglong/common/global/initialize.h" #include "linglong/oci-cfg-generators/container_cfg_builder.h" #include "linglong/package/architecture.h" #include "linglong/package/fuzzy_reference.h" @@ -24,7 +25,6 @@ #include "linglong/utils/error/error.h" #include "linglong/utils/file.h" #include "linglong/utils/finally/finally.h" -#include "linglong/utils/global/initialize.h" #include "linglong/utils/log/log.h" #include "linglong/utils/serialize/json.h" #include "linglong/utils/serialize/packageinfo_handler.h" @@ -33,7 +33,6 @@ #include #include -#include #include #include @@ -135,8 +134,8 @@ utils::error::Result pullDependency(const package::Reference &ref, printReplacedText( fmt::format("{:<35}{:<15}{:<15}waiting ...", ref.id, ref.version.toString(), module), 2); - QObject::connect(utils::global::GlobalTaskControl::instance(), - &utils::global::GlobalTaskControl::OnCancel, + QObject::connect(common::global::GlobalTaskControl::instance(), + &common::global::GlobalTaskControl::OnCancel, [&tmpTask]() { tmpTask.Cancel(); }); @@ -458,21 +457,19 @@ Builder::ensureUtils(const std::string &id, const package::Architecture &arch) n // the target and the current architectures. auto baseRef = clearDependency(info.base, false, true); if (!baseRef) { - return LINGLONG_ERR("base not exist: " + QString::fromStdString(info.base)); + return LINGLONG_ERR("base not exist: " + info.base); } if (!pullDependency(*baseRef, this->repo, "binary")) { - return LINGLONG_ERR("failed to pull base binary " + QString::fromStdString(info.base)); + return LINGLONG_ERR("failed to pull base binary " + info.base); } if (info.runtime) { auto runtimeRef = clearDependency(info.runtime.value(), false, true); if (!runtimeRef) { - return LINGLONG_ERR("runtime not exist: " - + QString::fromStdString(info.runtime.value())); + return LINGLONG_ERR("runtime not exist: " + info.runtime.value()); } if (!pullDependency(*runtimeRef, this->repo, "binary")) { - return LINGLONG_ERR("failed to pull runtime binary " - + QString::fromStdString(info.runtime.value())); + return LINGLONG_ERR("failed to pull runtime binary " + info.runtime.value()); } } @@ -487,7 +484,7 @@ utils::error::Result Builder::clearDependency(const std::str auto fuzzyRef = package::FuzzyReference::parse(ref); if (!fuzzyRef) { - return LINGLONG_ERR(QString::fromStdString("invalid ref ") + ref.c_str()); + return LINGLONG_ERR("invalid ref " + ref); } auto res = repo.clearReference(*fuzzyRef, @@ -663,7 +660,7 @@ utils::error::Result Builder::processBuildDepends() noexcept if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -763,9 +760,11 @@ utils::error::Result Builder::buildStageBuild(const QStringList &args) noe } // initialize the cache dir - QDir appCache(QString::fromStdString(internalDir / "cache")); - if (!appCache.mkpath(".")) { - return LINGLONG_ERR("make path " + appCache.absolutePath() + ": failed."); + auto appCache = internalDir / "cache"; + std::error_code ec; + std::filesystem::create_directories(appCache, ec); + if (ec) { + return LINGLONG_ERR(fmt::format("failed to create cache directory {}", appCache), ec); } linglong::generator::ContainerCfgBuilder cfgBuilder; @@ -798,17 +797,12 @@ utils::error::Result Builder::buildStageBuild(const QStringList &args) noe } // write ld.so.conf - QString ldConfPath = appCache.absoluteFilePath("ld.so.conf"); + auto ldConfPath = appCache / "ld.so.conf"; std::string triplet = package::Architecture::currentCPUArchitecture().getTriplet(); - std::string ldRawConf = cfgBuilder.ldConf(triplet); - - QFile ldsoconf{ ldConfPath }; - if (!ldsoconf.open(QIODevice::WriteOnly)) { - return LINGLONG_ERR(ldsoconf); + auto ret = utils::writeFile(ldConfPath, cfgBuilder.ldConf(triplet)); + if (!ret) { + return LINGLONG_ERR(ret); } - ldsoconf.write(ldRawConf.c_str()); - // must be closed here, this conf will be used later. - ldsoconf.close(); cfgBuilder.addExtraMounts(std::vector{ ocppi::runtime::config::types::Mount{ .destination = LINGLONG_BUILDER_HELPER, @@ -822,12 +816,12 @@ utils::error::Result Builder::buildStageBuild(const QStringList &args) noe ocppi::runtime::config::types::Mount{ .destination = "/etc/ld.so.conf.d/zz_deepin-linglong-app.conf", .options = { { "rbind", "ro" } }, - .source = ldConfPath.toStdString(), + .source = ldConfPath, .type = "bind" } }); if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -935,7 +929,7 @@ utils::error::Result Builder::buildStagePreCommit() noexcept if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -978,7 +972,7 @@ utils::error::Result Builder::generateAppConf() noexcept // generate application's configure file auto scriptFile = QString(LINGLONG_LIBEXEC_DIR) + "/app-conf-generator"; - auto useInstalledFile = utils::global::linglongInstalled() && QFile(scriptFile).exists(); + auto useInstalledFile = common::global::linglongInstalled() && QFile(scriptFile).exists(); QScopedPointer dir; if (!useInstalledFile) { LogD("Dumping app-conf-generator from qrc..."); @@ -1117,21 +1111,23 @@ utils::error::Result Builder::generateEntries() noexcept const std::filesystem::path exportDirConfigPath = LINGLONG_DATA_DIR "/export-dirs.json"; if (!std::filesystem::exists(exportDirConfigPath)) { return LINGLONG_ERR( - QString{ "this export config file doesn't exist: %1" }.arg(exportDirConfigPath.c_str())); + fmt::format("this export config file doesn't exist: {}", exportDirConfigPath)); } auto exportDirConfig = linglong::utils::serialize::LoadJSONFile( exportDirConfigPath); if (!exportDirConfig) { return LINGLONG_ERR( - QString{ "failed to load export config file: %1" }.arg(exportDirConfigPath.c_str())); + fmt::format("failed to load export config file {}", exportDirConfigPath), + exportDirConfig); } QDir binaryFiles(QString::fromStdString(internalDir / "output" / "binary" / "files")); QDir binaryEntries(QString::fromStdString(internalDir / "output" / "binary" / "entries")); if (!binaryEntries.mkpath(".")) { - return LINGLONG_ERR("make path " + binaryEntries.absolutePath() + ": failed."); + return LINGLONG_ERR("make path " + binaryEntries.absolutePath().toStdString() + + ": failed."); } if (binaryFiles.exists("share")) { @@ -1491,15 +1487,11 @@ utils::error::Result Builder::exportUAB(const ExportOption &option, std::error_code ec; const auto relativeBundleFile = std::filesystem::relative(bundleFile, workingDir, ec); if (ec) { - return LINGLONG_ERR( - fmt::format("failed to get relative path {}: {}", bundleFile, ec.message()) - .c_str()); + return LINGLONG_ERR(fmt::format("failed to get relative path {}", bundleFile), ec); } const auto relativeBundleDir = std::filesystem::relative(bundleDir, workingDir, ec); if (ec) { - return LINGLONG_ERR( - fmt::format("failed to get relative path {}: {}", bundleDir, ec.message()) - .c_str()); + return LINGLONG_ERR(fmt::format("failed to get relative path {}", bundleDir), ec); } if (common::strings::starts_with(relativeBundleFile.string(), "../") || common::strings::starts_with(relativeBundleDir.string(), "../")) { @@ -1708,7 +1700,7 @@ utils::error::Result Builder::extractLayer(const QString &layerPath, QDir destDir = destination; if (destDir.exists()) { - return LINGLONG_ERR(destination + " already exists"); + return LINGLONG_ERR(destination.toStdString() + " already exists"); } package::LayerPackager pkg; @@ -1861,7 +1853,7 @@ utils::error::Result Builder::run(std::vector modules, }); auto appCache = internalDir / "cache"; - std::string ldConfPath = appCache / "ld.so.conf"; + auto ldConfPath = appCache / "ld.so.conf"; applicationMounts.push_back(ocppi::runtime::config::types::Mount{ .destination = "/etc/ld.so.conf.d/zz_deepin-linglong-app.conf", .options = { { "rbind", "ro" } }, @@ -1891,19 +1883,14 @@ utils::error::Result Builder::run(std::vector modules, // write ld.so.conf std::string triplet = package::Architecture::currentCPUArchitecture().getTriplet(); - std::string ldRawConf = cfgBuilder.ldConf(triplet); - - QFile ldsoconf{ ldConfPath.c_str() }; - if (!ldsoconf.open(QIODevice::WriteOnly)) { - return LINGLONG_ERR(ldsoconf); + res = utils::writeFile(ldConfPath, cfgBuilder.ldConf(triplet)); + if (!res) { + return LINGLONG_ERR(res); } - ldsoconf.write(ldRawConf.c_str()); - // must be closed here, this conf will be used later. - ldsoconf.close(); if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -1955,7 +1942,7 @@ utils::error::Result Builder::run(std::vector modules, if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -2028,19 +2015,14 @@ utils::error::Result Builder::runFromRepo(const package::Reference &ref, // write ld.so.conf std::string triplet = package::Architecture::currentCPUArchitecture().getTriplet(); - std::string ldRawConf = cfgBuilder.ldConf(triplet); - - QFile ldsoconf{ ldConfPath.c_str() }; - if (!ldsoconf.open(QIODevice::WriteOnly)) { - return LINGLONG_ERR(ldsoconf); + res = utils::writeFile(ldConfPath, cfgBuilder.ldConf(triplet)); + if (!res) { + return LINGLONG_ERR(res); } - ldsoconf.write(ldRawConf.c_str()); - // must be closed here, this conf will be used later. - ldsoconf.close(); if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -2080,7 +2062,7 @@ utils::error::Result Builder::runFromRepo(const package::Reference &ref, if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -2134,15 +2116,7 @@ utils::error::Result Builder::generateEntryScript() noexcept LINGLONG_TRACE("generate entry script"); auto &project = *this->project; - QFile entry{ QString::fromStdString(internalDir / "entry.sh") }; - if (entry.exists() && !entry.remove()) { - return LINGLONG_ERR(entry); - } - - if (!entry.open(QIODevice::WriteOnly)) { - return LINGLONG_ERR(entry); - } - + auto entry = internalDir / "entry.sh"; std::string scriptContent = R"(#!/bin/bash set -e @@ -2162,23 +2136,17 @@ set -e scriptContent.append(LINGLONG_BUILDER_HELPER "/symbols-strip.sh\n"); } - auto writeBytes = scriptContent.size(); - auto bytesWrite = entry.write(scriptContent.c_str()); - - if (bytesWrite == -1 || (qint64)writeBytes != bytesWrite) { - return LINGLONG_ERR("Failed to write script content to file", entry); - } - - entry.close(); - if (entry.error() != QFile::NoError) { - return LINGLONG_ERR(entry); + auto res = utils::writeFile(entry, scriptContent); + if (!res) { + return LINGLONG_ERR(res); } LogD("build script: {}", scriptContent); - if (!entry.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner - | QFileDevice::ExeOwner)) { - return LINGLONG_ERR("set file permission error:", entry); + std::error_code ec; + std::filesystem::permissions(entry, std::filesystem::perms::owner_all, ec); + if (ec) { + return LINGLONG_ERR("set file permission error", ec); } LogD("generated entry.sh success"); diff --git a/libs/linglong/src/linglong/builder/source_fetcher.cpp b/libs/linglong/src/linglong/builder/source_fetcher.cpp index 23b7f8921..a898626e7 100644 --- a/libs/linglong/src/linglong/builder/source_fetcher.cpp +++ b/libs/linglong/src/linglong/builder/source_fetcher.cpp @@ -8,8 +8,8 @@ #include "configure.h" #include "linglong/common/formatter.h" +#include "linglong/common/global/initialize.h" #include "linglong/utils/error/error.h" -#include "linglong/utils/global/initialize.h" #include "linglong/utils/log/log.h" #include @@ -22,7 +22,8 @@ auto SourceFetcher::fetch(QDir destination) noexcept -> utils::error::Resultsource.kind != "git" && this->source.kind != "dsc" && this->source.kind != "file" @@ -45,14 +46,14 @@ auto SourceFetcher::fetch(QDir destination) noexcept -> utils::error::Result dir; if (!useInstalledFile) { dir.reset(new QTemporaryDir); // 便于在执行失败时进行调试 dir->setAutoRemove(false); scriptFile = dir->filePath(scriptName); - LogD("Dumping {} from qrc to {}", scriptName, scriptFile); + LogD("Dumping {} from qrc to {}", scriptName.toStdString(), scriptFile.toStdString()); QFile::copy(":/scripts/" + scriptName, scriptFile); } if (source.kind == "git") { @@ -85,7 +86,7 @@ QString SourceFetcher::getSourceName() QUrl url(source.url->c_str()); return url.fileName(); } - qCritical() << "missing name and url field"; + LogE("missing name and url field"); Q_ASSERT(false); return "unknown"; } @@ -98,7 +99,7 @@ SourceFetcher::SourceFetcher(api::types::v1::BuilderProjectSource source, const return; } - qCritical() << "mkpath" << this->cacheDir << "failed"; + LogE("mkpath {} failed", this->cacheDir.absolutePath().toStdString()); Q_ASSERT(false); } diff --git a/libs/linglong/src/linglong/cli/cli.cpp b/libs/linglong/src/linglong/cli/cli.cpp index 466fcb472..3576c00d6 100644 --- a/libs/linglong/src/linglong/cli/cli.cpp +++ b/libs/linglong/src/linglong/cli/cli.cpp @@ -45,6 +45,7 @@ #include "ocppi/runtime/Signal.hpp" #include "ocppi/types/ContainerListItem.hpp" +#include #include #include @@ -218,7 +219,7 @@ bool delegateToContainerInit(const std::string &containerID, int result{ -1 }; ret = ::recv(containerSocket, &result, sizeof(result), 0); - qDebug() << "delegate result:" << result; + LogD("delegate result: {}", result); return result == 0; } @@ -243,7 +244,7 @@ void Cli::onTaskPropertiesChanged( bool ok{ false }; auto val = value.toInt(&ok); if (!ok) { - qCritical() << "dbus ipc error, State couldn't convert to int"; + LogE("dbus ipc error, State couldn't convert to int"); continue; } @@ -255,7 +256,7 @@ void Cli::onTaskPropertiesChanged( bool ok{ false }; auto val = value.toDouble(&ok); if (!ok) { - qCritical() << "dbus ipc error, Percentage couldn't convert to int"; + LogE("dbus ipc error, Percentage couldn't convert to int"); continue; } @@ -265,7 +266,7 @@ void Cli::onTaskPropertiesChanged( if (key == "Message") { if (!value.canConvert()) { - qCritical() << "dbus ipc error, Message couldn't convert to QString"; + LogE("dbus ipc error, Message couldn't convert to QString"); continue; } @@ -277,7 +278,7 @@ void Cli::onTaskPropertiesChanged( bool ok{ false }; auto val = value.toInt(&ok); if (!ok) { - qCritical() << "dbus ipc error, Code couldn't convert to int"; + LogE("dbus ipc error, Code couldn't convert to int"); continue; } @@ -328,7 +329,7 @@ void Cli::interaction(const QDBusObjectPath &object_path, std::string action; auto notifyReply = notifier->request(req); if (!notifyReply) { - qCritical() << "internal error: notify failed"; + LogE("internal error: notify failed"); action = "no"; } else { action = notifyReply->action.value(); @@ -343,7 +344,7 @@ void Cli::interaction(const QDBusObjectPath &object_path, action = "no"; } - qDebug() << "action: " << QString::fromStdString(action); + LogD("action: {}", action); auto reply = api::types::v1::InteractionReply{ .action = action }; @@ -352,18 +353,18 @@ void Cli::interaction(const QDBusObjectPath &object_path, dbusReply.waitForFinished(); if (dbusReply.isError()) { this->printer.printErr( - LINGLONG_ERRV(dbusReply.error().message(), dbusReply.error().type())); + LINGLONG_ERRV(dbusReply.error().message().toStdString(), dbusReply.error().type())); } } void Cli::onTaskAdded(const QDBusObjectPath &object_path) { - LogD("task added: {}", object_path.path()); + LogD("task added: {}", object_path.path().toStdString()); } void Cli::onTaskRemoved(const QDBusObjectPath &object_path) { - LogD("task removed: {}", object_path.path()); + LogD("task removed: {}", object_path.path().toStdString()); if (object_path.path() != taskObjectPath) { return; } @@ -492,8 +493,7 @@ int Cli::run(const RunOptions &options) QObject::connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, [pidFile] { std::error_code ec; if (!std::filesystem::remove(pidFile, ec) && ec) { - qCritical().nospace() << "failed to remove file " << pidFile.c_str() << ": " - << ec.message().c_str(); + LogE("failed to remove file {}: {}", pidFile.c_str(), ec.message()); } }); @@ -557,11 +557,6 @@ int Cli::run(const RunOptions &options) } const auto &info = appLayerItem->info; - auto ret = RequestDirectories(info); - if (!ret) { - qWarning() << ret.error().message(); - } - auto commands = options.commands; if (options.commands.empty()) { commands = info.command.value_or(std::vector{ "bash" }); @@ -575,19 +570,18 @@ int Cli::run(const RunOptions &options) std::error_code ec; if (!std::filesystem::exists(pidFile, ec)) { if (ec) { - qCritical() << "couldn't get status of" << pidFile.c_str() << ":" - << ec.message().c_str(); + LogE("couldn't get status of {}: {}", pidFile.c_str(), ec.message()); return false; } - auto msg = "state file " + pidFile.string() + "doesn't exist, abort."; - qFatal("%s", msg.c_str()); + LogE("state file {} doesn't exist", pidFile.string()); + return false; } std::ofstream stream{ pidFile }; if (!stream.is_open()) { - auto msg = QString{ "failed to open %1" }.arg(pidFile.c_str()); - this->printer.printErr(LINGLONG_ERRV(msg)); + this->printer.printErr( + LINGLONG_ERRV(fmt::format("failed to open {}", pidFile.c_str()))); return false; } stream << nlohmann::json(runContext.stateInfo()); @@ -598,7 +592,7 @@ int Cli::run(const RunOptions &options) auto containers = getCurrentContainers().value_or(std::vector{}); for (const auto &container : containers) { - qDebug() << "found running container: " << container.package.c_str(); + LogD("found running container: {}", container.package); if (container.package != curAppRef->toString()) { continue; } @@ -617,7 +611,7 @@ int Cli::run(const RunOptions &options) auto *homeEnv = ::getenv("HOME"); if (homeEnv == nullptr) { - qCritical() << "Couldn't get HOME env."; + LogE("Couldn't get HOME env."); return -1; } @@ -707,7 +701,7 @@ int Cli::run(const RunOptions &options) if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - qCritical() << "build cfg error: " << QString::fromStdString(err.reason); + LogE("build cfg error: {}", err.reason); return -1; } @@ -749,7 +743,7 @@ int Cli::enter(const EnterOptions &options) } auto containerID = containerIDList.front(); - qInfo() << "select container id" << QString::fromStdString(containerID); + LogI("select container id: {}", containerID); auto commands = options.commands; if (commands.empty()) { commands = utils::BashCommandHelper::generateDefaultBashCommand(); @@ -791,8 +785,7 @@ Cli::getCurrentContainers() const noexcept return myContainers; } - return LINGLONG_ERR( - QString{ "failed to list %1: %2" }.arg(infoDir.c_str(), ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to list {}", infoDir), ec); } for (const auto &pidFile : it) { @@ -802,7 +795,7 @@ Cli::getCurrentContainers() const noexcept std::error_code ec; if (!std::filesystem::exists(process, ec)) { // this process may exit abnormally, skip it. - qDebug() << process.c_str() << "doesn't exist"; + LogD("{} doesn't exist", process.string()); continue; } @@ -813,7 +806,7 @@ Cli::getCurrentContainers() const noexcept auto info = linglong::utils::serialize::LoadJSONFile< linglong::api::types::v1::ContainerProcessStateInfo>(file); if (!info) { - qDebug() << "load info from" << file.c_str() << "error:" << info.error().message(); + LogD("load info from {}: {}", file.string(), info.error()); continue; } @@ -823,8 +816,7 @@ Cli::getCurrentContainers() const noexcept return item.id == info->containerID; }); if (container == containers.cend()) { - qDebug() << "couldn't find container that process " << file.filename().c_str() - << "belongs to"; + LogD("couldn't find container that process {} belongs to", file.filename().string()); continue; } @@ -872,7 +864,7 @@ std::vector Cli::getRunningAppContainers(const std::string &appid) for (const auto &container : *containers) { auto fuzzyRef = package::FuzzyReference::parse(container.package); if (!fuzzyRef) { - qWarning() << LINGLONG_ERRV(fuzzyRef).message(); + LogW("{}", fuzzyRef.error()); continue; } @@ -892,7 +884,7 @@ int Cli::kill(const KillOptions &options) auto ret = 0; for (const auto &containerID : containerIDList) { - qInfo() << "select container id" << QString::fromStdString(containerID); + LogI("select container id {}", containerID); auto result = this->ociCLI.kill(ocppi::runtime::ContainerID(containerID), ocppi::runtime::Signal(options.signal)); if (!result) { @@ -940,8 +932,9 @@ int Cli::installFromFile(const QFileInfo &fileInfo, return -1; } - this->printer.printErr(LINGLONG_ERRV(authReply.error().message() + authReply.error().name(), - static_cast(authReply.error().type()))); + this->printer.printErr(LINGLONG_ERRV( + fmt::format("{} {}", authReply.error().message() + authReply.error().name()), + static_cast(authReply.error().type()))); return -1; } @@ -951,10 +944,10 @@ int Cli::installFromFile(const QFileInfo &fileInfo, return -1; } - LogI("install from file {}", filePath); + LogI("install from file {}", filePath.toStdString()); QFile file{ filePath }; if (!file.open(QIODevice::ReadOnly | QIODevice::ExistingOnly)) { - auto err = LINGLONG_ERR(file); + auto err = LINGLONG_ERR(file.errorString().toStdString()); this->printer.printErr(err.value()); return -1; } @@ -1165,8 +1158,7 @@ int Cli::search(const SearchOptions &options) auto resultCode = static_cast(result->code); if (resultCode != utils::error::ErrorCode::Success) { if (resultCode == utils::error::ErrorCode::Failed) { - this->printer.printErr( - LINGLONG_ERRV("\n" + QString::fromStdString(result->message), result->code)); + this->printer.printErr(LINGLONG_ERRV("\n" + result->message, result->code)); loop.exit(result->code); return; } @@ -1178,8 +1170,7 @@ int Cli::search(const SearchOptions &options) } if (this->globalOptions.verbose) { - this->printer.printErr( - LINGLONG_ERRV("\n" + QString::fromStdString(result->message), result->code)); + this->printer.printErr(LINGLONG_ERRV("\n" + result->message, result->code)); } loop.exit(result->code); @@ -1394,15 +1385,14 @@ int Cli::repo(CLI::App *app, const RepoOptions &options) auto propCfg = this->pkgMan.configuration(); if (this->pkgMan.lastError().isValid()) { - auto err = LINGLONG_ERRV(this->pkgMan.lastError().message()); + auto err = LINGLONG_ERRV(this->pkgMan.lastError().message().toStdString()); this->printer.printErr(err); return -1; } auto cfg = common::serialize::fromQVariantMap(propCfg); if (!cfg) { - qCritical() << cfg.error(); - qCritical() << "linglong bug detected."; + LogE("fatal error: {}", cfg.error()); std::abort(); } @@ -1426,7 +1416,7 @@ int Cli::repo(CLI::App *app, const RepoOptions &options) if (argsParsed("add") || argsParsed("update")) { if (url.rfind("http", 0) != 0) { - this->printer.printErr(LINGLONG_ERRV(QString{ "url is invalid: " } + url.c_str())); + this->printer.printErr(LINGLONG_ERRV(fmt::format("url is invalid: {}", url))); return EINVAL; } @@ -1452,8 +1442,7 @@ int Cli::repo(CLI::App *app, const RepoOptions &options) return repo.alias.value_or(repo.name) == alias; }); if (isExist) { - this->printer.printErr( - LINGLONG_ERRV(QString{ "repo " } + alias.c_str() + " already exist.")); + this->printer.printErr(LINGLONG_ERRV(fmt::format("repo {} already exist", alias))); return -1; } cfgRef.repos.push_back(api::types::v1::Repo{ @@ -1472,15 +1461,16 @@ int Cli::repo(CLI::App *app, const RepoOptions &options) if (existingRepo == cfgRef.repos.end()) { this->printer.printErr( - LINGLONG_ERRV(QString{ "the operated repo " } + name.c_str() + " doesn't exist")); + LINGLONG_ERRV(fmt::format("the operated repo {} doesn't exist", name))); return -1; } if (argsParsed("remove")) { if (cfgRef.repos.size() == 1) { - this->printer.printErr(LINGLONG_ERRV(QString{ "repo " } + alias.c_str() - + " is the only repo, please add another repo " - "before removing it or update it directly.")); + this->printer.printErr( + LINGLONG_ERRV(fmt::format("repo {} is the only repo, please add another repo before " + "removing it or update it directly.", + alias))); return -1; } cfgRef.repos.erase(existingRepo); @@ -1557,7 +1547,7 @@ int Cli::setRepoConfig(const QVariantMap &config) this->pkgMan.setConfiguration(config); if (this->pkgMan.lastError().isValid()) { - auto err = LINGLONG_ERRV(this->pkgMan.lastError().message()); + auto err = LINGLONG_ERRV(this->pkgMan.lastError().message().toStdString()); this->printer.printErr(err); return -1; } @@ -1591,7 +1581,7 @@ int Cli::info(const InfoOptions &options) this->repository.clearReference(*fuzzyRef, { .forceRemote = false, .fallbackToRemote = false }); if (!ref) { - qDebug() << ref.error(); + LogD("{}", ref.error()); this->printer.printErr(LINGLONG_ERRV("Can not find such application.")); return -1; } @@ -1645,7 +1635,7 @@ int Cli::content(const ContentOptions &options) auto ref = this->repository.clearReference(*fuzzyRef, { .forceRemote = false, .fallbackToRemote = false }); if (!ref) { - qDebug() << ref.error(); + LogD("{}", ref.error()); this->printer.printErr(LINGLONG_ERRV("Can not find such application.")); return -1; } @@ -1716,7 +1706,7 @@ int Cli::content(const ContentOptions &options) } if (ec) { - qCritical() << "failed to check symlink " << file.c_str() << ":" << ec.message().c_str(); + LogE("failed to check symlink {}: {}", file.c_str(), ec.message()); } // Dont't mapping the file under /home @@ -1765,7 +1755,7 @@ std::vector Cli::filePathMapping(const std::vector &co if (arg == "%f" && options.filePaths.size() > 1) { // refer: // https://specifications.freedesktop.org/desktop-entry-spec/latest/exec-variables.html - qWarning() << "more than one file path specified, all file paths will be passed."; + LogW("more than one file path specified, all file paths will be passed."); } for (const auto &file : options.filePaths) { @@ -1781,7 +1771,7 @@ std::vector Cli::filePathMapping(const std::vector &co if (arg == "%u" || arg == "%U") { if (arg == "%u" && options.fileUrls.size() > 1) { - qWarning() << "more than one url specified, all file paths will be passed."; + LogW("more than one url specified, all file paths will be passed."); } for (const auto &url : options.fileUrls) { @@ -1795,7 +1785,7 @@ std::vector Cli::filePathMapping(const std::vector &co continue; } - qWarning() << "unkown command argument" << QString::fromStdString(arg); + LogW("unkown command argument {}", arg); } return execArgs; @@ -1863,13 +1853,13 @@ void Cli::filterPackageInfosByVersion( auto oldVersion = package::Version::parse(it->second.version); if (!oldVersion) { - qWarning() << "failed to parse old version:" << oldVersion.error().message(); + LogW("failed to parse old version: {}", oldVersion.error()); continue; } auto newVersion = package::Version::parse(pkgInfo.version); if (!newVersion) { - qWarning() << "failed to parse new version:" << newVersion.error().message(); + LogW("failed to parse new version: {}", newVersion.error()); continue; } @@ -1913,8 +1903,9 @@ utils::error::Result Cli::ensureAuthorized() return LINGLONG_ERR(message); } - return LINGLONG_ERR(authReply.error().message() + authReply.error().name(), - static_cast(authReply.error().type())); + return LINGLONG_ERR( + fmt::format("{} {}", authReply.error().message(), authReply.error().name()), + static_cast(authReply.error().type())); } return LINGLONG_OK; @@ -1932,12 +1923,12 @@ utils::error::Result Cli::runningAsRoot(const QList &args) const char *pkexecBin = "pkexec"; QStringList argv{ pkexecBin }; argv.append(args); - qDebug() << "run with pkexec:" << argv; std::vector targetArgv; for (const auto &arg : argv) { QByteArray byteArray = arg.toUtf8(); targetArgv.push_back(strdup(byteArray.constData())); } + LogD("run {}", fmt::join(targetArgv, " ")); targetArgv.push_back(nullptr); auto ret = execvp(pkexecBin, const_cast(targetArgv.data())); @@ -1955,197 +1946,6 @@ QDBusReply Cli::authorization() return this->pkgMan.Permissions(); } -utils::error::Result -Cli::RequestDirectories(const api::types::v1::PackageInfoV2 &info) noexcept -{ - LINGLONG_TRACE("request directories"); - - // TODO: skip request directories for now - return LINGLONG_OK; - - auto userHome = qgetenv("HOME").toStdString(); - if (userHome.empty()) { - return LINGLONG_ERR("HOME is not set, skip request directories"); - } - - QDir dialogPath = QDir{ LINGLONG_LIBEXEC_DIR }.filePath("dialog"); - if (auto runtimeDir = qgetenv("LINGLONG_PERMISSION_DIALOG_DIR"); !runtimeDir.isEmpty()) { - dialogPath.setPath(runtimeDir); - } - - auto appDataDir = utils::xdg::appDataDir(info.id); - if (!appDataDir) { - return LINGLONG_ERR(appDataDir); - } - - // make sure app data dir exists - auto dir = QDir{ appDataDir->c_str() }; - if (!dir.mkpath(".")) { - return LINGLONG_ERR(QString("make app data directory failed %1").arg(appDataDir->c_str())); - } - - auto permissions = QDir{ appDataDir->c_str() }.absoluteFilePath("permissions.json"); - if (QFileInfo::exists(permissions)) { - return LINGLONG_OK; - } - - auto fd = ::shm_open(info.id.c_str(), O_RDWR | O_CREAT, 0600); - if (fd < 0) { - return LINGLONG_ERR("shm_open error:" + common::error::errorString(errno)); - } - auto closeFd = utils::finally::finally([fd] { - ::close(fd); - }); - - struct flock lock{ - .l_type = F_WRLCK, - .l_whence = SEEK_SET, - .l_start = 0, - .l_len = 0, - }; - - // all later processes should be blocked - bool anotherRunning{ false }; - while (true) { - using namespace std::chrono_literals; - auto ret = ::fcntl(fd, F_SETLK, &lock); - if (ret == -1) { - if (errno == EACCES || errno == EAGAIN || errno == EINTR) { - anotherRunning = true; - std::this_thread::sleep_for(1s); - continue; - } - - return LINGLONG_ERR("fcntl lock error: " + common::error::errorString(errno)); - } - - if (!anotherRunning) { - break; - } - - lock.l_type = F_UNLCK; - ret = ::fcntl(fd, F_SETLK, &lock); - if (ret == -1) { - return LINGLONG_ERR("fcntl unlock error: " + common::error::errorString(errno)); - } - - return LINGLONG_OK; - } - - // unlink by creator - auto releaseResource = utils::finally::finally([&info, &lock, fd] { - lock.l_type = F_UNLCK; - if (::fcntl(fd, F_SETLK, &lock) == -1) { - LogD("failed to unlock mem file: {}", common::error::errorString(errno)); - } - - if (::shm_unlink(info.id.c_str()) == -1) { - LogD("shm_unlink error: {}", common::error::errorString(errno)); - } - }); - - std::vector requiredDirs = { - { .allowed = true, .dirType = "Desktop" }, { .allowed = true, .dirType = "Documents" }, - { .allowed = true, .dirType = "Downloads" }, { .allowed = true, .dirType = "Music" }, - { .allowed = true, .dirType = "Pictures" }, { .allowed = true, .dirType = "Videos" } - }; - if (info.permissions && info.permissions->xdgDirectories) { - requiredDirs = info.permissions->xdgDirectories.value(); - } - - if (requiredDirs.empty()) { - qDebug() << "no required directories."; - return LINGLONG_OK; - } - - auto availableDialogs = - dialogPath.entryInfoList(QDir::Executable | QDir::Files | QDir::NoSymLinks, QDir::Name); - if (availableDialogs.empty()) { - return LINGLONG_ERR("no available dialog"); - } - - auto dialogBin = availableDialogs.first().absoluteFilePath(); - QProcess dialogProc; - dialogProc.setProgram(dialogBin); - dialogProc.start(); - if (!dialogProc.waitForReadyRead(1000)) { - dialogProc.kill(); - return LINGLONG_ERR("wait for reading from dialog " + dialogBin - + "failed:" + dialogProc.errorString()); - } - - auto rawData = dialogProc.read(4); - auto *len = reinterpret_cast(rawData.data()); - rawData = dialogProc.read(*len); - auto version = utils::serialize::LoadJSON(rawData.data()); - if (!version) { - dialogProc.kill(); - return LINGLONG_ERR("error reply from dialog:" + version.error().message()); - } - - if (version->type != "Handshake") { - dialogProc.kill(); - return LINGLONG_ERR("dialog message type is not Handshake"); - } - - auto handshake = - utils::serialize::LoadJSON(version->payload); - if (!handshake) { - dialogProc.kill(); - return LINGLONG_ERR(" handshake message error:" + handshake.error().message()); - } - - if (handshake->version != "1.0") { - dialogProc.kill(); - return LINGLONG_ERR( - QString{ "incompatible version of dialog message protocol : required 1.0, actual " } - + handshake->version.c_str()); - } - - auto request = api::types::v1::ApplicationPermissionsRequest{ .appID = info.id, - .xdgDirectories = requiredDirs }; - api::types::v1::DialogMessage msg{ .payload = nlohmann::json(request).dump(), - .type = "Request" }; - auto data = nlohmann::json(msg).dump(); - uint32_t size = data.size(); - rawData = QByteArray{ reinterpret_cast(&size), 4 }; - rawData.append(data.c_str()); - - dialogProc.write(rawData); - dialogProc.closeWriteChannel(); - if (!dialogProc.waitForFinished(16 * 1000)) { - qWarning() << dialogProc.readAllStandardError(); - dialogProc.kill(); - return LINGLONG_ERR("dialog timeout"); - } - - bool allowRequired{ true }; - if (dialogProc.exitCode() != 0) { - qDebug() << "dialog exited with code" << dialogProc.exitCode() << ":" - << dialogProc.readAllStandardError(); - allowRequired = false; - } - - std::for_each(requiredDirs.begin(), - requiredDirs.end(), - [allowRequired](api::types::v1::XdgDirectoryPermission &dir) { - dir.allowed = allowRequired; - }); - api::types::v1::ApplicationConfigurationPermissions privs{ .xdgDirectories = requiredDirs }; - auto content = QByteArray::fromStdString(nlohmann::json(privs).dump()); - - QFile permissionFile{ permissions }; - if (!permissionFile.open(QIODevice::WriteOnly | QIODevice::NewOnly | QIODevice::Text)) { - return LINGLONG_ERR(permissionFile); - } - - if (permissionFile.write(content) != content.size()) { - qWarning() << "incomplete write to" << permissions << ":" << permissionFile.errorString(); - } - - return LINGLONG_OK; -} - utils::error::Result Cli::generateLDCache(runtime::RunContext &runContext, const std::string &ldConf) noexcept { @@ -2210,7 +2010,7 @@ utils::error::Result Cli::generateLDCache(runtime::RunContext &runContext, if (!cfgBuilder.build()) { auto err = cfgBuilder.getError(); - return LINGLONG_ERR("build cfg error: " + QString::fromStdString(err.reason)); + return LINGLONG_ERR("build cfg error: " + err.reason); } auto container = this->containerBuilder.create(cfgBuilder); @@ -2272,11 +2072,11 @@ utils::error::Result Cli::ensureCache( std::stringstream oldCache; std::ifstream ifs(ldSoConf, std::ios::binary | std::ios::in); if (!ifs.is_open()) { - return LINGLONG_ERR("failed to open " + QString::fromStdString(ldSoConf.string())); + return LINGLONG_ERR("failed to open " + ldSoConf.string()); } oldCache << ifs.rdbuf(); - qDebug() << "ld.so.conf:" << QString::fromStdString(ldConf); - qDebug() << "old ld.so.conf:" << QString::fromStdString(oldCache.str()); + LogD("ld.so.conf: {}", ldConf); + LogD("old ld.so.conf: {}", oldCache.str()); if (oldCache.str() != ldConf) { break; } @@ -2302,7 +2102,7 @@ void Cli::updateAM() noexcept && this->taskState.state == linglong::api::types::v1::State::Succeed) { QDBusConnection conn = QDBusConnection::systemBus(); if (!conn.isConnected()) { - qWarning() << "Failed to connect to the system bus"; + LogW("Failed to connect to the system bus"); } auto peer = linglong::api::dbus::v1::DBusPeer("org.desktopspec.ApplicationUpdateNotifier1", @@ -2311,8 +2111,8 @@ void Cli::updateAM() noexcept auto reply = peer.Ping(); reply.waitForFinished(); if (!reply.isValid()) { - qWarning() << "Failed to ping org.desktopspec.ApplicationUpdateNotifier1" - << reply.error(); + LogW("Failed to ping org.desktopspec.ApplicationUpdateNotifier1: {}", + reply.error().message().toStdString()); } } } @@ -2331,9 +2131,8 @@ int Cli::inspect(CLI::App *app, const InspectOptions &options) } else if (options.dirType == "bundle") { return this->getBundleDir(options); } else { - this->printer.printErr( - LINGLONG_ERRV(QString("Invalid type: %1, type must be layer or bundle") - .arg(QString::fromStdString(options.dirType)))); + this->printer.printErr(LINGLONG_ERRV( + fmt::format("Invalid type: {}, type must be layer or bundle", options.dirType))); return -1; } } @@ -2356,7 +2155,7 @@ int Cli::getLayerDir(const InspectOptions &options) auto ref = this->repository.clearReference(*fuzzyRef, { .forceRemote = false, .fallbackToRemote = false }); if (!ref) { - qDebug() << ref.error(); + LogD("{}", ref.error()); this->printer.printErr(LINGLONG_ERRV("Can not find such application.")); return -1; } @@ -2441,7 +2240,7 @@ utils::error::Result Cli::waitTaskCreated(QDBusPendingReply & this->taskState.state = linglong::api::types::v1::State::Queued; this->taskState.taskType = taskType; - LogD("task object path: {}", this->taskObjectPath); + LogD("task object path: {}", this->taskObjectPath.toStdString()); if (!conn.connect(pkgMan.service(), taskObjectPath, @@ -2451,7 +2250,7 @@ utils::error::Result Cli::waitTaskCreated(QDBusPendingReply & SLOT(onTaskPropertiesChanged(QString, QVariantMap, QStringList)))) { Q_ASSERT(false); return LINGLONG_ERR(fmt::format("Failed to connect signal PropertiesChanged: {}", - conn.lastError().message())); + conn.lastError().message().toStdString())); } return LINGLONG_OK; diff --git a/libs/linglong/src/linglong/cli/cli.h b/libs/linglong/src/linglong/cli/cli.h index 5df01d403..5e391ca01 100644 --- a/libs/linglong/src/linglong/cli/cli.h +++ b/libs/linglong/src/linglong/cli/cli.h @@ -18,7 +18,6 @@ #include "linglong/runtime/container_builder.h" #include "linglong/utils/error/error.h" #include "linglong/utils/log/log.h" -#include "linglong/utils/serialize/json.h" #include @@ -236,7 +235,7 @@ class Cli : public QObject reply.waitForFinished(); if (reply.isError()) { - return LINGLONG_ERR(reply.error().message(), reply.error().type()); + return LINGLONG_ERR(reply.error().message().toStdString(), reply.error().type()); } auto result = common::serialize::fromQVariantMap(reply.value()); diff --git a/libs/linglong/src/linglong/cli/dbus_notifier.cpp b/libs/linglong/src/linglong/cli/dbus_notifier.cpp index 67c3349f7..f9288d3e9 100644 --- a/libs/linglong/src/linglong/cli/dbus_notifier.cpp +++ b/libs/linglong/src/linglong/cli/dbus_notifier.cpp @@ -5,9 +5,9 @@ #include "dbus_notifier.h" #include "linglong/utils/finally/finally.h" +#include "linglong/utils/log/log.h" #include -#include #include namespace linglong::cli { @@ -45,7 +45,7 @@ linglong::utils::error::Result DBusNotifier::getCapabilities() noex QDBusReply reply = inter.call(QDBus::Block, "GetCapabilities"); if (!reply.isValid()) { - auto msg = "invoke GetCapabilities error:" + reply.error().message(); + auto msg = "invoke GetCapabilities error:" + reply.error().message().toStdString(); return LINGLONG_ERR(msg); } @@ -74,7 +74,7 @@ linglong::utils::error::Result DBusNotifier::notify(const QString &appN hints, expireTimeout); if (!reply.isValid()) { - auto msg = "send notification error:" + reply.error().message(); + auto msg = "send notification error:" + reply.error().message().toStdString(); return LINGLONG_ERR(msg); } @@ -94,7 +94,7 @@ utils::error::Result DBusNotifier::notify(const api::types::v1::Interactio { { "urgency", 1 } }, -1); if (!reply) { - return LINGLONG_ERR("failed to notify: " + reply.error().message()); + return LINGLONG_ERR("failed to notify", reply); } return LINGLONG_OK; @@ -148,7 +148,7 @@ DBusNotifier::request(const api::types::v1::InteractionRequest &request) { { "urgency", 1 } }, 0); if (!reply) { - return LINGLONG_ERR("failed to notify: " + reply.error().message()); + return LINGLONG_ERR("failed to notify", reply); } notificationID = *reply; @@ -176,8 +176,7 @@ DBusNotifier::request(const api::types::v1::InteractionRequest &request) break; } - qCritical() << "unexpected reason:" << static_cast(reason) - << "control flow shouldn't be here:" << __FILE__ << __LINE__; + LogE("unexpected reason: {}", static_cast(reason)); std::abort(); } diff --git a/libs/linglong/src/linglong/common/dbus/properties_forwarder.cpp b/libs/linglong/src/linglong/common/dbus/properties_forwarder.cpp index 1a4d25a13..2743544fb 100644 --- a/libs/linglong/src/linglong/common/dbus/properties_forwarder.cpp +++ b/libs/linglong/src/linglong/common/dbus/properties_forwarder.cpp @@ -4,6 +4,7 @@ #include "properties_forwarder.h" +#include "linglong/common/formatter.h" #include "linglong/utils/log/log.h" #include @@ -57,7 +58,7 @@ utils::error::Result PropertiesForwarder::forward() noexcept if (!connection.send(msg)) { return LINGLONG_ERR( - QString{ "send dbus message failed: %1" }.arg(connection.lastError().message())); + fmt::format("send dbus message failed: {}", connection.lastError().message())); } return LINGLONG_OK; diff --git a/libs/linglong/src/linglong/common/dbus/register.h b/libs/linglong/src/linglong/common/dbus/register.h index adbb00fd1..ffa7c34f0 100644 --- a/libs/linglong/src/linglong/common/dbus/register.h +++ b/libs/linglong/src/linglong/common/dbus/register.h @@ -46,7 +46,8 @@ inline void unregisterDBusObject(QDBusConnection conn, const QString &path) // FIXME: use real ERROR CODE defined in API. if (conn.lastError().isValid()) { - return LINGLONG_ERR(conn.lastError().name() + ": " + conn.lastError().message()); + return LINGLONG_ERR( + fmt::format("{}: {}", conn.lastError().name(), conn.lastError().message())); } return LINGLONG_ERR("service name existed."); @@ -64,7 +65,8 @@ inline void unregisterDBusObject(QDBusConnection conn, const QString &path) // FIXME: use real ERROR CODE defined in API. if (conn.lastError().isValid()) { - return LINGLONG_ERR(conn.lastError().name() + ": " + conn.lastError().message()); + return LINGLONG_ERR( + fmt::format("{}: {}", conn.lastError().name(), conn.lastError().message())); } return LINGLONG_ERR("unknown"); diff --git a/libs/linglong/src/linglong/common/formatter.h b/libs/linglong/src/linglong/common/formatter.h index c91cd38d9..8d320a0b4 100644 --- a/libs/linglong/src/linglong/common/formatter.h +++ b/libs/linglong/src/linglong/common/formatter.h @@ -44,3 +44,32 @@ struct fmt::formatter : fmt::formatter auto format(const GError &error, fmt::format_context &ctx) -> fmt::format_context::iterator; #endif }; + +template +struct ptr_view +{ + ptr_view(T *v) + : value(v) + { + } + + T *value; +}; + +template +struct fmt::formatter> : fmt::formatter +{ +#if FMT_VERSION >= 70000 + auto format(const ptr_view &ptr, fmt::format_context &ctx) const + -> fmt::format_context::iterator +#else + auto format(const ptr_view &ptr, fmt::format_context &ctx) -> fmt::format_context::iterator +#endif + { + if (ptr.value == nullptr) { + return formatter::format("no error(nullptr)", ctx); + } else { + return formatter::format(fmt::format("{}", *ptr.value), ctx); + } + } +}; diff --git a/libs/linglong/src/linglong/common/gkeyfile_wrapper.h b/libs/linglong/src/linglong/common/gkeyfile_wrapper.h index 3a8eea1bd..def7b1e82 100644 --- a/libs/linglong/src/linglong/common/gkeyfile_wrapper.h +++ b/libs/linglong/src/linglong/common/gkeyfile_wrapper.h @@ -6,6 +6,7 @@ #pragma once +#include "linglong/common/formatter.h" #include "linglong/utils/error/error.h" #include @@ -48,7 +49,7 @@ class GKeyFileWrapper final G_KEY_FILE_KEEP_TRANSLATIONS, &gErr); if (gErr != nullptr) { - return LINGLONG_ERR("g_key_file_load_from_file", gErr); + return LINGLONG_ERR(fmt::format("g_key_file_load_from_file {}", ptr_view(gErr))); } return entry; @@ -74,7 +75,7 @@ class GKeyFileWrapper final &gErr); if (gErr != nullptr) { - return LINGLONG_ERR("g_key_file_get_string", gErr); + return LINGLONG_ERR(fmt::format("g_key_file_get_string {}", ptr_view(gErr))); } return value; @@ -105,7 +106,7 @@ class GKeyFileWrapper final &length, &gErr); if (gErr != nullptr) { - return LINGLONG_ERR("g_key_file_get_keys", gErr); + return LINGLONG_ERR(fmt::format("g_key_file_get_keys {}", ptr_view(gErr))); } QStringList result; @@ -125,7 +126,7 @@ class GKeyFileWrapper final g_key_file_save_to_file(this->gKeyFile.get(), filepath.toLocal8Bit().constData(), &gErr); if (gErr != nullptr) { - return LINGLONG_ERR("g_key_file_save_to_file", gErr); + return LINGLONG_ERR(fmt::format("g_key_file_save_to_file {}", ptr_view(gErr))); } return LINGLONG_OK; @@ -143,7 +144,7 @@ class GKeyFileWrapper final &gErr) == FALSE) { if (gErr != nullptr) { - return LINGLONG_ERR("g_key_file_has_key", gErr); + return LINGLONG_ERR(fmt::format("g_key_file_has_key {}", ptr_view(gErr))); } return false; } diff --git a/libs/utils/src/linglong/utils/global/initialize.cpp b/libs/linglong/src/linglong/common/global/initialize.cpp similarity index 51% rename from libs/utils/src/linglong/utils/global/initialize.cpp rename to libs/linglong/src/linglong/common/global/initialize.cpp index 5bc105971..54613b018 100644 --- a/libs/utils/src/linglong/utils/global/initialize.cpp +++ b/libs/linglong/src/linglong/common/global/initialize.cpp @@ -4,25 +4,22 @@ * SPDX-License-Identifier: LGPL-3.0-or-later */ -#include "linglong/utils/global/initialize.h" +#include "initialize.h" #include "configure.h" #include "linglong/common/strings.h" -#include -#include #include #include #include -#include #include #include #include -namespace linglong::utils::global { +namespace linglong::common::global { using namespace linglong::common; using linglong::utils::log::LogBackend; @@ -32,7 +29,7 @@ namespace { void catchUnixSignals(std::initializer_list quitSignals) { auto handler = [](int sig) -> void { - qInfo().noquote() << QString("Quit the application by signal(%1).").arg(sig); + LogI("Quit the application by signal({}).", sig); QCoreApplication::quit(); GlobalTaskControl::cancel(); }; @@ -52,68 +49,6 @@ void catchUnixSignals(std::initializer_list quitSignals) sigaction(sig, &sa, nullptr); } -bool forceStderrLogging = false; - -auto shouldLogToStderr() -> bool -{ - return forceStderrLogging || isatty(STDERR_FILENO); -} - -void linglong_message_handler(QtMsgType type, - const QMessageLogContext &context, - const QString &message) -{ - QString formattedMessage = qFormatLogMessage(type, context, message); - // 非tty环境可能是从systemd启动的应用,为避免和下面的sd_journal输出重复,不输出日志到标准错误流 - if (shouldLogToStderr()) { - // print nothing if message pattern didn't apply / was empty. - // (still print empty lines, e.g. because message itself was empty) - if (formattedMessage.isNull()) - return; - - fprintf(stderr, - "(%d) %s:%d %s\n", - getpid(), - context.file, - context.line, - formattedMessage.toLocal8Bit().constData()); - fflush(stderr); - } - - int priority = LOG_INFO; // Informational - switch (type) { - case QtDebugMsg: - priority = LOG_DEBUG; // Debug-level messages - break; - case QtInfoMsg: - priority = LOG_INFO; // Informational conditions - break; - case QtWarningMsg: - priority = LOG_WARNING; // Warning conditions - break; - case QtCriticalMsg: - priority = LOG_CRIT; // Critical conditions - break; - case QtFatalMsg: - priority = LOG_ALERT; // Action must be taken immediately - break; - } - - auto file = QString("CODE_FILE=%1").arg((context.file != nullptr) ? context.file : "unknown"); - auto line = QString("CODE_LINE=%1").arg(context.line); - - sd_journal_send_with_location(file.toUtf8().constData(), - line.toUtf8().constData(), - (context.function != nullptr) ? context.function : "unknown", - "MESSAGE=%s", - formattedMessage.toUtf8().constData(), - "PRIORITY=%i", - priority, - "QT_CATEGORY=%s", - (context.category != nullptr) ? context.category : "unknown", - NULL); -} - LogLevel parseLogLevel(const char *level) { if (common::strings::stringEqual(level, "debug")) { @@ -182,24 +117,11 @@ void initLinyapsLogSystem(linglong::utils::log::LogBackend backend) setLogBackend(logBackend); } -void applicationInitialize(bool appForceStderrLogging) +void applicationInitialize() { - QCoreApplication::setOrganizationName("deepin"); - QLoggingCategory::setFilterRules("*.debug=false"); - if (appForceStderrLogging) { - forceStderrLogging = true; - } else if (qEnvironmentVariableIntValue("QT_FORCE_STDERR_LOGGING")) { - forceStderrLogging = true; - } - installMessageHandler(); catchUnixSignals({ SIGTERM, SIGQUIT, SIGINT, SIGHUP }); } -void installMessageHandler() -{ - qInstallMessageHandler(linglong_message_handler); -} - // Return current binary file is installed on the system bool linglongInstalled() { @@ -224,4 +146,4 @@ bool GlobalTaskControl::canceled() return globalTaskControl.cancelFlag.load(); } -} // namespace linglong::utils::global +} // namespace linglong::common::global diff --git a/libs/utils/src/linglong/utils/global/initialize.h b/libs/linglong/src/linglong/common/global/initialize.h similarity index 74% rename from libs/utils/src/linglong/utils/global/initialize.h rename to libs/linglong/src/linglong/common/global/initialize.h index 6a0639174..fb5753b12 100644 --- a/libs/utils/src/linglong/utils/global/initialize.h +++ b/libs/linglong/src/linglong/common/global/initialize.h @@ -12,12 +12,10 @@ #include -namespace linglong::utils::global { +namespace linglong::common::global { -void applicationInitialize(bool appForceStderrLogging = false); -void installMessageHandler(); +void applicationInitialize(); bool linglongInstalled(); -void cancelAllTask() noexcept; void initLinyapsLogSystem(linglong::utils::log::LogBackend backend); class GlobalTaskControl : public QObject @@ -34,4 +32,4 @@ class GlobalTaskControl : public QObject std::atomic cancelFlag = false; }; -} // namespace linglong::utils::global +} // namespace linglong::common::global diff --git a/libs/linglong/src/linglong/package/architecture.cpp b/libs/linglong/src/linglong/package/architecture.cpp index e97a399cc..d1310b660 100644 --- a/libs/linglong/src/linglong/package/architecture.cpp +++ b/libs/linglong/src/linglong/package/architecture.cpp @@ -6,6 +6,8 @@ #include "linglong/package/architecture.h" +#include "linglong/utils/log/log.h" + #include #include @@ -115,7 +117,7 @@ bool isNewWorldLoongArch() // 打开可执行文件 std::ifstream file("/proc/self/exe", std::ios::binary); if (!file) { - qCritical() << "Failed to open executable file"; + LogE("Failed to open executable file"); isLoongArch = false; return false; } @@ -124,7 +126,7 @@ bool isNewWorldLoongArch() Elf64_Ehdr ehdr; file.read(reinterpret_cast(&ehdr), sizeof(ehdr)); if (!file || std::memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0) { - qCritical() << "Not a valid ELF file."; + LogE("Not a valid ELF file."); isLoongArch = false; return false; } diff --git a/libs/linglong/src/linglong/package/layer_file.cpp b/libs/linglong/src/linglong/package/layer_file.cpp index 0d4c424fe..f2d2eb0d3 100644 --- a/libs/linglong/src/linglong/package/layer_file.cpp +++ b/libs/linglong/src/linglong/package/layer_file.cpp @@ -131,7 +131,7 @@ utils::error::Result LayerFile::saveTo(const QString &destination) noexcep LINGLONG_TRACE(fmt::format("save layer file to {}", destination.toStdString())); if (!this->copy(destination)) { - return LINGLONG_ERR(*this); + return LINGLONG_ERR(this->errorString().toStdString()); } return LINGLONG_OK; diff --git a/libs/linglong/src/linglong/package/layer_file.h b/libs/linglong/src/linglong/package/layer_file.h index c80145204..447c62689 100644 --- a/libs/linglong/src/linglong/package/layer_file.h +++ b/libs/linglong/src/linglong/package/layer_file.h @@ -10,6 +10,7 @@ #include "linglong/utils/error/error.h" #include +#include namespace linglong::package { diff --git a/libs/linglong/src/linglong/package/layer_packager.cpp b/libs/linglong/src/linglong/package/layer_packager.cpp index da4f49394..b8651460f 100644 --- a/libs/linglong/src/linglong/package/layer_packager.cpp +++ b/libs/linglong/src/linglong/package/layer_packager.cpp @@ -105,12 +105,12 @@ LayerPackager::pack(const LayerDir &dir, const QString &layerFilePath) const } if (!layer.open(QIODevice::WriteOnly | QIODevice::Append)) { - return LINGLONG_ERR(layer); + return LINGLONG_ERR(layer.errorString().toStdString()); } const auto &number = magicNumber(); if (layer.write(number) < 0) { - return LINGLONG_ERR(layer); + return LINGLONG_ERR(layer.errorString().toStdString()); } // generate LayerInfo @@ -137,11 +137,11 @@ LayerPackager::pack(const LayerDir &dir, const QString &layerFilePath) const Q_ASSERT(dataSizeStream.status() == QDataStream::Status::Ok); if (layer.write(dataSizeBytes) < 0) { - return LINGLONG_ERR(layer); + return LINGLONG_ERR(layer.errorString().toStdString()); } if (layer.write(data) < 0) { - return LINGLONG_ERR(layer); + return LINGLONG_ERR(layer.errorString().toStdString()); } layer.close(); @@ -190,7 +190,8 @@ utils::error::Result LayerPackager::copyFile(LayerFile &file, while (true) { auto n = file.read(buff, 4096); if (n < 0) { - return LINGLONG_ERR("Failed to read from layer file: " + file.errorString()); + return LINGLONG_ERR("Failed to read from layer file: " + + file.errorString().toStdString()); } if (n == 0) { break; diff --git a/libs/linglong/src/linglong/package/uab_file.cpp b/libs/linglong/src/linglong/package/uab_file.cpp index 55ffffafc..f40b14880 100644 --- a/libs/linglong/src/linglong/package/uab_file.cpp +++ b/libs/linglong/src/linglong/package/uab_file.cpp @@ -6,6 +6,7 @@ #include "linglong/api/types/v1/Generators.hpp" #include "linglong/common/error.h" +#include "linglong/common/formatter.h" #include "linglong/utils/cmd.h" #include "linglong/utils/error/error.h" #include "linglong/utils/finally/finally.h" @@ -41,13 +42,13 @@ utils::error::Result> UABFile::loadFromFile(int fd) noe auto file = std::make_unique(); if (!file->open(fd, QIODevice::ReadOnly, FileHandleFlag::AutoCloseHandle)) { - return LINGLONG_ERR(QString{ "open uab failed: %1" }.arg(file->errorString())); + return LINGLONG_ERR(fmt::format("open uab failed: {}", file->errorString())); } elf_version(EV_CURRENT); auto *elf = elf_begin(fd, ELF_C_READ, nullptr); if (elf == nullptr) { - return LINGLONG_ERR(QString{ "libelf err: %1" }.arg(elf_errmsg(errno))); + return LINGLONG_ERR(fmt::format("libelf err: {}", elf_errmsg(errno))); } file->e = elf; @@ -82,7 +83,7 @@ utils::error::Result UABFile::getSectionHeader(const QString §ion size_t shdrstrndx{ 0 }; if (elf_getshdrstrndx(this->e, &shdrstrndx) == -1) { return LINGLONG_ERR( - QString{ "failed to get section header index of bundle: %1" }.arg(elf_errmsg(errno))); + fmt::format("failed to get section header index of bundle: {}", elf_errmsg(errno))); } Elf_Scn *scn{ nullptr }; @@ -90,7 +91,7 @@ utils::error::Result UABFile::getSectionHeader(const QString §ion GElf_Shdr shdr; if (gelf_getshdr(scn, &shdr) == nullptr) { return LINGLONG_ERR( - QString{ "failed to get section header of bundle: %1" }.arg(elf_errmsg(errno))); + fmt::format("failed to get section header of bundle: {}", elf_errmsg(errno))); } auto *sname = elf_strptr(this->e, shdrstrndx, shdr.sh_name); @@ -99,7 +100,7 @@ utils::error::Result UABFile::getSectionHeader(const QString §ion } } - return LINGLONG_ERR(QString{ "couldn't found section %1" }.arg(section)); + return LINGLONG_ERR(fmt::format("couldn't found section {}", section)); } utils::error::Result> @@ -123,14 +124,14 @@ UABFile::getMetaInfo() noexcept auto metaInfo = read(metaSh->sh_size).toStdString(); if (metaInfo.empty()) { - return LINGLONG_ERR(QString{ "couldn't read metaInfo from uab: %1" }.arg(errorString())); + return LINGLONG_ERR(fmt::format("couldn't read metaInfo from uab: {}", errorString())); } nlohmann::json content; try { content = nlohmann::json::parse(metaInfo); } catch (nlohmann::json::parse_error &e) { - return LINGLONG_ERR(QString{ "parsing metaInfo error: %1" }.arg(e.what())); + return LINGLONG_ERR("parsing metaInfo error", e); } catch (...) { return LINGLONG_ERR("unknown exception has been catch"); } @@ -155,7 +156,7 @@ utils::error::Result UABFile::verify() noexcept auto bundleSh = getSectionHeader(bundleSection); if (!bundleSh) { return LINGLONG_ERR( - QString{ "couldn't find bundle section which named %1" }.arg(bundleSection)); + fmt::format("couldn't find bundle section which named {}", bundleSection)); } std::array buf{}; @@ -172,7 +173,7 @@ utils::error::Result UABFile::verify() noexcept int bytesRead{ 0 }; while ((bytesRead = read(buf.data(), readBytes)) != 0) { if (bytesRead == -1) { - return LINGLONG_ERR(QString{ "read error: %1" }.arg(errorString())); + return LINGLONG_ERR(fmt::format("read error: {}", errorString())); } cryptor.addData( #if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0) @@ -223,7 +224,7 @@ utils::error::Result UABFile::unpack() noexcept unpackPath = std::filesystem::temp_directory_path() / dirName / "unpack"; ret = this->mkdirDir(unpackPath); if (!ret) { - return LINGLONG_ERR(QString("failed to create directory ") + unpackPath.c_str(), ret); + return LINGLONG_ERR("failed to create directory " + unpackPath.string(), ret); } } @@ -311,7 +312,7 @@ utils::error::Result UABFile::extractSignData() noexcept auto tarFd = ::open(tarFile.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); if (tarFd == -1) { return LINGLONG_ERR( - QString{ "open %1 failed: %2" }.arg(tarFile.c_str()).arg(strerror(errno))); + fmt::format("open {} failed: {}", tarFile, common::error::errorString(errno))); } auto removeTar = utils::finally::finally([&tarFd, &tarFile] { @@ -422,13 +423,13 @@ utils::error::Result UABFile::saveErofsToFile(const std::string &path) } ofs.write(buf.data(), bytesRead); if (ofs.fail()) { - return LINGLONG_ERR(QString{ "write %1 failed" }.arg(path.c_str())); + return LINGLONG_ERR(fmt::format("write {} failed", path)); } bundleLength -= bytesRead; } ofs.close(); if (ofs.fail()) { - return LINGLONG_ERR(QString{ "close %1 failed" }.arg(path.c_str())); + return LINGLONG_ERR(fmt::format("close {} failed", path)); } return LINGLONG_OK; } diff --git a/libs/linglong/src/linglong/package/uab_packager.cpp b/libs/linglong/src/linglong/package/uab_packager.cpp index 366fe2979..3483eb17a 100644 --- a/libs/linglong/src/linglong/package/uab_packager.cpp +++ b/libs/linglong/src/linglong/package/uab_packager.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -984,7 +985,7 @@ utils::error::Result UABPackager::loadBlackList() noexcept auto [_, success] = this->blackList.emplace(line); if (!success) { - qWarning() << fmt::format("duplicate entry: {}", line); + LogW("duplicate entry: {}", line); } } @@ -998,9 +999,9 @@ utils::error::Result UABPackager::loadNeededFiles() noexcept auto file = workDir / "linglong" / "depends.yaml"; if (!std::filesystem::exists(file)) { return LINGLONG_ERR( - QString{ "%1 is generated by ldd-check but not found currently, it may be " - "deleted or ldd-check has been skipped" } - .arg(file.c_str())); + fmt::format("{} is generated by ldd-check but not found currently, it may be " + "deleted or ldd-check has been skipped", + file)); } auto content = YAML::LoadFile(file.string()); diff --git a/libs/linglong/src/linglong/package/version.cpp b/libs/linglong/src/linglong/package/version.cpp index 3f34fecc2..1664d11fa 100644 --- a/libs/linglong/src/linglong/package/version.cpp +++ b/libs/linglong/src/linglong/package/version.cpp @@ -7,6 +7,7 @@ #include "linglong/package/fallback_version.h" #include "linglong/package/versionv2.h" +#include "linglong/utils/log/log.h" #include @@ -72,7 +73,7 @@ std::vector Version::filterByFuzzyVersi for (auto it = list.begin(); it != list.end();) { auto packageVerRet = package::Version::parse(it->version.c_str()); if (!packageVerRet) { - qWarning() << "Ignore invalid package record " << packageVerRet.error(); + LogW("Ignore invalid package record {}", packageVerRet.error()); it = list.erase(it); continue; } diff --git a/libs/linglong/src/linglong/package_manager/package_manager.cpp b/libs/linglong/src/linglong/package_manager/package_manager.cpp index a07b51035..e035c534e 100644 --- a/libs/linglong/src/linglong/package_manager/package_manager.cpp +++ b/libs/linglong/src/linglong/package_manager/package_manager.cpp @@ -36,12 +36,9 @@ #include #include #include -#include #include -#include #include #include -#include #include #include @@ -107,15 +104,13 @@ PackageManager::PackageManager(linglong::repo::OSTreeRepo &repo, try { deferredTimeOut = std::stoi(deferredTimeOutEnv) * 1s; } catch (std::invalid_argument &e) { - qWarning() << "failed to parse LINGLONG_DEFERRED_TIMEOUT[" << deferredTimeOutEnv - << "]:" << e.what(); + LogW("failed to parse LINGLONG_DEFERRED_TIMEOUT[{}]: {}", deferredTimeOutEnv, e.what()); } catch (std::out_of_range &e) { - qWarning() << "failed to parse LINGLONG_DEFERRED_TIMEOUT[" << deferredTimeOutEnv - << "]:" << e.what(); + LogW("failed to parse LINGLONG_DEFERRED_TIMEOUT[{}]: {}", deferredTimeOutEnv, e.what()); } } - qInfo().nospace() << "deferredTimeOut:" << deferredTimeOut.count() << "s"; + LogD("deferredTimeOut: {}s", deferredTimeOut.count()); auto *timer = new QTimer(this); timer->setInterval(deferredTimeOut); @@ -131,7 +126,7 @@ PackageManager::~PackageManager() { auto ret = unlockRepo(); if (!ret) { - qCritical() << "failed to unlock repo:" << ret.error().message(); + LogE("failed to unlock repo: {}", ret.error()); } } @@ -141,22 +136,19 @@ utils::error::Result PackageManager::isRefBusy(const package::Reference &r auto ret = lockRepo(); if (!ret) { - return LINGLONG_ERR( - QStringLiteral("failed to lock repo, underlying data will not be removed: %1") - .arg(ret.error().message().c_str())); + return LINGLONG_ERR("failed to lock repo, underlying data will not be removed", ret); } auto unlock = utils::finally::finally([this] { auto ret = unlockRepo(); if (!ret) { - qCritical() << "failed to unlock repo:" << ret.error().message(); + LogE("failed to unlock repo: {}", ret.error()); } }); auto running = getAllRunningContainers(); if (!running) { - return LINGLONG_ERR(QStringLiteral("failed to get running containers: %1") - .arg(running.error().message().c_str())); + return LINGLONG_ERR("failed to get running containers", running); } auto &runningRef = *running; @@ -193,8 +185,7 @@ PackageManager::getAllRunningContainers() noexcept std::error_code ec; auto user_iterator = std::filesystem::directory_iterator{ "/run/linglong", ec }; if (ec) { - return LINGLONG_ERR( - QStringLiteral("failed to list /run/linglong: %1").arg(ec.message().c_str())); + return LINGLONG_ERR("failed to list /run/linglong", ec); } std::vector result; @@ -205,9 +196,7 @@ PackageManager::getAllRunningContainers() noexcept auto process_iterator = std::filesystem::directory_iterator{ entry.path(), ec }; if (ec) { - return LINGLONG_ERR(QStringLiteral("failed to list %1: %2") - .arg(entry.path().c_str()) - .arg(ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to list {}", entry.path()), ec); } for (const auto &process_entry : process_iterator) { @@ -218,13 +207,11 @@ PackageManager::getAllRunningContainers() noexcept auto pid = process_entry.path().filename().string(); if (auto procDir = "/proc/" + pid; !std::filesystem::exists(procDir, ec)) { if (ec) { - return LINGLONG_ERR(QStringLiteral("failed to get state of %1: %2") - .arg(procDir.c_str()) - .arg(ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to get state of {}", procDir), ec); } - qInfo() << "ignore" << process_entry.path().c_str() - << ",because corrsponding process is not found."; + LogI("ignore {} because corrsponding process is not found", + process_entry.path().c_str()); continue; } @@ -232,9 +219,9 @@ PackageManager::getAllRunningContainers() noexcept utils::serialize::LoadJSONFile( process_entry.path()); if (!content) { - return LINGLONG_ERR(QStringLiteral("failed to load info from %1: %2") - .arg(process_entry.path().c_str()) - .arg(content.error().message().c_str())); + return LINGLONG_ERR( + fmt::format("failed to load info from {}", process_entry.path()), + content); } result.emplace_back(std::move(content).value()); @@ -352,13 +339,13 @@ utils::error::Result PackageManager::switchAppVersion(const package::Refer void PackageManager::deferredUninstall() noexcept { if (auto ret = lockRepo(); !ret) { - qCritical() << "failed to lock repo:" << ret.error().message(); + LogE("failed to lock repo: {}", ret.error()); return; } auto unlock = utils::finally::finally([this] { auto ret = unlockRepo(); if (!ret) { - qCritical() << "failed to unlock repo:" << ret.error().message(); + LogE("failed to unlock repo: {}", ret.error()); } }); @@ -942,7 +929,7 @@ utils::error::Result PackageManager::Uninstall(PackageTask &taskContext, auto mergeRet = this->repo.mergeModules(); if (!mergeRet.has_value()) { - qCritical() << "merge modules failed: " << mergeRet.error().message(); + LogE("merge modules failed: {}", mergeRet.error()); } return LINGLONG_OK; @@ -1270,7 +1257,7 @@ PackageManager::Prune(std::vector &removed) noexc auto scanExtensionsByRef = [scanExtensionsByInfo, this](package::Reference &ref) { auto item = this->repo.getLayerItem(ref); if (!item) { - qWarning() << item.error().message(); + LogW("{}", item.error()); return; } scanExtensionsByInfo(item->info); @@ -1284,7 +1271,7 @@ PackageManager::Prune(std::vector &removed) noexc if (info.kind != "app") { auto ref = package::Reference::fromPackageInfo(info); if (!ref) { - qWarning() << ref.error().message(); + LogW("{}", ref.error()); continue; } // Note: if the ref already exists, it's ok, somebody depends it. @@ -1295,7 +1282,7 @@ PackageManager::Prune(std::vector &removed) noexc if (info.runtime) { auto runtimeFuzzyRef = package::FuzzyReference::parse(info.runtime.value()); if (!runtimeFuzzyRef) { - qWarning() << runtimeFuzzyRef.error().message(); + LogW("{}", runtimeFuzzyRef.error()); continue; } @@ -1306,7 +1293,7 @@ PackageManager::Prune(std::vector &removed) noexc .semanticMatching = true, }); if (!runtimeRef) { - qWarning() << runtimeRef.error().message(); + LogW("{}", runtimeRef.error()); continue; } target[*runtimeRef] += 1; @@ -1315,7 +1302,7 @@ PackageManager::Prune(std::vector &removed) noexc auto baseFuzzyRef = package::FuzzyReference::parse(info.base); if (!baseFuzzyRef) { - qWarning() << baseFuzzyRef.error().message(); + LogW("{}", baseFuzzyRef.error()); continue; } @@ -1326,7 +1313,7 @@ PackageManager::Prune(std::vector &removed) noexc .semanticMatching = true, }); if (!baseRef) { - qWarning() << baseRef.error().message(); + LogW("{}", baseRef.error()); continue; } target[*baseRef] += 1; @@ -1343,14 +1330,14 @@ PackageManager::Prune(std::vector &removed) noexc for (const auto &module : this->repo.getModuleList(it.first)) { auto layer = this->repo.getLayerDir(it.first, module); if (!layer) { - qWarning() << layer.error().message(); + LogW("{}", layer.error()); continue; } auto info = layer->info(); if (!info) { - qWarning() << info.error().message(); + LogW("{}", info.error()); continue; } @@ -1366,7 +1353,7 @@ PackageManager::Prune(std::vector &removed) noexc if (!target.empty()) { auto mergeRet = this->repo.mergeModules(); if (!mergeRet.has_value()) { - qCritical() << "merge modules failed: " << mergeRet.error().message(); + LogE("merge modules failed: {}", mergeRet.error()); } } auto pruneRet = this->repo.prune(); diff --git a/libs/linglong/src/linglong/package_manager/package_task.cpp b/libs/linglong/src/linglong/package_manager/package_task.cpp index c28ff7ce8..799d6451b 100644 --- a/libs/linglong/src/linglong/package_manager/package_task.cpp +++ b/libs/linglong/src/linglong/package_manager/package_task.cpp @@ -8,15 +8,11 @@ #include "linglong/common/dbus/register.h" #include "linglong/package_manager/package_manager.h" #include "linglong/utils/error/error.h" -#include "linglong/utils/global/initialize.h" #include "linglong/utils/log/formatter.h" // IWYU pragma: keep #include #include -#include -#include - #include const auto TASK_DONE = 100; @@ -95,8 +91,7 @@ utils::error::Result PackageTask::exposeOnDBus(const QDBusConnection &conn if (interfaceIndex == -1) { return LINGLONG_ERR("internal adaptor error"); } - auto ret = - linglong::common::dbus::registerDBusObject(connection, taskObjectPath().c_str(), this); + auto ret = common::dbus::registerDBusObject(connection, taskObjectPath().c_str(), this); if (!ret) { return LINGLONG_ERR(ret); } diff --git a/libs/linglong/src/linglong/repo/config.cpp b/libs/linglong/src/linglong/repo/config.cpp index eb9e0e0ff..5df85a02e 100644 --- a/libs/linglong/src/linglong/repo/config.cpp +++ b/libs/linglong/src/linglong/repo/config.cpp @@ -8,11 +8,14 @@ #include "linglong/api/types/v1/Generators.hpp" #include "linglong/utils/error/error.h" +#include "linglong/utils/log/log.h" #include "linglong/utils/serialize/yaml.h" #include "ytj/ytj.hpp" #include +#include + #include namespace linglong::repo { @@ -53,11 +56,11 @@ utils::error::Result loadConfig(const QStringList for (const auto &file : files) { auto config = loadConfig(file); if (!config.has_value()) { - qDebug() << "Failed to load repo config from" << file << ":" << config.error(); + LogD("Failed to load repo config from {}: {}", file.toStdString(), config.error()); continue; } - qDebug() << "load repo config from" << file; + LogD("load repo config from {}", file.toStdString()); return config; } diff --git a/libs/linglong/src/linglong/repo/ostree_repo.cpp b/libs/linglong/src/linglong/repo/ostree_repo.cpp index 0283dbd1b..f98af3b62 100644 --- a/libs/linglong/src/linglong/repo/ostree_repo.cpp +++ b/libs/linglong/src/linglong/repo/ostree_repo.cpp @@ -38,7 +38,6 @@ #include #include -#include #include #include #include @@ -197,13 +196,13 @@ utils::error::Result commitDirToRepo(std::vector dirs, g_autoptr(GError) gErr = nullptr; utils::Transaction transaction; if (ostree_repo_prepare_transaction(repo, NULL, NULL, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_prepare_transaction", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_prepare_transaction {}", ptr_view(gErr))); } transaction.addRollBack([repo]() noexcept { g_autoptr(GError) gErr = nullptr; if (ostree_repo_abort_transaction(repo, nullptr, &gErr) == FALSE) { - qCritical() << "ostree_repo_abort_transaction:" << gErr->message << gErr->code; + LogE("ostree_repo_abort_transaction {}", ptr_view(gErr)); } }); @@ -222,13 +221,14 @@ utils::error::Result commitDirToRepo(std::vector dirs, for (auto *dir : dirs) { if (ostree_repo_write_directory_to_mtree(repo, dir, mtree, modifier, nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_write_directory_to_mtree", gErr); + return LINGLONG_ERR( + fmt::format("ostree_repo_write_directory_to_mtree {}", ptr_view(gErr))); } } g_autoptr(GFile) file = nullptr; if (ostree_repo_write_mtree(repo, mtree, &file, nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_write_mtree", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_write_mtree {}", ptr_view(gErr))); } g_autofree char *commit = nullptr; @@ -242,7 +242,7 @@ utils::error::Result commitDirToRepo(std::vector dirs, NULL, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_write_commit", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_write_commit {}", ptr_view(gErr))); } ostree_repo_transaction_set_ref(repo, "local", refspec, commit); @@ -250,7 +250,7 @@ utils::error::Result commitDirToRepo(std::vector dirs, transaction.commit(); if (ostree_repo_commit_transaction(repo, NULL, NULL, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_commit_transaction", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_commit_transaction {}", ptr_view(gErr))); } return commit; @@ -279,7 +279,7 @@ updateOstreeRepoConfig(OstreeRepo *repo, nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_remote_change", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_remote_change {}", ptr_view(gErr))); } } } @@ -313,7 +313,7 @@ updateOstreeRepoConfig(OstreeRepo *repo, nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_remote_change", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_remote_change {}", ptr_view(gErr))); } } @@ -328,7 +328,7 @@ updateOstreeRepoConfig(OstreeRepo *repo, } if (ostree_repo_write_config(repo, configKeyFile, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_write_config", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_write_config {}", ptr_view(gErr))); } return LINGLONG_OK; @@ -355,7 +355,7 @@ createOstreeRepo(const QDir &location, Q_ASSERT(ostreeRepo != nullptr); if (ostree_repo_create(ostreeRepo, OSTREE_REPO_MODE_BARE_USER_ONLY, nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_create", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_create {}", ptr_view(gErr))); } auto result = updateOstreeRepoConfig(ostreeRepo, config, parent); @@ -405,7 +405,8 @@ utils::error::Result clearReferenceLocal(const linglong::rep auto pkgVer = linglong::package::Version::parse(ref.info.version); if (!pkgVer) { - qFatal("internal error: broken data of repo cache: %s", ref.info.version.c_str()); + LogE("internal error: broken data of repo cache: {}", ref.info.version); + return LINGLONG_ERR(pkgVer); } LogD("available layer {} found: {}", fuzzy.toString(), ref.info.version); @@ -430,7 +431,7 @@ utils::error::Result clearReferenceLocal(const linglong::rep } return package::Reference::fromPackageInfo(foundRef->info); -}; +} utils::error::Result semanticMatch(const package::FuzzyReference &fuzzy, const api::types::v1::PackageInfoV2 &record) noexcept @@ -475,11 +476,11 @@ std::optional matchReference(const api::types::v1::PackageIn } auto version = package::Version::parse(record.version); if (!version) { - qWarning() << "Ignore invalid package record" << recordStr.c_str() << version.error(); + LogW("Ignore invalid package record {}: {}", recordStr, version.error()); return std::nullopt; } if (record.arch.empty()) { - qWarning() << "Ignore invalid package record"; + LogW("Ignore empty arch package record {}", recordStr); return std::nullopt; } if (module == "binary") { @@ -493,13 +494,13 @@ std::optional matchReference(const api::types::v1::PackageIn } auto arch = package::Architecture::parse(record.arch[0]); if (!arch) { - qWarning() << "Ignore invalid package record" << recordStr.c_str() << arch.error(); + LogW("Ignore invalid package record {}: {}", recordStr, arch.error()); return std::nullopt; } auto currentRef = package::Reference::create(record.channel, fuzzy.id, *version, *arch); if (!currentRef) { - qWarning() << "Ignore invalid package record" << recordStr.c_str() << currentRef.error(); + LogW("Ignore invalid package record {}: {}", recordStr, currentRef.error()); return std::nullopt; } return *currentRef; @@ -536,7 +537,7 @@ OSTreeRepo::removeOstreeRef(const api::types::v1::RepositoryCacheLayersItem &lay nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_set_ref_immediate", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_set_ref_immediate {}", ptr_view(gErr))); } } @@ -559,12 +560,14 @@ utils::error::Result OSTreeRepo::handleRepositoryUpdate( if (!layerDir.mkpath(".")) { Q_ASSERT(false); - return LINGLONG_ERR(QString{ "couldn't create directory %1" }.arg(layerDir.absolutePath())); + return LINGLONG_ERR( + fmt::format("couldn't create directory {}", layerDir.absolutePath().toStdString())); } if (!layerDir.removeRecursively()) { Q_ASSERT(false); - return LINGLONG_ERR(QString{ "couldn't remove directory %1" }.arg(layerDir.absolutePath())); + return LINGLONG_ERR( + fmt::format("couldn't remove directory {}", layerDir.absolutePath().toStdString())); } g_autoptr(GError) gErr = nullptr; @@ -577,7 +580,7 @@ utils::error::Result OSTreeRepo::handleRepositoryUpdate( &commit, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_resolve_rev", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_resolve_rev {}", ptr_view(gErr))); } if (ostree_repo_checkout_at(this->ostreeRepo.get(), @@ -588,7 +591,8 @@ utils::error::Result OSTreeRepo::handleRepositoryUpdate( nullptr, &gErr) == FALSE) { - return LINGLONG_ERR(QString("ostree_repo_checkout_at %1").arg(path), gErr); + return LINGLONG_ERR( + fmt::format("ostree_repo_checkout_at {} {}", path.toStdString(), ptr_view(gErr))); } auto ret = this->cache->addLayerItem(layer); @@ -610,33 +614,26 @@ utils::error::Result OSTreeRepo::ensureEmptyLayerDir(const std::string &co if (std::filesystem::is_symlink(dir, ec)) { target = std::filesystem::read_symlink(dir, ec); if (ec) { - return LINGLONG_ERR( - QString{ "failed to resolve symlink %1: %2" }.arg(dir.c_str(), ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to resolve symlink {}", dir), ec); } if (!std::filesystem::remove(dir, ec)) { - return LINGLONG_ERR( - QString{ "failed to remove symlink %1: %2" }.arg(dir.c_str(), ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to remove symlink {}", dir), ec); } } if (ec && ec != std::errc::no_such_file_or_directory) { - return LINGLONG_ERR( - QString{ "check %1 is symlink failed: %2" }.arg(dir.c_str(), ec.message().c_str())); + return LINGLONG_ERR(fmt::format("check {} is symlink failed", dir), ec); } if (target && std::filesystem::exists(*target, ec)) { if (std::filesystem::remove_all(*target, ec) == static_cast(-1)) { - return LINGLONG_ERR( - QString{ "failed to remove layer dir %1: %2" }.arg(target->c_str(), - ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to remove layer dir {}", *target), ec); } } if (!std::filesystem::create_directories(dir, ec)) { if (ec) { - return LINGLONG_ERR( - QString{ "failed to create layer dir %1: %2" }.arg(dir.c_str(), - ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to create layer dir {}", dir), ec); } } @@ -657,14 +654,8 @@ OSTreeRepo::OSTreeRepo(const QDir &path, api::types::v1::RepoConfigV2 cfg) noexc : cfg(std::move(cfg)) { if (!path.exists()) { - qFatal("repo doesn't exists"); - } - - if (!QFileInfo(path.absolutePath()).isReadable()) { - auto msg = QString("read linglong repository(%1): permission denied ") - .arg(path.path()) - .toStdString(); - qFatal("%s", msg.c_str()); + LogE("repo doesn't exists"); + std::abort(); } // To avoid glib start thread @@ -693,8 +684,8 @@ OSTreeRepo::OSTreeRepo(const QDir &path, api::types::v1::RepoConfigV2 cfg) noexc this->cfg, *(this->ostreeRepo)); if (!ret) { - qCritical() << LINGLONG_ERRV(ret); - qFatal("abort"); + LogE("{}", ret.error()); + std::abort(); } this->cache = std::move(ret).value(); @@ -709,8 +700,8 @@ OSTreeRepo::OSTreeRepo(const QDir &path, api::types::v1::RepoConfigV2 cfg) noexc auto result = createOstreeRepo(this->ostreeRepoDir().absolutePath(), this->cfg); if (!result) { - qCritical() << LINGLONG_ERRV(result); - qFatal("abort"); + LogE("{}", result.error()); + std::abort(); } this->ostreeRepo.reset(*result); @@ -720,8 +711,8 @@ OSTreeRepo::OSTreeRepo(const QDir &path, api::types::v1::RepoConfigV2 cfg) noexc this->cfg, *(this->ostreeRepo)); if (!ret) { - qCritical() << LINGLONG_ERRV(ret); - qFatal("abort"); + LogE("{}", ret.error()); + std::abort(); } this->cache = std::move(ret).value(); @@ -781,8 +772,7 @@ OSTreeRepo::updateConfig(const api::types::v1::RepoConfigV2 &newCfg) noexcept transaction.addRollBack([this]() noexcept { auto result = updateOstreeRepoConfig(this->ostreeRepo.get(), this->cfg); if (!result) { - qCritical() << result.error(); - Q_ASSERT(false); + LogE("{}", result.error()); } }); if (!result) { @@ -811,8 +801,7 @@ utils::error::Result OSTreeRepo::setConfig(const api::types::v1::RepoConfi transaction.addRollBack([this]() noexcept { auto result = saveConfig(this->cfg, this->repoDir.absoluteFilePath("config.yaml")); if (!result) { - qCritical() << result.error(); - Q_ASSERT(false); + LogE("{}", result.error()); } }); LogI("update ostree repo config"); @@ -823,8 +812,7 @@ utils::error::Result OSTreeRepo::setConfig(const api::types::v1::RepoConfi transaction.addRollBack([this]() noexcept { auto result = updateOstreeRepoConfig(this->ostreeRepo.get(), this->cfg); if (!result) { - qCritical() << result.error(); - Q_ASSERT(false); + LogE("{}", result.error()); } }); LogI("rebuild repo cache"); @@ -872,7 +860,7 @@ OSTreeRepo::importLayerDir(const package::LayerDir &dir, for (const auto &overlay : overlays) { auto *gFile = g_file_new_for_path(overlay.c_str()); if (gFile == nullptr) { - qFatal("g_file_new_for_path"); + return LINGLONG_ERR(fmt::format("g_file_new_for_path {} failed", overlay)); } dirs.push_back(gFile); } @@ -936,7 +924,7 @@ utils::error::Result OSTreeRepo::pushToRemote(const std::string &remoteRep } if (signRes->code != 200) { const auto *msg = signRes->msg ? signRes->msg : "cannot send request to remote server"; - return LINGLONG_ERR(QString("sign error(%1): %2").arg(auth.username, msg)); + return LINGLONG_ERR(fmt::format("sign error({}): {}", auth.username, msg)); } auto *token = signRes->data->token; // 创建上传任务 @@ -950,14 +938,14 @@ utils::error::Result OSTreeRepo::pushToRemote(const std::string &remoteRep } if (newTaskRes->code != 200) { auto msg = newTaskRes->msg ? newTaskRes->msg : "cannot send request to remote server"; - return LINGLONG_ERR(QString("create task error: %1").arg(msg)); + return LINGLONG_ERR(fmt::format("create task error: {}", msg)); } auto *taskID = newTaskRes->data->id; // 上传tar文件 const QTemporaryDir tmpDir; if (!tmpDir.isValid()) { - return LINGLONG_ERR(tmpDir.errorString()); + return LINGLONG_ERR(tmpDir.errorString().toStdString()); } const auto tarFileName = fmt::format("{}.tgz", reference.id); @@ -977,23 +965,23 @@ utils::error::Result OSTreeRepo::pushToRemote(const std::string &remoteRep binary.filename = const_cast(tarFileName.data()); auto uploadTaskRes = client->uploadTaskFile(token, taskID, &binary); if (!uploadTaskRes) { - return LINGLONG_ERR(QString("upload file error(%1)").arg(taskID)); + return LINGLONG_ERR(fmt::format("upload file error({})", taskID)); } if (uploadTaskRes->code != 200) { const auto *msg = uploadTaskRes->msg ? uploadTaskRes->msg : "cannot send request to remote server"; - return LINGLONG_ERR(QString("upload file error(%1): %2").arg(taskID, msg)); + return LINGLONG_ERR(fmt::format("upload file error({}): {}", taskID, msg)); } // 查询任务状态 while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); auto uploadInfo = client->uploadTaskInfo(token, taskID); if (!uploadInfo) { - return LINGLONG_ERR(QString("get upload info error(%1)").arg(taskID)); + return LINGLONG_ERR(fmt::format("get upload info error({})", taskID)); } if (uploadInfo->code != 200) { auto msg = uploadInfo->msg ? uploadInfo->msg : "cannot send request to remote server"; - return LINGLONG_ERR(QString("get upload info error(%1): %2").arg(taskID, msg)); + return LINGLONG_ERR(fmt::format("get upload info error({}): {}", taskID, msg)); } LogI("pushing {}/{} status: {}", reference.toString(), module, uploadInfo->data->status); @@ -1001,7 +989,7 @@ utils::error::Result OSTreeRepo::pushToRemote(const std::string &remoteRep return LINGLONG_OK; } if (std::string(uploadInfo->data->status) == "failed") { - return LINGLONG_ERR(QString("An error occurred on the remote server(%1)").arg(taskID)); + return LINGLONG_ERR(fmt::format("An error occurred on the remote server({})", taskID)); } } } @@ -1083,11 +1071,11 @@ OSTreeRepo::undeployedLayer(const api::types::v1::RepositoryCacheLayersItem &lay target.cdUp(); while (topLevel.relativeFilePath(target.absolutePath()) != ".") { if (target.isEmpty() && !QFile::remove(target.absolutePath())) { - LogW("failed to remove {}", target.absolutePath()); + LogW("failed to remove {}", target.absolutePath().toStdString()); } if (!target.cdUp()) { - LogW("failed to cd up from {}", target.absolutePath()); + LogW("failed to cd up from {}", target.absolutePath().toStdString()); break; } } @@ -1113,7 +1101,7 @@ utils::error::Result OSTreeRepo::prune() nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_prune", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_prune {}", ptr_view(gErr))); } return LINGLONG_OK; } @@ -1164,7 +1152,7 @@ OSTreeRepo::getCommitSize(const std::string &remote, const std::string &refStrin nullptr, &gErr); if (status == FALSE) { - return LINGLONG_ERR("ostree_repo_pull", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_pull {}", ptr_view(gErr))); } // 使用refString获取commit的sha256 g_autofree char *resolved_rev = NULL; @@ -1173,7 +1161,7 @@ OSTreeRepo::getCommitSize(const std::string &remote, const std::string &refStrin FALSE, &resolved_rev, &gErr)) { - return LINGLONG_ERR("ostree_repo_resolve_rev", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_resolve_rev {}", ptr_view(gErr))); } // 使用sha256获取commit id g_autoptr(GVariant) commit = NULL; @@ -1182,12 +1170,12 @@ OSTreeRepo::getCommitSize(const std::string &remote, const std::string &refStrin resolved_rev, &commit, &gErr)) { - return LINGLONG_ERR("ostree_repo_load_variant", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_load_variant {}", ptr_view(gErr))); } g_autoptr(GPtrArray) sizes = NULL; // 获取commit中的所有对象大小 if (!ostree_commit_get_object_sizes(commit, &sizes, &gErr)) - return LINGLONG_ERR("ostree_commit_get_object_sizes", gErr); + return LINGLONG_ERR(fmt::format("ostree_commit_get_object_sizes {}", ptr_view(gErr))); // 计算需要下载的文件大小 guint64 needed_archived = 0; // 计算需要解压的文件大小 @@ -1204,7 +1192,7 @@ OSTreeRepo::getCommitSize(const std::string &remote, const std::string &refStrin &exists, NULL, &gErr)) - return LINGLONG_ERR("ostree_repo_has_object", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_has_object {}", ptr_view(gErr))); // Object not in local repo, so we need to download it if (!exists) { @@ -1220,7 +1208,7 @@ OSTreeRepo::getCommitSize(const std::string &remote, const std::string &refStrin nullptr, nullptr, &gErr)) { - return LINGLONG_ERR("ostree_repo_set_ref_immediate", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_set_ref_immediate {}", ptr_view(gErr))); } return std::vector{ needed_archived, needed_unpacked, needed_objects }; #else @@ -1273,7 +1261,7 @@ utils::error::Result OSTreeRepo::pull(service::Task &taskContext, if (status == FALSE) { // gErr->code is 0, so we compare string here. if (!strstr(gErr->message, "No such branch")) { - return LINGLONG_ERR("ostree_repo_pull_with_options", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_pull_with_options {}", ptr_view(gErr))); } LogW("ostree_repo_pull_with_options failed with [{}]: {}", gErr->code, gErr->message); shouldFallback = true; @@ -1301,7 +1289,7 @@ utils::error::Result OSTreeRepo::pull(service::Task &taskContext, &gErr); ostree_async_progress_finish(progress); if (status == FALSE) { - return LINGLONG_ERR("ostree_repo_pull_with_options", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_pull_with_options {}", ptr_view(gErr))); } } @@ -1317,14 +1305,14 @@ utils::error::Result OSTreeRepo::pull(service::Task &taskContext, cancellable, &gErr) == 0) { - return LINGLONG_ERR("ostree_repo_read_commit", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_read_commit {}", ptr_view(gErr))); } g_autoptr(GFile) infoFile = g_file_resolve_relative_path(layerRootDir, "info.json"); g_clear_error(&gErr); g_autofree gchar *content = nullptr; if (!g_file_load_contents(infoFile, nullptr, &content, nullptr, nullptr, &gErr)) { - return LINGLONG_ERR("g_file_load_contents", gErr); + return LINGLONG_ERR(fmt::format("g_file_load_contents: {}", ptr_view(gErr))); } auto info = utils::serialize::parsePackageInfo(content); if (!info) { @@ -1368,8 +1356,7 @@ OSTreeRepo::clearReference(const package::FuzzyReference &fuzzy, return LINGLONG_ERR(reference); } - qInfo() << reference.error(); - qInfo() << "fallback to Remote"; + LogD("fallback to remote: {}", reference.error()); } // TODO @@ -1598,12 +1585,12 @@ OSTreeRepo::searchRemote(const package::FuzzyReference &fuzzyRef, } if (response->code != 200) { - QString msg = (response->msg != nullptr) + std::string msg = (response->msg != nullptr) ? response->msg - : QString{ "cannot send request to remote server: %1\nIf the network is slow, " - "set a longer timeout via the LINGLONG_CONNECT_TIMEOUT environment " - "variable (current default: 5 seconds)." } - .arg(response->code); + : fmt::format("cannot send request to remote server: {}\nIf the network is slow, " + "set a longer timeout via the LINGLONG_CONNECT_TIMEOUT environment " + "variable (current default: 5 seconds).", + response->code); return LINGLONG_ERR(msg, (response->msg != nullptr ? utils::error::ErrorCode::Failed @@ -1730,8 +1717,9 @@ void OSTreeRepo::unexportReference(const std::string &layerDir) noexcept // NOTE: Everything in entries should be directory or symbol link. // But it can be some cache file, we should not remove it too. - qWarning() << "Invalid file detected." << info.absoluteFilePath(); - qWarning() << "If the file is a cache or something like that, ignore this warning."; + LogW("Invalid file detected. {}\nIf the file is a cache or something like that, ignore " + "this warning.", + info.absoluteFilePath().toStdString()); continue; } @@ -1740,8 +1728,7 @@ void OSTreeRepo::unexportReference(const std::string &layerDir) noexcept } if (!entriesDir.remove(it.filePath())) { - qCritical() << "Failed to remove" << it.filePath(); - Q_ASSERT(false); + LogE("Failed to remove {}", it.filePath().toStdString()); } } @@ -1766,7 +1753,7 @@ void OSTreeRepo::unexportReference(const std::string &layerDir) noexcept if (subDir.isEmpty()) { // 如果子目录为空,则删除它 if (!subDir.rmdir(subDirPath)) { - qDebug() << "Failed to remove directory:" << subDirPath; + LogD("Failed to remove directory: {}", subDirPath.toStdString()); continue; } } @@ -1996,8 +1983,7 @@ OSTreeRepo::exportEntries(const std::filesystem::path &rootEntriesDir, return LINGLONG_ERR("check appEntriesDir exists", ec); } if (!exists) { - qCritical() << QString("Failed to export %1:").arg(item.info.id.c_str()) - << appEntriesDir.c_str() << "not exists."; + LogE("Failed to export {}: {} not exists", item.info.id, appEntriesDir.string()); return LINGLONG_OK; } @@ -2005,16 +1991,16 @@ OSTreeRepo::exportEntries(const std::filesystem::path &rootEntriesDir, // The application configuration file can be exported after configuring it in the build // configuration file(linglong.yaml). const std::filesystem::path exportDirConfigPath = LINGLONG_DATA_DIR "/export-dirs.json"; - if (!std::filesystem::exists(exportDirConfigPath)) { + if (!std::filesystem::exists(exportDirConfigPath, ec)) { return LINGLONG_ERR( - QString{ "this export config file doesn't exist: %1" }.arg(exportDirConfigPath.c_str())); + fmt::format("this export config file doesn't exist: {}", exportDirConfigPath)); } auto exportDirConfig = linglong::utils::serialize::LoadJSONFile( exportDirConfigPath); if (!exportDirConfig) { return LINGLONG_ERR( - QString{ "failed to load export config file: %1" }.arg(exportDirConfigPath.c_str())); + fmt::format("failed to load export config file: {}", exportDirConfigPath)); } // 如果存在lib/systemd目录,优先导出lib/systemd,否则导出share/systemd(为兼容旧应用,新应用应该逐步将配置文件放在lib/systemd目录下) @@ -2044,7 +2030,7 @@ OSTreeRepo::exportEntries(const std::filesystem::path &rootEntriesDir, // 检查源目录是否存在,跳过不存在的目录 exists = std::filesystem::exists(source, ec); if (ec) { - return LINGLONG_ERR(QString("Failed to check file existence: ") + source.c_str(), ec); + return LINGLONG_ERR(fmt::format("Failed to check file existence: {}", source), ec); } if (!exists) { continue; @@ -2062,17 +2048,16 @@ utils::error::Result OSTreeRepo::fixExportAllEntries() noexcept auto exportVersion = repoDir.absoluteFilePath("entries/.version").toStdString(); auto data = linglong::utils::readFile(exportVersion); if (data && data == LINGLONG_EXPORT_VERSION) { - qDebug() << exportVersion.c_str() << data->c_str(); - qDebug() << "skip export entry, already exported"; + LogD("skip export entry, already exported: {} {}", exportVersion, *data); } else { auto ret = exportAllEntries(); if (!ret.has_value()) { - qCritical() << "failed to export entries:" << ret.error(); + LogE("failed to export entries: {}", ret.error()); return ret; } else { ret = linglong::utils::writeFile(exportVersion, LINGLONG_EXPORT_VERSION); if (!ret.has_value()) { - qCritical() << "failed to write export version:" << ret.error(); + LogE("failed to write export version: {}", ret.error()); return ret; } } @@ -2300,7 +2285,7 @@ auto OSTreeRepo::getLayerDir(const api::types::v1::RepositoryCacheLayersItem &la QDir dir = this->repoDir.absoluteFilePath(QString::fromStdString("layers/" + layer.commit)); if (!dir.exists()) { - return LINGLONG_ERR(dir.absolutePath() + " doesn't exist"); + return LINGLONG_ERR(dir.absolutePath().toStdString() + " doesn't exist"); } return std::filesystem::path{ dir.absolutePath().toStdString() }; } @@ -2401,7 +2386,7 @@ utils::error::Result OSTreeRepo::getMergedModuleDir( auto items = this->cache->queryMergedItems(); // 如果没有merged记录,尝试使用layer if (!items.has_value()) { - qDebug().nospace() << "not exists merged items"; + LogD("not exists merged items"); if (fallbackLayerDir) { return getLayerDir(layer); } @@ -2415,7 +2400,7 @@ utils::error::Result OSTreeRepo::getMergedModuleDir( return std::filesystem::path{ dir.path().toStdString() }; } - qWarning().nospace() << "not exists merged dir" << dir; + LogW("not exists merged dir {}", dir.path().toStdString()); } } @@ -2460,7 +2445,7 @@ utils::error::Result OSTreeRepo::createTempMergedModuleDir( } // 模块未全部找到 if (commits.size() < loadModules.size()) { - return LINGLONG_ERR(QString("missing module, only found: ") + findModules.c_str()); + return LINGLONG_ERR(fmt::format("missing module, only found: {}", findModules)); } // 合并layer,生成临时merged目录 const QString mergeID = hash.result().toHex(); @@ -2481,7 +2466,8 @@ utils::error::Result OSTreeRepo::createTempMergedModuleDir( nullptr, &gErr) == FALSE) { - return LINGLONG_ERR(QString("ostree_repo_checkout_at %1").arg(mergeTmp), gErr); + return LINGLONG_ERR( + fmt::format("ostree_repo_checkout_at {} {}", mergeTmp.toStdString(), ptr_view(gErr))); } } return std::filesystem::path{ mergeTmp.toStdString() }; @@ -2571,8 +2557,7 @@ utils::error::Result OSTreeRepo::mergeModules() const noexcept } // 将所有module文件合并到临时目录 for (const auto &layer : layers) { - qDebug() << "merge module" << it.first.c_str() - << layer.info.packageInfoV2Module.c_str(); + LogD("merge module {} {}", it.first, layer.info.packageInfoV2Module); int root = open("/", O_DIRECTORY); auto _ = utils::finally::finally([root]() { close(root); @@ -2588,8 +2573,8 @@ utils::error::Result OSTreeRepo::mergeModules() const noexcept nullptr, &gErr) == FALSE) { - return LINGLONG_ERR(QString("ostree_repo_checkout_at %1").arg(layer.commit.c_str()), - gErr); + return LINGLONG_ERR( + fmt::format("ostree_repo_checkout_at {} {}", layer.commit, ptr_view(gErr))); } } // 将临时目录改名到正式目录,以binary模块的commit为文件名 @@ -2630,7 +2615,7 @@ utils::error::Result OSTreeRepo::mergeModules() const noexcept if (leak) { std::filesystem::remove_all(entry.path(), ec); if (ec) { - qWarning() << ec.message().c_str(); + LogW("failed to remove unused merged dir {}: {}", entry.path(), ec.message()); } } } @@ -2661,7 +2646,7 @@ QString getOriginRawExec(const QString &execArgs, [[maybe_unused]] const QString return execArgs.mid(index + newExec.length()); } - qCritical() << "'-- ' or '--exec ' is not exist in" << execArgs << ", return an empty string"; + LogE("'-- ' or '--exec ' is not exist in {}, return an empty string", execArgs.toStdString()); return ""; } @@ -2714,7 +2699,7 @@ QString buildDesktopExec(QString origin, const QString &appID) noexcept return newExec; } default: { - qDebug() << "no need to mapping" << *next; + LogD("no need to mapping {}", next->toLatin1()); } break; } @@ -2742,7 +2727,7 @@ utils::error::Result desktopFileRewrite(const QString &filePath, const QSt } const auto &hasExec = *hasExecRet; if (!hasExec) { - qWarning() << "No Exec section in" << group << ", set a default value"; + LogW("No Exec section in {} group, set a default value", group.toStdString()); auto defaultExec = QString("%1 run %2").arg(LINGLONG_CLIENT_PATH, id); file->setValue("Exec", defaultExec, group); continue; @@ -2756,7 +2741,8 @@ utils::error::Result desktopFileRewrite(const QString &filePath, const QSt auto rawExec = *originExec; if (originExec->contains(LINGLONG_CLIENT_NAME)) { - qDebug() << "The Exec section in" << filePath << "has been generated, rewrite again."; + LogD("The Exec section in {} has been generated, rewrite again.", + filePath.toStdString()); rawExec = getOriginRawExec(*originExec, id); } @@ -2790,7 +2776,7 @@ utils::error::Result dbusServiceRewrite(const QString &filePath, const QSt } const auto &hasExec = *hasExecRet; if (!hasExec) { - qWarning() << "DBus service" << filePath << "has no Exec Section."; + LogW("DBus service {} has no Exec Section.", filePath.toStdString()); return LINGLONG_OK; } @@ -2801,7 +2787,7 @@ utils::error::Result dbusServiceRewrite(const QString &filePath, const QSt auto rawExec = *originExec; if (originExec->contains(LINGLONG_CLIENT_NAME)) { - qDebug() << "The Exec section in" << filePath << "has been generated, rewrite again."; + LogD("The Exec section in {} has been generated, rewrite again.", filePath.toStdString()); rawExec = getOriginRawExec(*originExec, id); } @@ -2847,7 +2833,8 @@ utils::error::Result systemdServiceRewrite(const QString &filePath, const auto rawExec = *originExec; if (originExec->contains(LINGLONG_CLIENT_NAME)) { - qDebug() << "The Exec section in" << filePath << "has been generated, rewrite again."; + LogD("The Exec section in {} has been generated, rewrite again.", + filePath.toStdString()); rawExec = getOriginRawExec(*originExec, id); } @@ -2891,7 +2878,8 @@ utils::error::Result contextMenuRewrite(const QString &filePath, const QSt } auto rawExec = *originExec; if (originExec->contains(LINGLONG_CLIENT_NAME)) { - qDebug() << "The Exec section in" << filePath << "has been generated, rewrite again."; + LogD("The Exec section in {} has been generated, rewrite again.", + filePath.toStdString()); rawExec = getOriginRawExec(*originExec, id); } @@ -2923,7 +2911,7 @@ utils::error::Result OSTreeRepo::IniLikeFileRewrite(const QFileInfo &info, | QFileDevice::ExeOwner | QFileDevice::ReadGroup | QFileDevice::ExeGroup | QFileDevice::ReadOther | QFileDevice::ExeOther)) { - qCritical() << "Failed to chmod" << info.absoluteFilePath(); + LogE("Failed to chmod {}", info.absoluteFilePath().toStdString()); Q_ASSERT(false); } diff --git a/libs/linglong/src/linglong/repo/repo_cache.cpp b/libs/linglong/src/linglong/repo/repo_cache.cpp index e0b3a43df..9304c1432 100644 --- a/libs/linglong/src/linglong/repo/repo_cache.cpp +++ b/libs/linglong/src/linglong/repo/repo_cache.cpp @@ -7,6 +7,7 @@ #include "repo_cache.h" #include "configure.h" +#include "linglong/common/formatter.h" #include "linglong/package/version.h" #include "linglong/utils/log/log.h" #include "linglong/utils/serialize/json.h" @@ -36,8 +37,7 @@ RepoCache::create(const std::filesystem::path &cacheFile, std::error_code ec; if (!std::filesystem::exists(repoCache->cacheFile, ec)) { if (ec) { - return LINGLONG_ERR( - QString{ "checking file existence failed: %1" }.arg(ec.message().c_str())); + return LINGLONG_ERR("checking file existence failed", ec); } auto ret = repoCache->rebuildCache(repoConfig, repo); @@ -90,7 +90,7 @@ utils::error::Result RepoCache::rebuildCache(const api::types::v1::RepoCon std::vector refs; if (ostree_repo_list_refs(&repo, nullptr, &refsTable, nullptr, &gErr) == FALSE) { - return LINGLONG_ERR("ostree_repo_list_refs", gErr); + return LINGLONG_ERR(fmt::format("ostree_repo_list_refs {}", ptr_view(gErr))); } // we couldn't report error within below lambda and for_each wouldn't return early if error @@ -107,7 +107,7 @@ utils::error::Result RepoCache::rebuildCache(const api::types::v1::RepoCon for (auto ref : refs) { auto pos = ref.find(':'); if (pos == std::string::npos) { - qWarning() << "invalid ref: " << ref.data(); + LogW("invalid ref: {}", ref.data()); continue; } @@ -118,7 +118,7 @@ utils::error::Result RepoCache::rebuildCache(const api::types::v1::RepoCon g_autoptr(GError) gErr{ nullptr }; g_autoptr(GFile) root{ nullptr }; if (ostree_repo_read_commit(&repo, ref.data(), &root, &commit, nullptr, &gErr) == FALSE) { - qWarning() << "ostree_repo_read_commit failed:" << gErr->message; + LogW("ostree_repo_read_commit failed: {}", ptr_view(gErr)); continue; } item.commit = commit; @@ -128,7 +128,7 @@ utils::error::Result RepoCache::rebuildCache(const api::types::v1::RepoCon g_clear_error(&gErr); g_autofree gchar *content = nullptr; if (!g_file_load_contents(infoFile, nullptr, &content, nullptr, nullptr, &gErr)) { - return LINGLONG_ERR("g_file_load_contents", gErr); + return LINGLONG_ERR(fmt::format("g_file_load_contents: {}", ptr_view(gErr))); } auto info = utils::serialize::parsePackageInfo(content); if (!info) { @@ -142,7 +142,7 @@ utils::error::Result RepoCache::rebuildCache(const api::types::v1::RepoCon // FIXME: ll-cli may initialize repo, it can make states.json own by root if (getuid() == 0) { - std::cerr << "Rebuild the cache by root, skip to write data to states.json"; + LogE("Rebuild the cache by root, skip to write data to states.json"); return LINGLONG_OK; } @@ -283,12 +283,12 @@ RepoCache::queryLayerItem(const repoCacheQuery &query) const noexcept std::sort(layers_view.begin(), layers_view.end(), [](itemRef lhs, itemRef rhs) { auto lhsVersion = linglong::package::Version::parse(lhs.get().info.version.c_str()); if (!lhsVersion) { - qCritical() << "Failed to parse lhs version: " << lhs.get().info.version.c_str(); + LogE("Failed to parse lhs version: {}", lhs.get().info.version); return false; } auto rhsVersion = linglong::package::Version::parse(rhs.get().info.version.c_str()); if (!rhsVersion) { - qCritical() << "Failed to parse rhs version: " << rhs.get().info.version.c_str(); + LogE("Failed to parse rhs version: {}", rhs.get().info.version); return false; } return *lhsVersion > *rhsVersion; @@ -316,8 +316,7 @@ utils::error::Result RepoCache::writeToDisk() std::error_code ec; auto parent_path = this->cacheFile.parent_path(); if (!std::filesystem::exists(parent_path, ec)) { - return LINGLONG_ERR("The parent directory of state.json doesn't exist:" - + QString::fromStdString(ec.message())); + return LINGLONG_ERR("The parent directory of state.json doesn't exist", ec); } auto dumpStatus = [](const std::filesystem::path &p, std::error_code &ec) { @@ -328,31 +327,30 @@ utils::error::Result RepoCache::writeToDisk() auto targetPerm = status.permissions(); using std::filesystem::perms; - auto out = qInfo().nospace(); - out << QString::fromStdString(p.string()) << ":"; - auto show = [&out, targetPerm](char op, perms perm) { - out << (perms::none == (perm & targetPerm) ? '-' : op); + auto show = [targetPerm](char op, perms perm) { + return perms::none == (perm & targetPerm) ? '-' : op; }; - show('r', perms::owner_read); - show('w', perms::owner_write); - show('x', perms::owner_exec); - show('r', perms::group_read); - show('w', perms::group_write); - show('x', perms::group_exec); - show('r', perms::others_read); - show('w', perms::others_write); - show('x', perms::others_exec); + LogI("{}: {}{}{}{}{}{}{}{}{}", + p.string(), + show('r', perms::owner_read), + show('w', perms::owner_write), + show('x', perms::owner_exec), + show('r', perms::group_read), + show('w', perms::group_write), + show('x', perms::group_exec), + show('r', perms::others_read), + show('w', perms::others_write), + show('x', perms::others_exec)); ec.clear(); }; auto tmpFile = parent_path / ("temp-" + this->cacheFile.filename().string()); auto ofs = std::ofstream(tmpFile); if (!ofs.is_open()) { // dump all info - qInfo() << "process uid:" << ::getuid() << "process gid:" << ::getgid(); + LogI("process uid {}, process gid {}", ::getuid(), ::getgid()); dumpStatus(parent_path, ec); if (ec) { - qCritical() << "get status of directory" << QString::fromStdString(parent_path) - << "error:" << QString::fromStdString(ec.message()); + LogE("get status of directory {} error: {}", parent_path.string(), ec.message()); } return LINGLONG_ERR("failed to update cache"); } @@ -363,30 +361,26 @@ utils::error::Result RepoCache::writeToDisk() std::filesystem::rename(tmpFile, this->cacheFile, ec); if (ec) { - qCritical().nospace() << "failed to rename from " - << QString::fromStdString(tmpFile.string()) << " to " - << QString::fromStdString(this->cacheFile.string()) << ": " - << QString::fromStdString(ec.message()); + LogE("failed to rename from {} to {}: {}", + tmpFile.string(), + this->cacheFile.string(), + ec.message()); // dump status of original file if (std::filesystem::exists(this->cacheFile, ec)) { dumpStatus(this->cacheFile, ec); if (ec) { - qCritical() << "get status of file" - << QString::fromStdString(this->cacheFile.string()) - << "error:" << QString::fromStdString(ec.message()); + LogE("failed to get status of file {}: {}", this->cacheFile.string(), ec.message()); ec.clear(); } } if (ec) { - qCritical() << "couldn't check the existence of" << this->cacheFile.c_str() << ":" - << QString::fromStdString(ec.message()); + LogE("couldn't check the existence of {}: {}", this->cacheFile.c_str(), ec.message()); ec.clear(); } std::filesystem::remove(tmpFile, ec); if (ec) { - qCritical() << "check file" << QString::fromStdString(this->cacheFile.string()) - << "exist error:" << QString::fromStdString(ec.message()); + LogE("failed to remove file {}: {}", tmpFile.string(), ec.message()); } return LINGLONG_ERR("failed to update cache"); @@ -395,7 +389,7 @@ utils::error::Result RepoCache::writeToDisk() auto versionTag = parent_path / ".version"; ofs.open(parent_path / ".version", std::ios::out | std::ios::trunc); if (ofs.fail()) { - qWarning() << "failed to open file" << versionTag.c_str(); + LogE("failed to open file {}", versionTag.string()); return LINGLONG_OK; } diff --git a/libs/linglong/src/linglong/runtime/container.cpp b/libs/linglong/src/linglong/runtime/container.cpp index 10eed8641..32f6d0ab4 100644 --- a/libs/linglong/src/linglong/runtime/container.cpp +++ b/libs/linglong/src/linglong/runtime/container.cpp @@ -9,6 +9,7 @@ #include "configure.h" #include "linglong/common/dir.h" #include "linglong/utils/bash_command_helper.h" +#include "linglong/utils/file.h" #include "linglong/utils/finally/finally.h" #include "linglong/utils/log/log.h" #include "ocppi/runtime/RunOption.hpp" @@ -16,6 +17,7 @@ #include +#include #include #include @@ -70,8 +72,7 @@ void mergeProcessConfig(ocppi::runtime::config::types::Process &dst, }); if (it != dstEnv.end()) { - qWarning() << "environment set multiple times " << QString::fromStdString(*it) - << QString::fromStdString(env); + LogW("environment set multiple times {} {}", *it, env); *it = env; } else { dstEnv.emplace_back(env); @@ -125,7 +126,7 @@ Container::Container(ocppi::runtime::config::types::Config cfg, , bundleDir(std::move(bundleDir)) , cli(cli) { - Q_ASSERT(cfg.process.has_value()); + assert(cfg.process.has_value()); } utils::error::Result Container::run(const ocppi::runtime::config::types::Process &process, @@ -191,14 +192,10 @@ utils::error::Result Container::run(const ocppi::runtime::config::types::P this->cfg.process->args.value_or(std::vector{ "echo", "noting to run" }); auto entrypoint = bundleDir / "entrypoint.sh"; - { - std::ofstream ofs(entrypoint); - Q_ASSERT(ofs.is_open()); - if (!ofs.is_open()) { - return LINGLONG_ERR("create font config in bundle directory"); - } - - ofs << utils::BashCommandHelper::generateEntrypointScript(originalArgs); + auto res = utils::writeFile(entrypoint, + utils::BashCommandHelper::generateEntrypointScript(originalArgs)); + if (!res) { + return LINGLONG_ERR(fmt::format("failed to write to {}", entrypoint), res); } std::filesystem::permissions(entrypoint, std::filesystem::perms::owner_all, ec); @@ -217,24 +214,18 @@ utils::error::Result Container::run(const ocppi::runtime::config::types::P auto cmd = utils::BashCommandHelper::generateExecCommand(entrypointPath); this->cfg.process->args = cmd; - - { - std::ofstream ofs(bundleDir / "config.json"); - Q_ASSERT(ofs.is_open()); - if (!ofs.is_open()) { - return LINGLONG_ERR("create config.json in bundle directory"); - } - - ofs << nlohmann::json(this->cfg); - ofs.close(); + res = utils::writeFile(bundleDir / "config.json", nlohmann::json(this->cfg).dump()); + if (!res) { + return LINGLONG_ERR("failed to write to config.json", res); } + LogD("run container with bundle {}", bundleDir); // 禁用crun自己创建cgroup,便于AM识别和管理玲珑应用 opt.GlobalOption::extra.emplace_back("--cgroup-manager=disabled"); auto result = this->cli.run(this->id, bundleDir, opt); if (!result) { - return LINGLONG_ERR("cli run", result); + return LINGLONG_ERR("cli run", result.error()); } return LINGLONG_OK; diff --git a/libs/linglong/src/linglong/runtime/container_builder.cpp b/libs/linglong/src/linglong/runtime/container_builder.cpp index a6f00ae61..a08766910 100644 --- a/libs/linglong/src/linglong/runtime/container_builder.cpp +++ b/libs/linglong/src/linglong/runtime/container_builder.cpp @@ -7,6 +7,7 @@ #include "linglong/runtime/container_builder.h" #include "linglong/common/dir.h" +#include "linglong/utils/log/log.h" namespace linglong::runtime { @@ -22,14 +23,12 @@ utils::error::Result makeBundleDir(const std::string &con if (std::filesystem::exists(bundle, ec)) { std::filesystem::remove_all(bundle, ec); if (ec) { - qWarning() << QString("failed to remove bundle directory %1: %2") - .arg(bundle.c_str(), ec.message().c_str()); + LogW("failed to remove bundle directory {}: {}", bundle.c_str(), ec.message()); } } if (!std::filesystem::create_directories(bundle, ec) && ec) { - return LINGLONG_ERR(QString("failed to create bundle directory %1: %2") - .arg(bundle.c_str(), ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to create bundle directory {}", bundle), ec); } return bundle; diff --git a/libs/linglong/src/linglong/runtime/container_builder.h b/libs/linglong/src/linglong/runtime/container_builder.h index caa9be9cf..c3a30ec62 100644 --- a/libs/linglong/src/linglong/runtime/container_builder.h +++ b/libs/linglong/src/linglong/runtime/container_builder.h @@ -14,6 +14,7 @@ #include "ocppi/cli/CLI.hpp" #include +#include namespace linglong::runtime { diff --git a/libs/linglong/src/linglong/runtime/run_context.cpp b/libs/linglong/src/linglong/runtime/run_context.cpp index 983d1847a..358182b31 100644 --- a/libs/linglong/src/linglong/runtime/run_context.cpp +++ b/libs/linglong/src/linglong/runtime/run_context.cpp @@ -126,7 +126,7 @@ utils::error::Result RunContext::resolve(const linglong::package::Referenc } else if (info.kind == "runtime") { runtimeLayer = std::move(layer).value(); } else { - return LINGLONG_ERR("kind " + QString::fromStdString(info.kind) + " is not runnable"); + return LINGLONG_ERR(fmt::format("kind {} is not runnable", info.kind)); } // base layer must be resolved for all kinds @@ -218,8 +218,7 @@ utils::error::Result RunContext::resolve(const api::types::v1::BuilderProj } else if (target.package.kind == "runtime") { runtimeOutput = buildOutput; } else { - return LINGLONG_ERR("can't resolve run context from package kind " - + QString::fromStdString(target.package.kind)); + return LINGLONG_ERR("can't resolve run context from package kind " + target.package.kind); } auto baseFuzzyRef = package::FuzzyReference::parse(target.base); @@ -325,7 +324,7 @@ utils::error::Result RunContext::resolveLayer(bool depsBinaryOnly, for (auto &ext : extensionLayers) { if (!ext.resolveLayer()) { - qWarning() << "ignore failed extension layer"; + LogW("ignore failed extension layer"); continue; } @@ -575,7 +574,7 @@ utils::error::Result RunContext::fillContextCfg( auto bundleDir = runtime::makeBundleDir(containerID, bundleSuffix); if (!bundleDir) { - return LINGLONG_ERR("failed to get bundle dir of " + QString::fromStdString(containerID)); + return LINGLONG_ERR("failed to get bundle dir of " + containerID); } bundle = *bundleDir; builder.setBundlePath(bundle); diff --git a/libs/linglong/src/linglong/runtime/wayland_security_ctx.cpp b/libs/linglong/src/linglong/runtime/wayland_security_ctx.cpp index e2f33585a..282cd61d6 100644 --- a/libs/linglong/src/linglong/runtime/wayland_security_ctx.cpp +++ b/libs/linglong/src/linglong/runtime/wayland_security_ctx.cpp @@ -15,6 +15,7 @@ #include #include +#include namespace linglong::runtime { diff --git a/libs/linglong/tests/ll-tests/src/linglong/builder/linglong_builder_test.cpp b/libs/linglong/tests/ll-tests/src/linglong/builder/linglong_builder_test.cpp index 0c22a554d..ed7e6c2d3 100644 --- a/libs/linglong/tests/ll-tests/src/linglong/builder/linglong_builder_test.cpp +++ b/libs/linglong/tests/ll-tests/src/linglong/builder/linglong_builder_test.cpp @@ -7,7 +7,6 @@ #include "../mocks/linglong_builder_mock.h" #include "linglong/builder/linglong_builder.h" #include "linglong/utils/error/error.h" -#include "linglong/utils/global/initialize.h" #include #include diff --git a/libs/linglong/tests/ll-tests/src/linglong/repo/ostree_repo_test.cpp b/libs/linglong/tests/ll-tests/src/linglong/repo/ostree_repo_test.cpp index 2b1fe2299..14a232e13 100644 --- a/libs/linglong/tests/ll-tests/src/linglong/repo/ostree_repo_test.cpp +++ b/libs/linglong/tests/ll-tests/src/linglong/repo/ostree_repo_test.cpp @@ -13,7 +13,6 @@ #include "linglong/repo/client_factory.h" #include "linglong/repo/ostree_repo.h" #include "linglong/utils/error/error.h" -#include "linglong/utils/global/initialize.h" #include #include diff --git a/libs/linglong/tests/ll-tests/src/linglong/utils/command_test.cpp b/libs/linglong/tests/ll-tests/src/linglong/utils/command_test.cpp deleted file mode 100644 index 16363540b..000000000 --- a/libs/linglong/tests/ll-tests/src/linglong/utils/command_test.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: LGPL-3.0-or-later - -#include - -#include "linglong/utils/command/cmd.h" -#include "linglong/utils/error/error.h" - -TEST(command, Exec) -{ - auto ret = linglong::utils::command::Cmd("echo").exec({ "-n", "hello" }); - EXPECT_TRUE(ret); - EXPECT_EQ(ret->length(), 5); - EXPECT_EQ(ret->toStdString(), "hello"); - auto ret2 = linglong::utils::command::Cmd("id").exec({ "-u" }); - EXPECT_TRUE(ret2.has_value()); - - auto userId = ret2->toStdString(); - userId.erase(std::remove(userId.begin(), userId.end(), '\n'), userId.end()); - EXPECT_EQ(userId, std::to_string(getuid())); - - // 测试command不存在时 - auto ret3 = linglong::utils::command::Cmd("nonexistent").exec(); - EXPECT_FALSE(ret3.has_value()); - - // 测试exec出错时 - auto ret4 = linglong::utils::command::Cmd("ls").exec({ "nonexistent" }); - EXPECT_FALSE(ret4.has_value()); -} - -TEST(command, commandExists) -{ - auto ret = linglong::utils::command::Cmd("ls").exists(); - EXPECT_TRUE(ret) << "ls command should exist"; - ret = linglong::utils::command::Cmd("nonexistent").exists(); - EXPECT_FALSE(ret) << "nonexistent should not exist"; -} - -TEST(command, setEnv) -{ - linglong::utils::command::Cmd cmd("bash"); - // test set - cmd.setEnv("LINGLONG_TEST_SETENV", "OK"); - auto existsRef = cmd.exists(); - EXPECT_TRUE(existsRef); - // test unset - cmd.setEnv("PATH", ""); - auto ret = cmd.exec({ "-c", "export" }); - EXPECT_TRUE(ret.has_value()) << ret.error().message(); - auto retStr = *ret; - EXPECT_TRUE(retStr.contains("declare -x LINGLONG_TEST_SETENV=")) << retStr.toStdString(); - EXPECT_FALSE(retStr.contains("declare -x PATH=\"")) << retStr.toStdString(); -} diff --git a/libs/linglong/tests/ll-tests/src/linglong/utils/error/error_test.cpp b/libs/linglong/tests/ll-tests/src/linglong/utils/error/error_test.cpp index c3688e6aa..5de70007d 100644 --- a/libs/linglong/tests/ll-tests/src/linglong/utils/error/error_test.cpp +++ b/libs/linglong/tests/ll-tests/src/linglong/utils/error/error_test.cpp @@ -121,41 +121,6 @@ TEST(Error, WarpStdErrorCode) ASSERT_TRUE(strings::contains(msg, se.what())) << msg; } -TEST(Error, WarpQtFile) -{ - EnvironmentVariableGuard guard("LINYAPS_BACKTRACE", "1"); - auto res = []() -> Result { - LINGLONG_TRACE("test LINGLONG_ERR"); - QFile file("/not_exists_file"); - if (!file.open(QIODevice::ReadOnly)) { - return LINGLONG_ERR("open file failed", file); - } - return LINGLONG_OK; - }(); - ASSERT_FALSE(res.has_value()); - auto msg = res.error().message(); - ASSERT_TRUE(strings::contains(msg, "test LINGLONG_ERR")) << msg; - ASSERT_TRUE(strings::contains(msg, "open file failed")) << msg; - ASSERT_TRUE(strings::contains(msg, "No such file or directory")) << msg; -} - -TEST(Error, WarpGError) -{ - EnvironmentVariableGuard guard("LINYAPS_BACKTRACE", "1"); - auto res = []() -> Result { - LINGLONG_TRACE("test LINGLONG_ERR with GError"); - g_autoptr(GError) gErr = - g_error_new_literal(G_FILE_ERROR, G_FILE_ERROR_FAILED, "GError test"); - return LINGLONG_ERR("GLib operation failed", gErr); - }(); - - ASSERT_FALSE(res.has_value()); - auto msg = res.error().message(); - ASSERT_TRUE(strings::contains(msg, "test LINGLONG_ERR with GError")) << msg; - ASSERT_TRUE(strings::contains(msg, "GLib operation failed")) << msg; - ASSERT_TRUE(strings::contains(msg, "GError test")) << msg; -} - TEST(Error, WarpSystemError) { EnvironmentVariableGuard guard("LINYAPS_BACKTRACE", "1"); @@ -270,22 +235,6 @@ TEST(Error, WarpErrorWithCustomCode) ASSERT_EQ(res.error().code(), 12345); } -TEST(Error, WarpQStringMessage) -{ - EnvironmentVariableGuard guard("LINYAPS_BACKTRACE", "1"); - auto res = []() -> Result { - LINGLONG_TRACE("test LINGLONG_ERR with QString message"); - QString errorMsg = QString("Error occurred at line %1").arg(__LINE__); - return LINGLONG_ERR(errorMsg, ErrorCode::Unknown); - }(); - - ASSERT_FALSE(res.has_value()); - auto msg = res.error().message(); - ASSERT_TRUE(strings::contains(msg, "test LINGLONG_ERR with QString message")) << msg; - ASSERT_TRUE(strings::contains(msg, "Error occurred at line")) << msg; - ASSERT_EQ(res.error().code(), static_cast(ErrorCode::Unknown)); -} - TEST(Error, WarpStdStringMessage) { EnvironmentVariableGuard guard("LINYAPS_BACKTRACE", "1"); @@ -302,22 +251,6 @@ TEST(Error, WarpStdStringMessage) ASSERT_EQ(res.error().code(), static_cast(ErrorCode::AppNotFoundFromRemote)); } -TEST(Error, WarpEmptyFile) -{ - EnvironmentVariableGuard guard("LINYAPS_BACKTRACE", "1"); - auto res = []() -> Result { - LINGLONG_TRACE("test LINGLONG_ERR with empty QFile"); - QFile emptyFile; - return LINGLONG_ERR(emptyFile); - }(); - - ASSERT_FALSE(res.has_value()); - auto msg = res.error().message(); - ASSERT_TRUE(strings::contains(msg, "test LINGLONG_ERR with empty QFile")) << msg; - // 空QFile会有特定的错误信息 - ASSERT_TRUE(strings::contains(msg, "Unknown error")) << msg; -} - TEST(Error, SuccessCase) { EnvironmentVariableGuard guard("LINYAPS_BACKTRACE", "1"); diff --git a/libs/linglong/tests/ll-tests/src/linglong/utils/file_test.cpp b/libs/linglong/tests/ll-tests/src/linglong/utils/file_test.cpp index 68df92ba1..5b732d7e6 100644 --- a/libs/linglong/tests/ll-tests/src/linglong/utils/file_test.cpp +++ b/libs/linglong/tests/ll-tests/src/linglong/utils/file_test.cpp @@ -6,7 +6,7 @@ #include "linglong/utils/file.h" -#include +#include #include #include #include @@ -351,7 +351,7 @@ TEST_F(FileTest, WriteFile) // Test writing empty content fs::path empty_file = dest_dir / "empty.txt"; - result = linglong::utils::writeFile(empty_file.string(), "\0"); + result = linglong::utils::writeFile(empty_file.string(), ""); ASSERT_TRUE(result.has_value()) << result.error().message(); EXPECT_TRUE(fs::exists(empty_file)); diff --git a/libs/linglong/tests/ll-tests/src/main.cpp b/libs/linglong/tests/ll-tests/src/main.cpp index 7b624870d..7c90cbbe0 100644 --- a/libs/linglong/tests/ll-tests/src/main.cpp +++ b/libs/linglong/tests/ll-tests/src/main.cpp @@ -6,15 +6,13 @@ #include -#include "linglong/utils/global/initialize.h" +#include "linglong/common/global/initialize.h" #include int main(int argc, char **argv) { - qputenv("QT_FORCE_STDERR_LOGGING", QByteArray("1")); - linglong::utils::global::installMessageHandler(); - linglong::utils::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Console); + linglong::common::global::initLinyapsLogSystem(linglong::utils::log::LogBackend::Console); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/libs/utils/CMakeLists.txt b/libs/utils/CMakeLists.txt index 31cf82a8f..ddcd7e1b6 100644 --- a/libs/utils/CMakeLists.txt +++ b/libs/utils/CMakeLists.txt @@ -25,8 +25,6 @@ pfl_add_library( src/linglong/utils/finally/finally.cpp src/linglong/utils/finally/finally.h src/linglong/utils/gettext.h - src/linglong/utils/global/initialize.cpp - src/linglong/utils/global/initialize.h src/linglong/utils/hooks.cpp src/linglong/utils/hooks.h src/linglong/utils/log/formatter.cpp @@ -54,14 +52,11 @@ pfl_add_library( cxx_std_17 LINK_LIBRARIES PUBLIC - Qt${QT_VERSION_MAJOR}::Core - Qt${QT_VERSION_MAJOR}::DBus - PkgConfig::glib2 + PkgConfig::cap PkgConfig::systemd fmt::fmt - tl::expected - ytj::ytj - linglong::ocppi linglong::api linglong::common - PkgConfig::cap) + linglong::ocppi + tl::expected + ytj::ytj) diff --git a/libs/utils/src/linglong/utils/error/error.h b/libs/utils/src/linglong/utils/error/error.h index 47404e207..2043f0080 100644 --- a/libs/utils/src/linglong/utils/error/error.h +++ b/libs/utils/src/linglong/utils/error/error.h @@ -8,12 +8,9 @@ #include "linglong/utils/error/details/error_impl.h" -#include #include -#include -#include - +#include #include #include #include @@ -73,60 +70,6 @@ class Error [[nodiscard]] auto message() const { return pImpl->message(); } - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const QString &msg, - const ErrorCode &code) -> Error - { - return Error(std::make_unique(file, - line, - static_cast(code), - trace_msg, - msg.toStdString(), - nullptr)); - } - - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const std::string &msg, - const ErrorCode &code) -> Error - { - return Error(std::make_unique(file, - line, - static_cast(code), - trace_msg, - msg, - nullptr)); - } - - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const char *msg, - const ErrorCode &code) -> Error - { - return Error(std::make_unique(file, - line, - static_cast(code), - trace_msg, - msg, - nullptr)); - } - - static auto - Err(const char *file, int line, const std::string &trace_msg, const QString &msg, int code = -1) - -> Error - { - return Error(std::make_unique(file, - line, - code, - trace_msg, - msg.toStdString(), - nullptr)); - } - static auto Err(const char *file, int line, const std::string &trace_msg, @@ -137,39 +80,13 @@ class Error std::make_unique(file, line, code, trace_msg, msg, nullptr)); } - static auto - Err(const char *file, int line, const std::string &trace_msg, const char *msg, int code = -1) - -> Error - { - return Error( - std::make_unique(file, line, code, trace_msg, msg, nullptr)); - } - static auto Err(const char *file, int line, const std::string &trace_msg, - const QString &msg, - const QFile &qfile) -> Error - { - return Error(std::make_unique(file, - line, - qfile.error(), - trace_msg, - msg.toStdString() + ": " - + qfile.errorString().toStdString(), - nullptr)); - } - - static auto Err(const char *file, int line, const std::string &trace_msg, const QFile &qfile) - -> Error + const std::string &msg, + const ErrorCode &code) -> Error { - return Error(std::make_unique(file, - line, - qfile.error(), - trace_msg, - qfile.fileName().toStdString() + ": " - + qfile.errorString().toStdString(), - nullptr)); + return Err(file, line, trace_msg, msg, static_cast(code)); } static auto Err(const char *file, @@ -187,18 +104,17 @@ class Error what = "unknown"; } - return Error( - std::make_unique(file, line, code, trace_msg, what, nullptr)); + return Err(file, line, trace_msg, what, code); } static auto Err(const char *file, int line, const std::string &trace_msg, - const QString &msg, + const std::string &msg, std::exception_ptr err, int code = -1) -> Error { - std::string what = msg.toStdString() + ": "; + std::string what = msg + ": "; try { std::rethrow_exception(std::move(err)); } catch (const std::exception &e) { @@ -207,60 +123,23 @@ class Error what += "unknown"; } - return Error( - std::make_unique(file, line, code, trace_msg, what, nullptr)); + return Err(file, line, trace_msg, what, code); } static auto Err(const char *file, int line, const std::string &trace_msg, const std::exception &e) -> Error { - return Error( - std::make_unique(file, line, -1, trace_msg, e.what(), nullptr)); - } - - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const QString &msg, - const std::exception &e, - int code = -1) -> Error - { - std::string what = msg.toStdString() + ": " + e.what(); - - return Error( - std::make_unique(file, line, code, trace_msg, what, nullptr)); + return Err(file, line, trace_msg, e.what()); } static auto Err(const char *file, int line, const std::string &trace_msg, - const QString &msg, - GError const *const e) -> Error - { - QString new_msg = msg; - if (e != nullptr) { - new_msg.append( - QString{ " error code:%1, message:%2" }.arg(QString::number(e->code), e->message)); - } - return Err(file, line, trace_msg, new_msg); - } - - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const char *msg, - const std::system_error &e) -> Error - { - return Err(file, line, trace_msg, msg, e, e.code().value()); - } - - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const QString &msg, - const std::system_error &e) -> Error + const std::string &msg, + const std::exception &e) -> Error { - return Err(file, line, trace_msg, msg, e, e.code().value()); + std::string what = msg + ": " + e.what(); + return Err(file, line, trace_msg, what); } static auto Err(const char *file, @@ -269,24 +148,8 @@ class Error const std::string &msg, const std::system_error &e) -> Error { - return Err(file, line, trace_msg, msg.c_str(), e, e.code().value()); - } - - template - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const QString &msg, - tl::expected &&cause) -> Error - { - Q_ASSERT(!cause.has_value()); - - return Error(std::make_unique(file, - line, - cause.error().code(), - trace_msg, - msg.toStdString(), - std::move(cause.error().pImpl))); + std::string what = msg + ": " + e.what(); + return Err(file, line, trace_msg, what, e.code().value()); } template @@ -296,7 +159,7 @@ class Error const std::string &msg, tl::expected &&cause) -> Error { - Q_ASSERT(!cause.has_value()); + assert(!cause.has_value()); return Error(std::make_unique(file, line, @@ -310,26 +173,9 @@ class Error static auto Err(const char *file, int line, const std::string &trace_msg, - const char *msg, tl::expected &&cause) -> Error { - Q_ASSERT(!cause.has_value()); - - return Error(std::make_unique(file, - line, - cause.error().code(), - trace_msg, - msg, - std::move(cause.error().pImpl))); - } - - template - static auto Err(const char *file, - int line, - const std::string &trace_msg, - tl::expected &&cause) -> Error - { - Q_ASSERT(!cause.has_value()); + assert(!cause.has_value()); return Error(std::make_unique(file, line, @@ -372,23 +218,11 @@ class Error tl::expected &&cause, int code = -1) -> Error { - Q_ASSERT(!cause.has_value()); + assert(!cause.has_value()); return Err(file, line, trace_msg, cause.error(), code); } - template - static auto Err(const char *file, - int line, - const std::string &trace_msg, - const QString &msg, - tl::expected &&cause) -> Error - { - Q_ASSERT(!cause.has_value()); - - return Err(file, line, trace_msg, msg, cause.error()); - } - private: explicit Error(std::unique_ptr pImpl) : pImpl(std::move(pImpl)) @@ -408,14 +242,11 @@ using Result = tl::expected; // Use this macro to create new error or wrap an existing error // LINGLONG_ERR(message, code =-1) -// LINGLONG_ERR(message, /* const QFile& */) -// LINGLONG_ERR(/* const QFile& */) // LINGLONG_ERR(message, /* std::exception_ptr */, code=-1) // LINGLONG_ERR(/* std::exception_ptr */) // LINGLONG_ERR(message, /* const std::exception & */, code=-1) // LINGLONG_ERR(/* const std::exception & */) // LINGLONG_ERR(message, /* const std::system_exception & */) -// LINGLONG_ERR(message, /* GError* */) // LINGLONG_ERR(message, /* Result&& */) // LINGLONG_ERR(/* Result&& */) // LINGLONG_ERR(message, /* tl::expected&& */, code=-1) @@ -428,22 +259,22 @@ using Result = tl::expected; // std::move is used for Result #define LINGLONG_ERR_1(_1) /*NOLINT*/ \ - tl::unexpected(::linglong::utils::error::Error::Err(QT_MESSAGELOG_FILE, \ - QT_MESSAGELOG_LINE, \ + tl::unexpected(::linglong::utils::error::Error::Err(__FILE__, \ + __LINE__, \ _linglong_trace_message, \ std::move((_1)) /*NOLINT*/)) // std::move is used for Result #define LINGLONG_ERR_2(_1, _2) /*NOLINT*/ \ - tl::unexpected(::linglong::utils::error::Error::Err(QT_MESSAGELOG_FILE, \ - QT_MESSAGELOG_LINE, \ + tl::unexpected(::linglong::utils::error::Error::Err(__FILE__, \ + __LINE__, \ _linglong_trace_message, \ (_1), \ std::move((_2)) /*NOLINT*/)) #define LINGLONG_ERR_3(_1, _2, _3) /*NOLINT*/ \ - tl::unexpected(::linglong::utils::error::Error::Err(QT_MESSAGELOG_FILE, \ - QT_MESSAGELOG_LINE, \ + tl::unexpected(::linglong::utils::error::Error::Err(__FILE__, \ + __LINE__, \ _linglong_trace_message, \ (_1), \ (_2), \ @@ -454,24 +285,3 @@ using Result = tl::expected; } #define LINGLONG_ERRV(...) /*NOLINT*/ LINGLONG_ERR(__VA_ARGS__).value() - -// https://github.com/AD-Vega/qarv/issues/22#issuecomment-1012011346 -#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) -namespace Qt { -static auto endl = ::endl; -} -#endif - -inline QDebug operator<<(QDebug debug, const linglong::utils::error::Error &err) -{ - debug.noquote().nospace() << "[code " << err.code() << " ] message:" << Qt::endl - << "\t" - << QString::fromStdString(err.message()).replace("\n", "\n\t"); - return debug; -} - -inline QDebug operator<<(QDebug debug, const std::string &str) -{ - debug.noquote().nospace() << QString::fromStdString(str); - return debug; -} diff --git a/libs/utils/src/linglong/utils/file.cpp b/libs/utils/src/linglong/utils/file.cpp index 5d95641d8..c2fd3648a 100644 --- a/libs/utils/src/linglong/utils/file.cpp +++ b/libs/utils/src/linglong/utils/file.cpp @@ -103,8 +103,7 @@ calculateDirectorySize(const std::filesystem::path &dir) noexcept auto fsIter = std::filesystem::recursive_directory_iterator{ dir, ec }; if (ec) { - return LINGLONG_ERR( - QString{ "failed to calculate directory size: %1" }.arg(ec.message().c_str())); + return LINGLONG_ERR("failed to calculate directory size", ec); } for (const auto &entry : fsIter) { @@ -121,9 +120,7 @@ calculateDirectorySize(const std::filesystem::path &dir) noexcept continue; } if (ec) { - return LINGLONG_ERR( - QString{ "failed to get entry type of %1: %2" }.arg(entry.path().c_str(), - ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to get entry type of {}", entry.path()), ec); } if (entry.is_directory(ec)) { @@ -137,9 +134,7 @@ calculateDirectorySize(const std::filesystem::path &dir) noexcept continue; } if (ec) { - return LINGLONG_ERR( - QString{ "failed to get entry type of %1: %2" }.arg(entry.path().c_str(), - ec.message().c_str())); + return LINGLONG_ERR(fmt::format("failed to get entry type of {}", entry.path()), ec); } size += entry.file_size(); diff --git a/libs/utils/src/linglong/utils/hooks.cpp b/libs/utils/src/linglong/utils/hooks.cpp index 39aadfa3f..1a66dae04 100644 --- a/libs/utils/src/linglong/utils/hooks.cpp +++ b/libs/utils/src/linglong/utils/hooks.cpp @@ -73,17 +73,17 @@ utils::error::Result executeHookCommands( if (!WIFEXITED(ret)) { int signalNum = WTERMSIG(ret); - return LINGLONG_ERR(QString("Command '%1' terminated by signal %2 (%3).") - .arg(QString::fromStdString(fullCommand)) - .arg(signalNum) - .arg(strsignal(signalNum))); + return LINGLONG_ERR(fmt::format("Command '{}' terminated by signal {} ({}).", + fullCommand, + signalNum, + strsignal(signalNum))); } int exitStatus = WEXITSTATUS(ret); if (exitStatus != 0) { - return LINGLONG_ERR(QString("Command '%1' exited with non-zero status: %2.") - .arg(QString::fromStdString(fullCommand)) - .arg(exitStatus)); + return LINGLONG_ERR(fmt::format("Command '{}' exited with non-zero status: {}.", + fullCommand, + exitStatus)); } } return LINGLONG_OK; @@ -97,8 +97,8 @@ utils::error::Result InstallHookManager::parseInstallHooks() for (const auto &entry : std::filesystem::directory_iterator(LINGLONG_INSTALL_HOOKS_DIR, ec)) { if (ec) { return LINGLONG_ERR( - QString("Failed to iterate directory %1: %2") - .arg(LINGLONG_INSTALL_HOOKS_DIR, QString::fromStdString(ec.message()))); + fmt::format("Failed to iterate directory {}", LINGLONG_INSTALL_HOOKS_DIR), + ec); } if (!std::filesystem::is_regular_file(entry.status(ec))) { @@ -110,7 +110,7 @@ utils::error::Result InstallHookManager::parseInstallHooks() std::ifstream file(entry.path()); if (!file.is_open()) { - return LINGLONG_ERR(QString{ "Couldn't open file: %1" }.arg(entry.path().c_str())); + return LINGLONG_ERR(fmt::format("Couldn't open file: {}", entry.path())); } std::string line; diff --git a/libs/utils/src/linglong/utils/serialize/yaml.h b/libs/utils/src/linglong/utils/serialize/yaml.h index e9f01a535..30538bcd9 100644 --- a/libs/utils/src/linglong/utils/serialize/yaml.h +++ b/libs/utils/src/linglong/utils/serialize/yaml.h @@ -43,7 +43,7 @@ error::Result LoadYAMLFile(const std::filesystem::path &filename) noexcept std::ifstream file_stream(filename); if (!file_stream.is_open()) { - return LINGLONG_ERR("Failed to open file: " + QString::fromStdString(filename)); + return LINGLONG_ERR("Failed to open file: " + filename.string()); } return LoadYAML(file_stream);