summaryrefslogtreecommitdiff
path: root/src/other_tools/just_mr/rc.cpp
blob: a7894d53e385c5d7a20a20ce82992b5718081f79 (plain)
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "src/other_tools/just_mr/rc.hpp"

#include "nlohmann/json.hpp"
#include "src/buildtool/build_engine/expression/configuration.hpp"
#include "src/buildtool/build_engine/expression/expression_ptr.hpp"
#include "src/buildtool/file_system/file_system_manager.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/logging/log_sink_file.hpp"
#include "src/buildtool/logging/logger.hpp"
#include "src/other_tools/just_mr/exit_codes.hpp"

namespace {

[[nodiscard]] auto ReadLocation(
    ExpressionPtr const& location,
    std::optional<std::filesystem::path> const& ws_root)
    -> std::optional<std::pair<std::filesystem::path, std::filesystem::path>> {
    if (location.IsNotNull()) {
        auto root = location->Get("root", Expression::none_t{});
        auto path = location->Get("path", Expression::none_t{});
        auto base = location->Get("base", std::string("."));

        if (not path->IsString() or not root->IsString() or
            not kLocationTypes.contains(root->String())) {
            Logger::Log(LogLevel::Error,
                        "Malformed location object: {}",
                        location.ToJson().dump(-1));
            std::exit(kExitConfigError);
        }
        auto root_str = root->String();
        std::filesystem::path root_path{};
        if (root_str == "workspace") {
            if (not ws_root) {
                Logger::Log(LogLevel::Warning,
                            "Not in workspace root, ignoring location {}.",
                            location.ToJson().dump(-1));
                return std::nullopt;
            }
            root_path = *ws_root;
        }
        if (root_str == "home") {
            root_path = StorageConfig::GetUserHome();
        }
        if (root_str == "system") {
            root_path = FileSystemManager::GetCurrentDirectory().root_path();
        }
        return std::make_pair(
            std::filesystem::weakly_canonical(
                std::filesystem::absolute(root_path / path->String())),
            std::filesystem::weakly_canonical(
                std::filesystem::absolute(root_path / base->String())));
    }
    return std::nullopt;
}

[[nodiscard]] auto ReadLocation(
    nlohmann::json const& location,
    std::optional<std::filesystem::path> const& ws_root)
    -> std::optional<std::pair<std::filesystem::path, std::filesystem::path>> {
    if (not location.contains("path") or not location.contains("root")) {
        Logger::Log(LogLevel::Error,
                    "Malformed location object: {}",
                    location.dump(-1));
        std::exit(kExitConfigError);
    }
    auto root = location["root"].get<std::string>();
    auto path = location["path"].get<std::string>();
    auto base = location.contains("base") ? location["base"].get<std::string>()
                                          : std::string(".");

    std::filesystem::path root_path{};
    if (root == "workspace") {
        if (not ws_root) {
            Logger::Log(LogLevel::Warning,
                        "Not in workspace root, ignoring location {}.",
                        location.dump(-1));
            return std::nullopt;
        }
        root_path = *ws_root;
    }
    if (root == "home") {
        root_path = StorageConfig::GetUserHome();
    }
    if (root == "system") {
        root_path = FileSystemManager::GetCurrentDirectory().root_path();
    }
    return std::make_pair(std::filesystem::weakly_canonical(
                              std::filesystem::absolute(root_path / path)),
                          std::filesystem::weakly_canonical(
                              std::filesystem::absolute(root_path / base)));
}

[[nodiscard]] auto ReadOptionalLocationList(
    ExpressionPtr const& location_list,
    std::optional<std::filesystem::path> const& ws_root,
    std::string const& argument_name) -> std::optional<std::filesystem::path> {
    if (location_list->IsNone()) {
        return std::nullopt;
    }
    if (not location_list->IsList()) {
        Logger::Log(LogLevel::Error,
                    "Argument {} has to be a list, but found {}",
                    argument_name,
                    location_list->ToString());
        std::exit(kExitConfigError);
    }
    for (auto const& location : location_list->List()) {
        auto p = ReadLocation(location, ws_root);
        if (p and FileSystemManager::IsFile(p->first)) {
            return p->first;
        }
    }
    return std::nullopt;
}

[[nodiscard]] auto ObtainRCConfig(
    gsl::not_null<CommandLineArguments*> const& clargs) -> Configuration {
    Configuration rc_config{};
    auto rc_path = clargs->common.rc_path;
    // set default if rcpath not given
    if (not clargs->common.norc) {
        if (not rc_path) {
            rc_path = std::filesystem::weakly_canonical(
                std::filesystem::absolute(kDefaultRCPath));
        }
        else {
            if (not FileSystemManager::IsFile(*rc_path)) {
                Logger::Log(LogLevel::Error,
                            "Cannot read RC file {}.",
                            rc_path->string());
                std::exit(kExitConfigError);
            }
        }
        if (FileSystemManager::IsFile(*rc_path)) {
            // json::parse may throw
            try {
                std::ifstream fs(*rc_path);
                auto map = Expression::FromJson(nlohmann::json::parse(fs));
                if (not map->IsMap()) {
                    Logger::Log(
                        LogLevel::Error,
                        "In RC file {}: expected an object but found:\n{}",
                        rc_path->string(),
                        map->ToString());
                    std::exit(kExitConfigError);
                }
                rc_config = Configuration{map};
            } catch (std::exception const& e) {
                Logger::Log(LogLevel::Error,
                            "Parsing RC file {} as JSON failed with error:\n{}",
                            rc_path->string(),
                            e.what());
                std::exit(kExitConfigError);
            }
        }
    }
    return rc_config;
}

}  // namespace

/// \brief Read just-mrrc file and set up various configs. Return the path to
/// the repository config file, if any is provided.
[[nodiscard]] auto ReadJustMRRC(
    gsl::not_null<CommandLineArguments*> const& clargs)
    -> std::optional<std::filesystem::path> {
    Configuration rc_config = ObtainRCConfig(clargs);
    // read local build root; overwritten if user provided it already
    if (not clargs->common.just_mr_paths->root) {
        auto build_root =
            ReadLocation(rc_config["local build root"],
                         clargs->common.just_mr_paths->workspace_root);
        if (build_root) {
            clargs->common.just_mr_paths->root = build_root->first;
        }
    }
    // read checkout locations file; overwritten if user provided it already
    if (not clargs->common.checkout_locations_file) {
        auto checkout =
            ReadLocation(rc_config["checkout locations"],
                         clargs->common.just_mr_paths->workspace_root);
        if (checkout) {
            if (not FileSystemManager::IsFile(checkout->first)) {
                Logger::Log(LogLevel::Error,
                            "Cannot find checkout locations file {}.",
                            checkout->first.string());
                std::exit(kExitConfigError);
            }
            clargs->common.checkout_locations_file = checkout->first;
        }
    }
    // read distdirs; user can append, but does not overwrite
    auto distdirs = rc_config["distdirs"];
    if (distdirs.IsNotNull()) {
        if (not distdirs->IsList()) {
            Logger::Log(LogLevel::Error,
                        "Configuration-file provided distdirs has to be a list "
                        "of strings, but found {}",
                        distdirs->ToString());
            std::exit(kExitConfigError);
        }
        auto const& distdirs_list = distdirs->List();
        for (auto const& l : distdirs_list) {
            auto paths =
                ReadLocation(l, clargs->common.just_mr_paths->workspace_root);
            if (paths) {
                if (FileSystemManager::IsDirectory(paths->first)) {
                    clargs->common.just_mr_paths->distdirs.emplace_back(
                        paths->first);
                }
                else {
                    Logger::Log(LogLevel::Warning,
                                "Ignoring non-existing distdir {}.",
                                paths->first.string());
                }
            }
        }
    }
    // read just path; overwritten if user provided it already
    if (not clargs->common.just_path) {
        auto just = ReadLocation(rc_config["just"],
                                 clargs->common.just_mr_paths->workspace_root);
        if (just) {
            clargs->common.just_path = just->first;
        }
    }
    // read git binary path; overwritten if user provided it already
    if (not clargs->common.git_path) {
        auto git = ReadLocation(rc_config["git"],
                                clargs->common.just_mr_paths->workspace_root);
        if (git) {
            clargs->common.git_path = git->first;
        }
    }
    // read the just file-arguments
    auto just_files = rc_config["just files"];
    if (just_files.IsNotNull()) {
        if (not just_files->IsMap()) {
            Logger::Log(LogLevel::Error,
                        "Configuration-file provided 'just files' has to be a "
                        "map, but found {}.",
                        just_files->ToString());
            std::exit(kExitConfigError);
        }
        auto files = Configuration(just_files);
        clargs->just_cmd.config = ReadOptionalLocationList(
            files["config"],
            clargs->common.just_mr_paths->workspace_root,
            "'config' in 'just files'");
        clargs->just_cmd.endpoint_configuration = ReadOptionalLocationList(
            files["endpoint-configuration"],
            clargs->common.just_mr_paths->workspace_root,
            "'endpoint-configuration' in 'just files'");
    }
    // read additional just args; user can append, but does not overwrite
    auto just_args = rc_config["just args"];
    if (just_args.IsNotNull()) {
        if (not just_args->IsMap()) {
            Logger::Log(LogLevel::Error,
                        "Configuration-file provided 'just' arguments has to "
                        "be a map, but found {}",
                        just_args->ToString());
            std::exit(kExitConfigError);
        }
        for (auto const& [cmd_name, cmd_args] : just_args->Map()) {
            // get list of string args for current command
            std::vector<std::string> args{};
            if (not cmd_args->IsList()) {
                Logger::Log(
                    LogLevel::Error,
                    "Configuration-file provided 'just' argument key {} has to "
                    "have as value a list of strings, but found {}",
                    cmd_name,
                    cmd_args->ToString());
                std::exit(kExitConfigError);
            }
            auto const& args_list = cmd_args->List();
            args.reserve(args_list.size());
            for (auto const& arg : args_list) {
                if (not arg->IsString()) {
                    Logger::Log(
                        LogLevel::Error,
                        "Configuration-file provided 'just' argument key {} "
                        "must have strings in its list value, but found {}",
                        cmd_name,
                        arg->ToString());
                    std::exit(kExitConfigError);
                }
                args.emplace_back(arg->String());
            }
            clargs->just_cmd.just_args[cmd_name] = std::move(args);
        }
    }
    // read default for local launcher
    if (not clargs->common.local_launcher) {
        auto launcher = rc_config["local launcher"];
        if (launcher.IsNotNull()) {
            if (not launcher->IsList()) {
                Logger::Log(LogLevel::Error,
                            "Configuration-file provided launcher has to be a "
                            "list of strings, but found {}",
                            launcher->ToString());
                std::exit(kExitConfigError);
            }
            std::vector<std::string> default_launcher{};
            default_launcher.reserve(launcher->List().size());
            for (auto const& entry : launcher->List()) {
                if (not entry->IsString()) {
                    Logger::Log(LogLevel::Error,
                                "Configuration-file provided launcher {} is "
                                "not a list of strings",
                                launcher->ToString());
                    std::exit(kExitConfigError);
                }
                default_launcher.emplace_back(entry->String());
            }
            clargs->common.local_launcher = default_launcher;
        }
        else {
            clargs->common.local_launcher = kDefaultLauncher;
        }
    }
    // Set log limit, if specified and not set on the command line
    if (not clargs->log.log_limit) {
        auto limit = rc_config["log limit"];
        if (limit.IsNotNull()) {
            if (not limit->IsNumber()) {
                Logger::Log(LogLevel::Error,
                            "Configuration-file specified log-limit has to be "
                            "a number, but found {}",
                            limit->ToString());
                std::exit(kExitConfigError);
            }
            clargs->log.log_limit = ToLogLevel(limit->Number());
            LogConfig::SetLogLimit(*clargs->log.log_limit);
        }
    }
    // Add additional log sinks specified in the rc file.
    auto log_files = rc_config["log files"];
    if (log_files.IsNotNull()) {
        if (not log_files->IsList()) {
            Logger::Log(LogLevel::Error,
                        "Configuration-provided log files have to be a list of "
                        "location objects, but found {}",
                        log_files->ToString());
            std::exit(kExitConfigError);
        }
        for (auto const& log_file : log_files->List()) {
            auto path =
                ReadLocation(log_file->ToJson(),
                             clargs->common.just_mr_paths->workspace_root);
            if (path) {
                LogConfig::AddSink(LogSinkFile::CreateFactory(
                    path->first,
                    clargs->log.log_append ? LogSinkFile::Mode::Append
                                           : LogSinkFile::Mode::Overwrite));
                clargs->log.log_files.emplace_back(path->first);
            }
        }
    }
    // read remote exec args; overwritten if user provided it already
    auto remote = rc_config["remote execution"];
    if (remote.IsNotNull()) {
        if (not remote->IsMap()) {
            Logger::Log(LogLevel::Error,
                        "Configuration-provided remote execution arguments has "
                        "to be a map, but found {}",
                        remote->ToString());
            std::exit(kExitConfigError);
        }
        if (not clargs->common.remote_execution_address) {
            auto addr = remote->Get("address", Expression::none_t{});
            if (addr.IsNotNull()) {
                if (not addr->IsString()) {
                    Logger::Log(LogLevel::Error,
                                "Configuration-provided remote execution "
                                "address has to be a string, but found {}",
                                addr->ToString());
                    std::exit(kExitConfigError);
                }
                clargs->common.remote_execution_address = addr->String();
            }
        }
        if (not clargs->common.compatible) {
            auto compat = remote->Get("compatible", Expression::none_t{});
            if (compat.IsNotNull()) {
                if (not compat->IsBool()) {
                    Logger::Log(LogLevel::Error,
                                "Configuration-provided remote execution "
                                "compatibility has to be a flag, but found {}",
                                compat->ToString());
                    std::exit(kExitConfigError);
                }
                clargs->common.compatible = compat->Bool();
            }
        }
    }
    // read remote exec args; overwritten if user provided it already
    auto serve = rc_config["remote serve"];
    if (serve.IsNotNull()) {
        if (not serve->IsMap()) {
            Logger::Log(LogLevel::Error,
                        "Configuration-provided remote serve service arguments "
                        "has to be a map, but found {}",
                        serve->ToString());
            std::exit(kExitConfigError);
        }
        if (not clargs->common.remote_serve_address) {
            auto addr = serve->Get("address", Expression::none_t{});
            if (addr.IsNotNull()) {
                if (not addr->IsString()) {
                    Logger::Log(LogLevel::Error,
                                "Configuration-provided remote serve service "
                                "address has to be a string, but found {}",
                                addr->ToString());
                    std::exit(kExitConfigError);
                }
                clargs->common.remote_serve_address = addr->String();
            }
        }
    }
    // read authentication args; overwritten if user provided it already
    auto auth_args = rc_config["authentication"];
    if (auth_args.IsNotNull()) {
        if (not auth_args->IsMap()) {
            Logger::Log(LogLevel::Error,
                        "Configuration-provided authentication arguments has "
                        "to be a map, but found {}",
                        auth_args->ToString());
            std::exit(kExitConfigError);
        }
        if (not clargs->auth.tls_ca_cert) {
            auto v =
                ReadLocation(auth_args->Get("ca cert", Expression::none_t{}),
                             clargs->common.just_mr_paths->workspace_root);
            if (v) {
                clargs->auth.tls_ca_cert = v->first;
            }
        }
        if (not clargs->auth.tls_client_cert) {
            auto v = ReadLocation(
                auth_args->Get("client cert", Expression::none_t{}),
                clargs->common.just_mr_paths->workspace_root);
            if (v) {
                clargs->auth.tls_client_cert = v->first;
            }
        }
        if (not clargs->auth.tls_client_key) {
            auto v =
                ReadLocation(auth_args->Get("client key", Expression::none_t{}),
                             clargs->common.just_mr_paths->workspace_root);
            if (v) {
                clargs->auth.tls_client_key = v->first;
            }
        }
    }
    // read path to absent repository specification if not already provided by
    // the user
    if (not clargs->common.absent_repository_file) {
        auto absent_order = rc_config["absent"];
        if (absent_order.IsNotNull() and absent_order->IsList()) {
            for (auto const& entry : absent_order->List()) {
                auto path = ReadLocation(
                    entry, clargs->common.just_mr_paths->workspace_root);
                if (path and FileSystemManager::IsFile(path->first)) {
                    clargs->common.absent_repository_file = path->first;
                    break;
                }
            }
        }
    }
    // read config lookup order
    auto config_lookup_order = rc_config["config lookup order"];
    if (config_lookup_order.IsNotNull()) {
        for (auto const& entry : config_lookup_order->List()) {
            auto paths = ReadLocation(
                entry, clargs->common.just_mr_paths->workspace_root);
            if (paths and FileSystemManager::IsFile(paths->first)) {
                clargs->common.just_mr_paths->setup_root = paths->second;
                return paths->first;
            }
        }
    }
    else {
        for (auto const& entry : kDefaultConfigLocations) {
            auto paths = ReadLocation(
                entry, clargs->common.just_mr_paths->workspace_root);
            if (paths and FileSystemManager::IsFile(paths->first)) {
                clargs->common.just_mr_paths->setup_root = paths->second;
                return paths->first;
            }
        }
    }
    return std::nullopt;  // default return value
}