Skip to content

Commit 5bb2871

Browse files
committed
Add cli --exit-code
1 parent 984fe6d commit 5bb2871

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

src/lib/main.cpp

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@
99
#include <eggs/test/cli.hpp>
1010
#include <eggs/test/detail/print.hpp>
1111

12+
#include <charconv>
1213
#include <cstddef>
1314
#include <cstdio>
1415
#include <cstdlib>
1516
#include <filesystem>
17+
#include <optional>
1618
#include <string_view>
1719

1820
namespace eggs::test {
@@ -32,12 +34,22 @@ void print_help(std::FILE* out, std::string_view const usage)
3234
test::print_options(out, /*ns:*/ {}, k_desc_col);
3335
}
3436

37+
std::optional<int> parse_int(std::string_view sv) noexcept
38+
{
39+
int value = 0;
40+
auto [end, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value);
41+
if (ec != std::errc{} || end != sv.data() + sv.size()) return std::nullopt;
42+
return value;
43+
}
44+
3545
} // namespace
3646

3747
int main(int argc, char const* argv[])
3848
{
3949
run_options const opts = parse_cli(argc, argv);
4050

51+
std::optional<int> exit_code;
52+
4153
for (int i = 1; i < argc; ++i) {
4254
std::string_view const arg = argv[i];
4355

@@ -49,11 +61,22 @@ int main(int argc, char const* argv[])
4961
return EXIT_SUCCESS;
5062
}
5163

64+
if (arg.starts_with("--exit-code=")) {
65+
std::string_view const val = arg.substr(12);
66+
67+
if (exit_code = test::parse_int(val); !exit_code) {
68+
detail::println(stderr, "error: invalid exit code '{}'", val);
69+
return EXIT_FAILURE;
70+
}
71+
continue;
72+
}
73+
5274
detail::println(stderr, "error: unknown argument '{}'", arg);
5375
return EXIT_FAILURE;
5476
}
5577

56-
return test::run(opts);
78+
int const result = test::run(opts);
79+
return exit_code.value_or(result);
5780
}
5881

5982
} // namespace eggs::test

test/CMakeLists.txt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,31 @@ add_lib_test(
207207
EXITS 1
208208
)
209209

210+
# --exit-code=0 on a failing suite must override the exit code to 0.
211+
add_lib_test(
212+
cli.exit_code.pass
213+
SOURCES check.fail.cpp
214+
ARGS "--exit-code=0"
215+
EXITS 0
216+
)
217+
218+
# --exit-code=1 on a passing suite must override the exit code to 1.
219+
add_lib_test(
220+
cli.exit_code.fail
221+
SOURCES check.pass.cpp
222+
ARGS "--exit-code=1"
223+
EXITS 1
224+
)
225+
226+
# --exit-code=<non-integer> must print an error and exit 1.
227+
add_lib_test(
228+
cli.exit_code.invalid.fail
229+
SOURCES check.pass.cpp
230+
ARGS "--exit-code=oops"
231+
PASS_REGEX "invalid exit code 'oops'"
232+
EXITS 1
233+
)
234+
210235
# --list must print exactly the registered test case names, one per line.
211236
string(
212237
CONCAT _list_regex

0 commit comments

Comments
 (0)