C++Spec 1.1.0
BDD testing for C++
Loading...
Searching...
No Matches
argparse.hpp
1#pragma once
2
3#include <argparse/argparse.hpp>
4#include <fstream>
5#include <memory>
6#include <string>
7#include <string_view>
8#include "formatters/junit_xml.hpp"
10#include "formatters/tap.hpp"
12#include "runner.hpp"
13
14namespace CppSpec {
15
16inline std::string file_name(std::string_view path) {
17 std::string_view file = path;
18 for (size_t i = 0; i < path.size(); ++i) {
19 if (path[i] == '/') {
20 file = &path[i + 1];
21 }
22 }
23 return std::string{file};
24}
25
32struct JUnitOutputFile {
33 std::ofstream stream;
34 Formatters::JUnitXML formatter{stream, false};
35
36 explicit JUnitOutputFile(const std::string& path) : stream(path) {}
37};
38
39inline Runner parse(int argc, char** const argv) {
40 std::filesystem::path executable_path = argv[0];
41 std::string executable_name = executable_path.filename().string();
42 argparse::ArgumentParser program{executable_name};
43
44 program.add_argument("-f", "--format")
45 .default_value(std::string{"p"})
46 .choices("progress", "p", "tap", "t", "detail", "d", "junit", "j")
47 .required()
48 .help("set the output format");
49
50 program.add_argument("--output-junit").help("output JUnit XML to the specified file").default_value(std::string{});
51 program.add_argument("--verbose").help("increase output verbosity").flag();
52
53 try {
54 program.parse_args(argc, argv);
55 } catch (const std::runtime_error& err) {
56 std::cerr << err.what() << std::endl;
57 std::cerr << program;
58 std::exit(1);
59 }
60
61 auto format_string = program.get<std::string>("--format");
62 std::shared_ptr<Formatters::BaseFormatter> formatter;
63 if (format_string == "d" || format_string == "detail" || program["--verbose"] == true) {
64 formatter = std::make_shared<Formatters::Verbose>();
65 } else if (format_string == "p" || format_string == "progress") {
66 formatter = std::make_shared<Formatters::Progress>();
67 } else if (format_string == "t" || format_string == "tap") {
68 formatter = std::make_shared<Formatters::TAP>();
69 } else if (format_string == "j" || format_string == "junit") {
70 formatter = std::make_shared<Formatters::JUnitXML>();
71 } else {
72 std::cerr << "Unrecognized format type" << std::endl;
73 std::exit(-1);
74 }
75
76 auto junit_output_filepath = program.get<std::string>("--output-junit");
77 if (!junit_output_filepath.empty()) {
78 auto junit_file = std::make_shared<JUnitOutputFile>(junit_output_filepath);
79 std::shared_ptr<Formatters::BaseFormatter> junit_output{junit_file, &junit_file->formatter};
80 return Runner{formatter, junit_output};
81 }
82 return Runner{formatter};
83}
84} // namespace CppSpec
Definition junit_xml.hpp:180
A collection of Descriptions that are run in sequence.
Definition runner.hpp:16