9bf5450fe5bf56ab461c54e80ccab1439edc5b47
[babeltrace.git] / tests / lib / conds / utils.cpp
1 /*
2 * SPDX-License-Identifier: GPL-2.0-only
3 *
4 * Copyright (C) 2020 Philippe Proulx <pproulx@efficios.com>
5 */
6
7 #include <glib.h>
8 #include <stdlib.h>
9 #include <string.h>
10
11 #include <babeltrace2/babeltrace.h>
12
13 #include "common/assert.h"
14 #include "cpp-common/vendor/fmt/core.h"
15 #include "cpp-common/vendor/nlohmann/json.hpp"
16
17 #include "utils.hpp"
18
19 CondTrigger::CondTrigger(const Type type, const std::string& condId,
20 const bt2s::optional<std::string>& nameSuffix) noexcept :
21 _mType {type},
22 _mCondId {fmt::format("{}:{}", type == Type::PRE ? "pre" : "post", condId)},
23 _mName {
24 fmt::format("{}{}{}", condId, nameSuffix ? "-" : "", nameSuffix ? nameSuffix->data() : "")}
25 {
26 }
27
28 SimpleCondTrigger::SimpleCondTrigger(std::function<void()> func, const Type type,
29 const std::string& condId,
30 const bt2s::optional<std::string>& nameSuffix) :
31 CondTrigger {type, condId, nameSuffix},
32 _mFunc {std::move(func)}
33 {
34 }
35
36 namespace {
37
38 void listCondTriggers(const CondTriggers condTriggers) noexcept
39 {
40 auto condTriggerArray = nlohmann::json::array();
41
42 for (const auto condTrigger : condTriggers) {
43 condTriggerArray.push_back(nlohmann::json {
44 {"cond-id", condTrigger->condId()},
45 {"name", condTrigger->name()},
46 });
47 }
48
49 fmt::println("{}", condTriggerArray.dump());
50 }
51
52 } /* namespace */
53
54 void condMain(const int argc, const char ** const argv, const CondTriggers condTriggers) noexcept
55 {
56 BT_ASSERT(argc >= 2);
57
58 if (strcmp(argv[1], "list") == 0) {
59 listCondTriggers(condTriggers);
60 } else if (strcmp(argv[1], "run") == 0) {
61 /*
62 * It's expected that calling `*condTriggers[index]` below
63 * aborts (calls bt_common_abort()). In this testing context, we
64 * don't want any custom abortion command to run.
65 */
66 g_unsetenv("BABELTRACE_EXEC_ON_ABORT");
67
68 /* Call the trigger */
69 BT_ASSERT(argc >= 3);
70
71 const auto index = atoi(argv[2]);
72
73 BT_ASSERT(index >= 0 && index < condTriggers.size());
74 (*condTriggers[index])();
75 }
76 }
This page took 0.030231 seconds and 3 git commands to generate.