diff --git a/include/rfl/cli/read_app.hpp b/include/rfl/cli/read_app.hpp index 230fc2d8f..4ab5cb336 100644 --- a/include/rfl/cli/read_app.hpp +++ b/include/rfl/cli/read_app.hpp @@ -50,7 +50,8 @@ inline rfl::Result take_builtin_flag( /// instead of reading the struct. template rfl::Result> parse_and_read_app( - const std::string& _program_name, const ParseFn& _parse) { + const std::string& _program_name, const ParseFn& _parse, + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { using ProcessorsType = Processors; using ResultType = std::variant; auto options = make_options(); @@ -78,7 +79,7 @@ rfl::Result> parse_and_read_app( } if (*help || *help_short) { - return usage(_program_name, true) + return usage(_program_name, _usage_opts) .transform([](std::string _text) { return ResultType( HelpOrVersion{HelpOrVersion::Kind::help, std::move(_text)}); @@ -135,36 +136,45 @@ inline std::string program_name(int argc, const wchar_t* const argv[]) { /// has no name. /// @return The struct, or the help or version text, or an error template -rfl::Result> read_app(int argc, - const char* const argv[]) { +rfl::Result> read_app( + int argc, const char* const argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { return internal::parse_and_read_app( internal::program_name(argc, argv), [&](const auto& _options) { return internal::parse_argv(argc, argv, _options); - }); + }, + _usage_opts); } template -rfl::Result> read_app(int argc, char* argv[]) { - return read_app(argc, static_cast(argv)); +rfl::Result> read_app( + int argc, char* argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { + return read_app(argc, static_cast(argv), + _usage_opts); } /// Like rfl::cli::read_app, for wide-character arguments, which are /// converted to UTF-8 first. template rfl::Result> read_app( - int argc, const wchar_t* const argv[]) { + int argc, const wchar_t* const argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { return internal::parse_and_read_app( internal::program_name(argc, argv), [&](const auto& _options) { return internal::parse_argv(argc, argv, _options); - }); + }, + _usage_opts); } template -rfl::Result> read_app(int argc, - wchar_t* argv[]) { - return read_app(argc, static_cast(argv)); +rfl::Result> read_app( + int argc, wchar_t* argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { + return read_app(argc, static_cast(argv), + _usage_opts); } /// Like rfl::cli::read_app, reading every element of a range of narrow or @@ -174,11 +184,14 @@ template > requires(internal::StringRange || internal::WideStringRange) rfl::Result> read_app( - std::string_view _program_name, R&& _args) { + std::string_view _program_name, R&& _args, + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { return internal::parse_and_read_app( - std::string(_program_name), [&](const auto& _options) { + std::string(_program_name), + [&](const auto& _options) { return internal::parse_argv(std::forward(_args), _options); - }); + }, + _usage_opts); } /// Like rfl::cli::read_app, reading every element of a range of narrow or @@ -186,10 +199,12 @@ rfl::Result> read_app( template > requires(internal::StringRange || internal::WideStringRange) -rfl::Result> read_app(R&& _args) { +rfl::Result> read_app( + R&& _args, + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { using ProcessorsType = Processors; return read_app(internal::app_settings_t::name, - std::forward(_args)); + std::forward(_args), _usage_opts); } } // namespace rfl::cli diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 9c5c2d1ca..2a80e10b9 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -41,6 +41,30 @@ namespace rfl::cli { +/// Runtime customization for `rfl::cli::usage` and `rfl::cli::read_app`. +struct UsageOptions { + bool detailed = true; + /// If non-empty, shown before the Usage line in detailed output (overrides + /// any header from rfl::cli::App). + std::string header = {}; + /// If non-empty, replaces the auto-generated synopsis after "Usage: ". + std::string synopsis = {}; + /// If non-empty, shown after the Usage line in detailed output. + std::string description = {}; + /// If non-empty, appended after a blank line at the end of detailed output. + std::string footer = {}; + /// If non-empty, places built-in `--help` and `--version` in this group + /// (at the start of the group if fields already use it). + std::string help_group = {}; + /// Maximum left-column width used to align option descriptions; options + /// wider than this place their description on the next line instead of + /// widening every other row. Set to 0 for no cap. + size_t max_option_width = 40; + /// Group names to omit from generated detailed help output (e.g. conditional + /// feature groups hidden at runtime). + std::vector hidden_groups = {}; +}; + namespace internal { /// Whether a top-level field is required, which the schema cannot tell the @@ -624,10 +648,11 @@ inline std::string usage_help_text(const UsageArg& _arg) { /// The rows of the built-in options of rfl::cli::App that no field takes. inline std::vector builtin_usage_args( - const BuiltinOptions& _builtin) { + const BuiltinOptions& _builtin, + const std::string& _help_group = std::string()) { auto args = std::vector(); - const auto make = [](std::string_view _name, std::string_view _short_name, - std::string _description) { + const auto make = [&](std::string_view _name, std::string_view _short_name, + std::string _description) { auto arg = UsageArg{}; arg.name = std::string(_name); arg.short_name = std::string(_short_name); @@ -635,6 +660,7 @@ inline std::vector builtin_usage_args( arg.bare = true; arg.required = false; arg.description = std::move(_description); + arg.group = _help_group; return arg; }; if (_builtin.help) { @@ -654,22 +680,47 @@ inline std::vector builtin_usage_args( /// argument (rfl::cli::OptionsFirst), so the synopsis lists them first. inline std::string format_usage(const std::string& _program_name, const std::vector& _args, - const bool _detailed, + const UsageOptions& _opts, const std::optional _delimiter, const bool _options_first, const std::string& _header) { - auto synopsis = _args; - if (_options_first) { - std::stable_partition(synopsis.begin(), synopsis.end(), - [](const UsageArg& _arg) { return !_arg.positional; }); - } - auto out = (_detailed ? _header : std::string()) + "Usage: " + _program_name; - for (const auto& arg : synopsis) { - const auto str = usage_arg_to_string(arg, "|", _delimiter); - out += arg.required ? " " + str : " [" + str + "]"; - } - out += '\n'; - if (!_detailed || _args.empty()) { + auto out = std::string(); + if (_opts.detailed) { + if (!_opts.header.empty()) { + out += _opts.header; + if (!out.ends_with('\n')) { + out += '\n'; + } + out += '\n'; + } else { + out += _header; + } + } + if (!_opts.synopsis.empty()) { + out += "Usage: " + _opts.synopsis + "\n"; + } else { + auto synopsis = _args; + if (_options_first) { + std::stable_partition(synopsis.begin(), synopsis.end(), + [](const UsageArg& _arg) { return !_arg.positional; }); + } + out += "Usage: " + _program_name; + for (const auto& arg : synopsis) { + const auto str = usage_arg_to_string(arg, "|", _delimiter); + out += arg.required ? " " + str : " [" + str + "]"; + } + out += '\n'; + } + if (!_opts.detailed) { + return out; + } + if (!_opts.description.empty()) { + out += "\n" + _opts.description + "\n"; + } + if (_args.empty()) { + if (!_opts.footer.empty()) { + out += "\n" + _opts.footer + "\n"; + } return out; } @@ -678,7 +729,12 @@ inline std::string format_usage(const std::string& _program_name, for (const auto& arg : _args) { rows.emplace_back(usage_arg_to_string(arg, ", ", _delimiter), usage_help_text(arg)); - width = std::max(width, rows.back().first.size()); + const size_t row_w = rows.back().first.size(); + if (_opts.max_option_width == 0 || row_w <= _opts.max_option_width) { + width = std::max(width, row_w); + } else { + width = std::max(width, _opts.max_option_width); + } } constexpr size_t indent = 2; @@ -688,7 +744,11 @@ inline std::string format_usage(const std::string& _program_name, const std::string& _right) { out += std::string(indent, ' ') + _left; if (!_right.empty()) { - out += std::string(width - _left.size() + gap, ' '); + if (_left.size() <= width) { + out += std::string(width - _left.size() + gap, ' '); + } else { + out += continuation; + } for (const char c : _right) { if (c == '\n') { out += continuation; @@ -709,30 +769,32 @@ inline std::string format_usage(const std::string& _program_name, for (const auto& [left, right] : rows) { emit_row(left, right); } - return out; - } - - // Emit sections in order of first appearance; ungrouped args (if any) go - // under "Arguments". - std::vector section_order; - for (const auto& arg : _args) { - const std::string section = - arg.group.empty() ? std::string("Arguments") : arg.group; - if (std::find(section_order.begin(), section_order.end(), section) - == section_order.end()) { - section_order.push_back(section); + } else { + // Emit sections in order of first appearance; ungrouped args (if any) go + // under "Arguments". + std::vector section_order; + for (const auto& arg : _args) { + const std::string section = + arg.group.empty() ? std::string("Arguments") : arg.group; + if (std::find(section_order.begin(), section_order.end(), section) + == section_order.end()) { + section_order.push_back(section); + } } - } - for (const auto& section : section_order) { - out += "\n" + section + ":\n"; - for (size_t i = 0; i < _args.size(); ++i) { - const std::string arg_section = - _args[i].group.empty() ? std::string("Arguments") : _args[i].group; - if (arg_section == section) { - emit_row(rows[i].first, rows[i].second); + for (const auto& section : section_order) { + out += "\n" + section + ":\n"; + for (size_t i = 0; i < _args.size(); ++i) { + const std::string arg_section = + _args[i].group.empty() ? std::string("Arguments") : _args[i].group; + if (arg_section == section) { + emit_row(rows[i].first, rows[i].second); + } } } } + if (!_opts.footer.empty()) { + out += "\n" + _opts.footer + "\n"; + } return out; } @@ -781,7 +843,7 @@ std::optional usage_defaults() { /// rfl::DefaultVal and default-constructing it throws. template rfl::Result usage(const std::string& _program_name, - const bool _detailed = false) { + const UsageOptions& _opts) { using ProcessorsType = Processors; using NamedTupleType = rfl::internal::processed_t; constexpr auto delimiter = internal::list_delimiter_v; @@ -806,13 +868,44 @@ rfl::Result usage(const std::string& _program_name, auto collector = internal::UsageCollector( &definition, &meta, &options, rfl::internal::no_optionals_v, delimiter); - auto args = internal::builtin_usage_args(builtin); - const auto fields = collector.collect( + auto builtin_args = + internal::builtin_usage_args(builtin, _opts.help_group); + auto fields = collector.collect( rfl::internal::default_if_missing_v, internal::usage_defaults()); - args.insert(args.end(), fields.begin(), fields.end()); + auto args = std::vector(); + if (!_opts.help_group.empty() && !builtin_args.empty()) { + const auto pos = std::find_if( + fields.begin(), fields.end(), + [&](const internal::UsageArg& _a) { + return _a.group == _opts.help_group; + }); + if (pos != fields.end()) { + args.insert(args.end(), fields.begin(), pos); + args.insert(args.end(), builtin_args.begin(), builtin_args.end()); + args.insert(args.end(), pos, fields.end()); + } else { + args = std::move(builtin_args); + args.insert(args.end(), fields.begin(), fields.end()); + } + } else { + args = std::move(builtin_args); + args.insert(args.end(), fields.begin(), fields.end()); + } + if (!_opts.hidden_groups.empty()) { + args.erase( + std::remove_if( + args.begin(), args.end(), + [&](const internal::UsageArg& _a) { + return !_a.group.empty() && + std::find(_opts.hidden_groups.begin(), + _opts.hidden_groups.end(), + _a.group) != _opts.hidden_groups.end(); + }), + args.end()); + } return internal::format_usage( - _program_name, args, _detailed, delimiter, options.options_first, + _program_name, args, _opts, delimiter, options.options_first, internal::app_header(_program_name)); } catch (std::exception& e) { return error(e.what()); @@ -820,6 +913,12 @@ rfl::Result usage(const std::string& _program_name, }); } +template +rfl::Result usage(const std::string& _program_name, + const bool _detailed = false) { + return usage(_program_name, UsageOptions{.detailed = _detailed}); +} + } // namespace rfl::cli #endif diff --git a/tests/cli/test_usage_custom.cpp b/tests/cli/test_usage_custom.cpp new file mode 100644 index 000000000..32f1be14a --- /dev/null +++ b/tests/cli/test_usage_custom.cpp @@ -0,0 +1,122 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_usage_custom { + +struct CatOptions { + rfl::Group<"COMMAND OPTIONS", + rfl::Description<"Buffer data in memory", rfl::DefaultVal>> + buffer_data = false; + rfl::Group<"COMMON OPTIONS", + rfl::Short<"v", rfl::Description<"Set verbose mode", + rfl::DefaultVal>>> + verbose = false; + rfl::Group<"INPUT OPTIONS", + rfl::Short<"F", rfl::Description<"Format of input files", + std::optional>>> + input_format; + rfl::Hidden>>> + input_filenames; +}; + +using SubApp = + rfl::cli::App<"", "", "", rfl::cli::BuiltinHelp::short_and_long>; + +TEST(cli, test_usage_custom_synopsis_description_footer_and_help_group) { + const rfl::cli::UsageOptions opts{ + .detailed = true, + .synopsis = "osmium cat [OPTIONS] [OSM-FILE...]", + .description = "Concatenate OSM files and convert to different formats.", + .footer = "Use 'osmium help cat' to display the manual page.", + .help_group = "COMMON OPTIONS", + }; + const std::vector args = {"-h"}; + const auto res = + rfl::cli::read_app("osmium cat", args, opts); + ASSERT_TRUE(res) << res.error().what(); + ASSERT_TRUE(std::holds_alternative(*res)); + const auto& text = std::get(*res).text; + + EXPECT_TRUE(text.starts_with( + "Usage: osmium cat [OPTIONS] [OSM-FILE...]\n\n" + "Concatenate OSM files and convert to different formats.\n")); + const auto cmd_pos = text.find("\nCOMMAND OPTIONS:\n"); + const auto common_pos = text.find("\nCOMMON OPTIONS:\n"); + const auto help_pos = text.find(" -h, --help"); + const auto verbose_pos = text.find(" -v, --verbose"); + const auto input_pos = text.find("\nINPUT OPTIONS:\n"); + const auto footer_pos = + text.find("\nUse 'osmium help cat' to display the manual page.\n"); + + ASSERT_NE(cmd_pos, std::string::npos) << text; + ASSERT_NE(common_pos, std::string::npos) << text; + ASSERT_NE(help_pos, std::string::npos) << text; + ASSERT_NE(verbose_pos, std::string::npos) << text; + ASSERT_NE(input_pos, std::string::npos) << text; + ASSERT_NE(footer_pos, std::string::npos) << text; + + // Built-in -h/--help is placed at the start of COMMON OPTIONS without + // reordering COMMAND OPTIONS ahead of it. + EXPECT_LT(cmd_pos, common_pos); + EXPECT_LT(common_pos, help_pos); + EXPECT_LT(help_pos, verbose_pos); + EXPECT_LT(verbose_pos, input_pos); + EXPECT_LT(input_pos, footer_pos); + EXPECT_EQ(text.find("input-filenames"), std::string::npos); +} + +TEST(cli, test_usage_custom_header_before_usage) { + const rfl::cli::UsageOptions opts{ + .detailed = true, + .header = "solc, the Solidity commandline compiler.\n\nNo warranty.", + .synopsis = "solc [options] [input_file...]", + }; + const auto text = rfl::cli::usage("solc", opts); + ASSERT_TRUE(text) << text.error().what(); + EXPECT_TRUE(text->starts_with( + "solc, the Solidity commandline compiler.\n\nNo warranty.\n\n" + "Usage: solc [options] [input_file...]\n")) + << *text; +} + +TEST(cli, test_usage_max_option_width_wraps_wide_options) { + struct WideOptions { + rfl::Description<"Short flag", rfl::DefaultVal> verbose = false; + rfl::Description<"Very wide option label", std::optional> + very_long_option_name_exceeding_forty_characters; + }; + const auto text = + rfl::cli::usage("tool", true); + ASSERT_TRUE(text) << text.error().what(); + // Short option should not be padded past the 40-char cap. + EXPECT_EQ(text->find("--verbose "), + std::string::npos) + << *text; + // Wide option wraps its description onto the next line. + EXPECT_NE( + text->find( + "--very-long-option-name-exceeding-forty-characters=\n"), + std::string::npos) + << *text; +} + +TEST(cli, test_usage_hidden_groups) { + const rfl::cli::UsageOptions opts{ + .detailed = true, + .hidden_groups = {"INPUT OPTIONS"}, + }; + const auto text = rfl::cli::usage("osmium cat", opts); + ASSERT_TRUE(text) << text.error().what(); + EXPECT_NE(text->find("COMMAND OPTIONS:"), std::string::npos) << *text; + EXPECT_NE(text->find("COMMON OPTIONS:"), std::string::npos) << *text; + EXPECT_EQ(text->find("INPUT OPTIONS:"), std::string::npos) << *text; + EXPECT_EQ(text->find("--input-format"), std::string::npos) << *text; +} + +} // namespace test_usage_custom