| 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 bt2c::CStringView nameSuffix) noexcept : |
| 21 | _mType {type}, |
| 22 | _mCondId {fmt::format("{}:{}", type == Type::PRE ? "pre" : "post", condId)}, |
| 23 | _mName {fmt::format("{}{}{}", condId, nameSuffix ? "-" : "", nameSuffix ? nameSuffix : "")} |
| 24 | { |
| 25 | } |
| 26 | |
| 27 | SimpleCondTrigger::SimpleCondTrigger(std::function<void()> func, const Type type, |
| 28 | const std::string& condId, |
| 29 | const bt2c::CStringView nameSuffix) : |
| 30 | CondTrigger {type, condId, nameSuffix}, |
| 31 | _mFunc {std::move(func)} |
| 32 | { |
| 33 | } |
| 34 | |
| 35 | namespace { |
| 36 | |
| 37 | void listCondTriggers(const CondTriggers& condTriggers) noexcept |
| 38 | { |
| 39 | auto condTriggerArray = nlohmann::json::array(); |
| 40 | |
| 41 | for (const auto& condTrigger : condTriggers) { |
| 42 | condTriggerArray.push_back(nlohmann::json { |
| 43 | {"cond-id", condTrigger->condId()}, |
| 44 | {"name", condTrigger->name()}, |
| 45 | }); |
| 46 | } |
| 47 | |
| 48 | fmt::println("{}", condTriggerArray.dump()); |
| 49 | } |
| 50 | |
| 51 | } /* namespace */ |
| 52 | |
| 53 | void condMain(const int argc, const char ** const argv, const CondTriggers& condTriggers) noexcept |
| 54 | { |
| 55 | BT_ASSERT(argc >= 2); |
| 56 | |
| 57 | if (strcmp(argv[1], "list") == 0) { |
| 58 | listCondTriggers(condTriggers); |
| 59 | } else if (strcmp(argv[1], "run") == 0) { |
| 60 | /* |
| 61 | * It's expected that calling `*condTriggers[index]` below |
| 62 | * aborts (calls bt_common_abort()). In this testing context, we |
| 63 | * don't want any custom abortion command to run. |
| 64 | */ |
| 65 | g_unsetenv("BABELTRACE_EXEC_ON_ABORT"); |
| 66 | |
| 67 | /* Call the trigger */ |
| 68 | BT_ASSERT(argc >= 3); |
| 69 | |
| 70 | const auto index = atoi(argv[2]); |
| 71 | |
| 72 | BT_ASSERT(index >= 0 && index < condTriggers.size()); |
| 73 | (*condTriggers[index])(); |
| 74 | } |
| 75 | } |