5. Resolving dependencies and running a transaction

This tutorial is a follow-up to Creating and configuring a session and potentially one of Loading repositories (to have some packages to work with), you can prepend them directly for a functional piece of code.

 1#include <libdnf5/base/goal.hpp>
 2#include <libdnf5/repo/package_downloader.hpp>
 3
 4// Create a goal, which is a class that allows to add items for resolving into
 5// a transaction.
 6libdnf5::Goal goal(base);
 7
 8// Add an RPM package named "one" for installation into the goal.
 9goal.add_rpm_install("one");
10
11// Resolve the goal, create a transaction object.
12//
13// The argument is `allow_erasing`, a flag indicating whether to allow removing
14// packages in the resolved transaction.
15auto transaction = goal.resolve();
16
17// We can iterate over the resolved transaction and inspect the packages.
18std::cout << "Resolved transaction:" << std::endl;
19for (const auto & tspkg : transaction.get_transaction_packages()) {
20    std::cout << tspkg.get_package().get_nevra() << ": " << transaction_item_action_to_string(tspkg.get_action())
21              << std::endl;
22}
23
24// This class demonstrates user-defined callbacks for the url/package downloads.
25//
26// The callbacks are implemented by inheriting from the callbacks base class
27// and overriding its methods.
28//
29// We only override one of the callbacks here, see
30// `libdnf5::repo::DownloadCallbacks` documentation for a complete list.
31class PackageDownloadCallbacks : public libdnf5::repo::DownloadCallbacks {
32private:
33    int mirror_failure(
34        [[maybe_unused]] void * user_cb_data,
35        const char * msg,
36        [[maybe_unused]] const char * url,
37        [[maybe_unused]] const char * metadata) override {
38        std::cout << "Mirror failure: " << msg << std::endl;
39        return 0;
40    }
41};
42
43base.set_download_callbacks(std::make_unique<PackageDownloadCallbacks>());
44
45// Download the packages.
46transaction.download();
47
48// A class for defining the RPM transaction callbacks.
49//
50// Again, only a callback for when an RPM package installation starts, for a
51// complete list of the callbacks see `libdnf5::rpm::TransactionCallbacks`
52// documentation.
53class TransactionCallbacks : public libdnf5::rpm::TransactionCallbacks {
54    void install_start(const libdnf5::rpm::TransactionItem & item, [[maybe_unused]] uint64_t total) override {
55        std::cout << transaction_item_action_to_string(item.get_action()) << " " << item.get_package().get_nevra()
56                  << std::endl;
57    }
58};
59
60transaction.set_callbacks(std::make_unique<TransactionCallbacks>());
61
62// Add transaction metadata to be stored in the history database.
63transaction.set_description("install package one");
64
65// Run the transaction.
66std::cout << std::endl << "Running the transaction:" << std::endl;
67transaction.run();