* @brief A class to parse command line arguments. All arguments are simple on/off flags. */
| 3863 | * @brief A class to parse command line arguments. All arguments are simple on/off flags. |
| 3864 | */ |
| 3865 | class [[nodiscard]] arg_parser |
| 3866 | { |
| 3867 | public: |
| 3868 | /** |
| 3869 | * @brief Convert the command line arguments passed to the `main()` function into an `std::vector`. |
| 3870 | * |
| 3871 | * @param argc The number of arguments. |
| 3872 | * @param argv An array containing the arguments. |
| 3873 | */ |
| 3874 | arg_parser(int argc, char* argv[]) : args(argv + 1, argv + argc), executable(argv[0]) {}; |
| 3875 | |
| 3876 | /** |
| 3877 | * @brief Check if a specific command line argument has been passed to the program. If no arguments were passed, use the default value instead. |
| 3878 | * |
| 3879 | * @param arg The argument to check for. |
| 3880 | * @return `true` if the argument exists, `false` otherwise. |
| 3881 | */ |
| 3882 | [[nodiscard]] bool operator[](const std::string_view arg) |
| 3883 | { |
| 3884 | if (size() > 0) |
| 3885 | return (args.count(arg) == 1); |
| 3886 | return allowed[arg].def; |
| 3887 | } |
| 3888 | |
| 3889 | /** |
| 3890 | * @brief Add an argument to the list of allowed arguments. |
| 3891 | * |
| 3892 | * @param arg The argument. |
| 3893 | * @param desc The description of the argument. |
| 3894 | * @param def The default value of the argument. |
| 3895 | */ |
| 3896 | void add_argument(const std::string_view arg, const std::string_view desc, const bool def) |
| 3897 | { |
| 3898 | allowed[arg] = {desc, def}; |
| 3899 | } |
| 3900 | |
| 3901 | /** |
| 3902 | * @brief Get the name of the executable. |
| 3903 | * |
| 3904 | * @return The name of the executable. |
| 3905 | */ |
| 3906 | std::string_view get_executable() |
| 3907 | { |
| 3908 | return executable; |
| 3909 | } |
| 3910 | |
| 3911 | void show_help() const |
| 3912 | { |
| 3913 | int width = 1; |
| 3914 | for (const auto& [arg, opt] : allowed) |
| 3915 | width = std::max(width, static_cast<int>(arg.size())); |
| 3916 | logln("\nAvailable options (all are on/off and default to off):"); |
| 3917 | for (const auto& [arg, opt] : allowed) |
| 3918 | logln(" ", std::left, std::setw(width), arg, " ", opt.desc); |
| 3919 | log("If no options are entered, the default is:\n "); |
| 3920 | for (const auto& [arg, opt] : allowed) |
| 3921 | { |
| 3922 | if (opt.def) |
nothing calls this directly
no outgoing calls
no test coverage detected