File: setopt.cpp

package info (click to toggle)
dnf5 5.4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 17,960 kB
  • sloc: cpp: 94,312; python: 3,370; xml: 1,073; ruby: 600; sql: 250; ansic: 232; sh: 104; perl: 62; makefile: 30
file content (282 lines) | stat: -rw-r--r-- 11,037 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright Contributors to the DNF5 project.
// Copyright Contributors to the libdnf project.
// SPDX-License-Identifier: GPL-2.0-or-later
//
// This file is part of libdnf: https://github.com/rpm-software-management/libdnf/
//
// Libdnf is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Libdnf is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libdnf.  If not, see <https://www.gnu.org/licenses/>.

#include "setopt.hpp"

#include "shared.hpp"

#include <libdnf5/common/sack/match_string.hpp>
#include <libdnf5/conf/const.hpp>
#include <libdnf5/utils/bgettext/bgettext-mark-domain.h>

#include <filesystem>

namespace dnf5 {

using namespace libdnf5;

namespace {

constexpr std::string_view REPOS_OVERRIDE_CFG_HEADER =
    "# Generated by dnf5 config-manager.\n# Do not modify this file manually, use dnf5 config-manager instead.\n";


void modify_config(
    ConfigParser & parser, const std::string & section_id, const std::map<std::string, std::string> & opts) {
    if (!parser.has_section(section_id)) {
        parser.add_section(section_id);
    }
    for (const auto & [key, value] : opts) {
        parser.set_value(section_id, key, value, "");
    }
}


std::set<std::string> filter_repo_ids(const std::string & pattern, const std::set<std::string> & repo_ids) {
    std::set<std::string> matched_repo_ids;
    for (const auto & repo_id : repo_ids) {
        if (sack::match_string(repo_id, sack::QueryCmp::GLOB, pattern)) {
            matched_repo_ids.insert(repo_id);
        }
    }
    return matched_repo_ids;
}

}  // namespace


void ConfigManagerSetOptCommand::set_argument_parser() {
    auto & ctx = get_context();
    auto & parser = ctx.get_argument_parser();

    auto & cmd = *get_argument_parser_command();
    cmd.set_description("Set configuration and repositories options");

    auto opts_vals =
        parser.add_new_positional_arg("optvals", cli::ArgumentParser::PositionalArg::AT_LEAST_ONE, nullptr, nullptr);
    opts_vals->set_description("List of options with values. Format: \"[REPO_ID.]option=value\"");
    opts_vals->set_parse_hook_func([this](
                                       [[maybe_unused]] cli::ArgumentParser::PositionalArg * arg,
                                       int argc,
                                       const char * const argv[]) {
        for (int i = 0; i < argc; ++i) {
            auto value = argv[i];
            const auto * const val = strchr(value + 1, '=');
            if (!val) {
                throw cli::ArgumentParserError(
                    M_("{}: Badly formatted argument value \"{}\""), std::string{"optval"}, std::string{value});
            }
            std::string key{value, val};
            std::string key_value{val + 1};
            auto dot_pos = key.rfind('.');
            if (dot_pos != std::string::npos) {
                if (dot_pos == key.size() - 1) {
                    throw cli::ArgumentParserError(
                        M_("{}: Badly formatted argument value: Last key character cannot be '.': {}"),
                        std::string{"optval"},
                        std::string{value});
                }

                // Save the repository option for later processing (solving glob pattern, writing to file).
                auto repo_id = key.substr(0, dot_pos);
                if (repo_id.empty()) {
                    throw cli::ArgumentParserError(
                        M_("{}: Empty repository id is not allowed: {}"), std::string{"optval"}, std::string{value});
                }
                auto repo_key = key.substr(dot_pos + 1);

                // Test if the repository option is known and can be set.
                try {
                    tmp_repo_conf.opt_binds().at(repo_key).new_string(Option::Priority::COMMANDLINE, key_value);
                } catch (const Error & ex) {
                    throw ConfigManagerError(
                        M_("Cannot set repository option \"{}\": {}"), std::string{value}, std::string{ex.what()});
                }

                const auto [it, inserted] = in_repos_setopts[repo_id].insert({repo_key, key_value});
                if (!inserted) {
                    if (it->second != key_value) {
                        throw ConfigManagerError(
                            M_("Sets the \"{}\" option of the repository \"{}\" again with a different value: \"{}\" "
                               "!= \"{}\""),
                            repo_key,
                            repo_id,
                            it->second,
                            key_value);
                    }
                }
            } else {
                // Test if the global option is known and can be set.
                try {
                    tmp_config.opt_binds().at(key).new_string(Option::Priority::COMMANDLINE, key_value);
                } catch (const Error & ex) {
                    throw ConfigManagerError(
                        M_("Cannot set option: \"{}\": {}"), std::string{value}, std::string(ex.what()));
                }

                // Save the global option for later writing to a file.
                const auto [it, inserted] = main_setopts.insert({key, key_value});
                if (!inserted) {
                    if (it->second != key_value) {
                        throw ConfigManagerError(
                            M_("Sets the \"{}\" option again with a different value: \"{}\" != \"{}\""),
                            key,
                            it->second,
                            key_value);
                    }
                }
            }
        }
        return true;
    });
    cmd.register_positional_arg(opts_vals);

    auto create_missing_dirs_opt = parser.add_new_named_arg("create-missing-dir");
    create_missing_dirs_opt->set_long_name("create-missing-dir");
    create_missing_dirs_opt->set_description("Allow to create missing directories");
    create_missing_dirs_opt->set_has_value(false);
    create_missing_dirs_opt->set_parse_hook_func([this](cli::ArgumentParser::NamedArg *, const char *, const char *) {
        create_missing_dirs = true;
        return true;
    });
    cmd.register_named_arg(create_missing_dirs_opt);
}


void ConfigManagerSetOptCommand::configure() {
    auto & ctx = get_context();
    const auto & config = ctx.get_base().get_config();

    auto repo_ids = load_existing_repo_ids();
    for (auto & [in_repo_id, repo_setopts] : in_repos_setopts) {
        auto filtered_repo_ids = filter_repo_ids(in_repo_id, repo_ids);
        if (filtered_repo_ids.empty()) {
            throw ConfigManagerError(M_("No matching repository to modify: {}"), in_repo_id);
        }
        for (const auto & repo_id : filtered_repo_ids) {
            for (const auto & [key, value] : repo_setopts) {
                // Save the repository option for later writing to a file.
                const auto [it, inserted] = matching_repos_setopts[repo_id].insert({key, value});
                if (!inserted) {
                    if (it->second != value) {
                        throw ConfigManagerError(
                            M_("Sets the \"{}\" option of the repository \"{}\" again with a different value: \"{}\" "
                               "!= \"{}\""),
                            key,
                            repo_id,
                            it->second,
                            value);
                    }
                }
            }
        }
    }

    // Write new and modify existing options in the main configuration file.
    if (!main_setopts.empty()) {
        ConfigParser parser;

        const auto & cfg_filepath = get_config_file_path(config);
        resolve_missing_dir(cfg_filepath.parent_path(), create_missing_dirs);

        const bool exists = std::filesystem::exists(cfg_filepath);
        if (exists) {
            parser.read(cfg_filepath);
        }

        modify_config(parser, "main", main_setopts);
        parser.write(cfg_filepath, false);
        if (!exists) {
            set_file_permissions(cfg_filepath);
        }
    }

    // Write new and modify existing options in the repositories overrides configuration file.
    if (!matching_repos_setopts.empty()) {
        ConfigParser parser;

        resolve_missing_dir(get_repos_config_override_dir_path(config), create_missing_dirs);

        auto repos_override_file_path = get_config_manager_repos_override_file_path(config);

        const bool exists = std::filesystem::exists(repos_override_file_path);
        if (exists) {
            parser.read(repos_override_file_path);
        }

        parser.get_header() = REPOS_OVERRIDE_CFG_HEADER;

        for (const auto & [repo_id, repo_opts] : matching_repos_setopts) {
            modify_config(parser, repo_id, repo_opts);
        }

        parser.write(repos_override_file_path, false);
        if (!exists) {
            set_file_permissions(repos_override_file_path);
        }
    }
}


std::set<std::string> ConfigManagerSetOptCommand::load_existing_repo_ids() const {
    auto & ctx = get_context();
    auto & base = ctx.get_base();
    auto logger = base.get_logger();

    std::set<std::string> repo_ids;

    // The repository can also be defined in the main configuration file.
    if (const auto & conf_path = get_config_file_path(base.get_config()); std::filesystem::exists(conf_path)) {
        ConfigParser parser;
        parser.read(conf_path);
        for (const auto & [section, opts] : parser.get_data()) {
            if (section == "main") {
                continue;
            }
            repo_ids.insert(section);
        }
    }

    const auto & repo_dirs = base.get_config().get_reposdir_option().get_value();
    for (const std::filesystem::path dir : repo_dirs) {
        if (std::filesystem::exists(dir)) {
            std::error_code ec;
            std::filesystem::directory_iterator di(dir, ec);
            if (ec) {
                write_warning(
                    *logger, M_("Cannot read repositories from directory \"{}\": {}"), dir.string(), ec.message());
                continue;
            }
            for (auto & dentry : di) {
                const auto & path = dentry.path();
                if (path.extension() == ".repo") {
                    ConfigParser parser;
                    parser.read(path);
                    for (const auto & [repo_id, opts] : parser.get_data()) {
                        repo_ids.insert(repo_id);
                    }
                }
            }
        }
    }

    return repo_ids;
}

}  // namespace dnf5