diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 7c9c24797..361a45feb 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -6,6 +6,7 @@ #include "cli/App.hpp" #include "cli/KeepEmptyItems.hpp" #include "cli/ListDelimiter.hpp" +#include "cli/Opt.hpp" #include "cli/OptionsFirst.hpp" #include "cli/Parser.hpp" #include "cli/PureFlags.hpp" diff --git a/include/rfl/cli/Opt.hpp b/include/rfl/cli/Opt.hpp new file mode 100644 index 000000000..75e7c2aba --- /dev/null +++ b/include/rfl/cli/Opt.hpp @@ -0,0 +1,204 @@ +#ifndef RFL_CLI_OPT_HPP_ +#define RFL_CLI_OPT_HPP_ + +#include +#include +#include + +#include "../internal/StringLiteral.hpp" +#include "../internal/TransparentWrapper.hpp" + +namespace rfl::cli { + +/// Attribute tags accepted by `rfl::cli::Opt` in any order. +namespace attr { + +template +struct Short { + static constexpr auto value = _name; +}; + +struct Positional {}; + +struct Hidden {}; + +template +struct Group { + static constexpr auto value = _group; +}; + +template +struct ValueName { + static constexpr auto value = _name; +}; + +template +struct Implicit { + static constexpr auto value = _val; +}; + +struct MultiToken {}; + +template +struct Desc { + static constexpr auto value = _desc; +}; + +template +struct Deprecated { + static constexpr auto message = _msg; + static constexpr auto description = _desc; +}; + +template +struct DefaultHint { + static constexpr auto value = _hint; +}; + +} // namespace attr + +namespace internal { + +template +struct opt_attrs; + +template <> +struct opt_attrs<> { + static constexpr bool is_short = false; + static constexpr bool is_positional = false; + static constexpr bool is_hidden = false; + static constexpr bool has_group = false; + static constexpr bool has_value_name = false; + static constexpr bool is_multi_token = false; + static constexpr size_t num_implicit_value = 0; + static constexpr int count = 0; + static constexpr rfl::internal::StringLiteral<1> short_name = ""; + static constexpr rfl::internal::StringLiteral<1> implicit_value = ""; + static constexpr rfl::internal::StringLiteral<1> group_name = ""; + static constexpr rfl::internal::StringLiteral<1> value_name = ""; + static constexpr std::string_view description = {}; + static constexpr bool is_deprecated = false; + static constexpr std::string_view deprecation_message = {}; + static constexpr std::string_view default_hint = {}; +}; + +template +struct opt_attrs { + static_assert( + !std::is_same_v, + "Unknown attribute passed to rfl::cli::Opt. Use tags from " + "rfl::cli::attr (Short, Positional, Hidden, Group, ValueName, " + "Implicit, MultiToken, Desc, Deprecated, DefaultHint)."); +}; + +template +struct opt_attrs, Rest...> : opt_attrs { + using Next = opt_attrs; + static constexpr bool is_short = true; + static constexpr bool is_positional = false; + static constexpr auto short_name = _name; + static constexpr int count = Next::count + 1; +}; + +template +struct opt_attrs : opt_attrs { + using Next = opt_attrs; + static constexpr bool is_short = false; + static constexpr bool is_positional = true; + static constexpr int count = Next::count + 1; +}; + +template +struct opt_attrs : opt_attrs { + static constexpr bool is_hidden = true; +}; + +template +struct opt_attrs, Rest...> : opt_attrs { + static constexpr bool has_group = true; + static constexpr auto group_name = _group; +}; + +template +struct opt_attrs, Rest...> : opt_attrs { + static constexpr bool has_value_name = true; + static constexpr auto value_name = _name; +}; + +template +struct opt_attrs, Rest...> : opt_attrs { + using Next = opt_attrs; + static constexpr size_t num_implicit_value = Next::num_implicit_value + 1; + static constexpr auto implicit_value = _val; +}; + +template +struct opt_attrs : opt_attrs { + static constexpr bool is_multi_token = true; +}; + +template +struct opt_attrs, Rest...> : opt_attrs { + using Next = opt_attrs; + static constexpr std::string_view description = + _desc.string_view().empty() ? Next::description : _desc.string_view(); +}; + +template +struct opt_attrs, Rest...> : opt_attrs { + using Next = opt_attrs; + static constexpr std::string_view description = + _desc.string_view().empty() ? Next::description : _desc.string_view(); + static constexpr bool is_deprecated = true; + static constexpr std::string_view deprecation_message = + Next::is_deprecated ? Next::deprecation_message : _msg.string_view(); +}; + +template +struct opt_attrs, Rest...> : opt_attrs { + using Next = opt_attrs; + static constexpr std::string_view default_hint = + _hint.string_view().empty() ? Next::default_hint : _hint.string_view(); +}; + +} // namespace internal + +/// Single-layer variadic CLI option wrapper carrying any combination of +/// `rfl::cli::attr::*` metadata tags in any order, replacing deeply nested +/// `Group>>>` stacks with one wrapper. +/// +/// Example: +/// ```cpp +/// using namespace rfl::cli::attr; +/// rfl::cli::Opt, +/// Short<"o">, Group<"Output">, ValueName<"path">, +/// Desc<"Output directory">> output_dir; +/// ``` +template +struct Opt : rfl::internal::TransparentWrapper, T> { + using Base = rfl::internal::TransparentWrapper, T>; + using Base::Base; + using Base::operator=; + + using AttrsInfo = internal::opt_attrs; +}; + +namespace internal { + +template +struct is_cli_opt : std::false_type {}; + +template +struct is_cli_opt> : std::true_type {}; + +template +constexpr bool is_cli_opt_v = + is_cli_opt>>::value; + +} // namespace internal + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index cdd150edb..d53999e63 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -33,6 +33,7 @@ #include "../internal/processed_t.hpp" #include "../parsing/is_string_map.hpp" #include "AllowAbbreviations.hpp" +#include "Opt.hpp" #include "OptionsFirst.hpp" #include "Parser.hpp" #include "PureFlags.hpp" @@ -75,6 +76,10 @@ struct Option { /// when it is given without one. It views the rfl::ImplicitValue's /// template argument, which lives as long as the program. std::string_view implicit_value = {}; + + /// Whether a list option consumes multiple space-separated tokens after one + /// occurrence (rfl::MultiToken). + bool multi_token = false; }; /// The options that a target struct accepts, built once per @@ -117,6 +122,10 @@ struct Options { /// Section header name for fields wrapped in rfl::Group, sorted by path. std::vector> option_groups; + /// Custom value placeholder name for fields wrapped in rfl::ValueName, + /// sorted by path. + std::vector> option_value_names; + /// Whether options that match no field are an error (rfl::NoExtraFields). bool reject_unknown = false; @@ -158,16 +167,20 @@ struct Options { /// token (rfl::cli::PureFlags). bool pure_flags = false; - /// Records one leaf long option along with its optional hidden/group + /// Records one leaf long option along with its optional hidden/group/value_name /// metadata. Non-template to avoid per-field template instantiations. void add_leaf_option(std::string _path, const Option& _opt, - const bool _hidden, const std::string_view _group) { + const bool _hidden, const std::string_view _group, + const std::string_view _value_name) { if (_hidden) { hidden_options.push_back(_path); } if (!_group.empty()) { option_groups.emplace_back(_path, std::string(_group)); } + if (!_value_name.empty()) { + option_value_names.emplace_back(_path, std::string(_value_name)); + } long_options.emplace_back(std::move(_path), _opt); } @@ -202,6 +215,7 @@ struct Options { std::unique(hidden_options.begin(), hidden_options.end()), hidden_options.end()); sort_pairs(option_groups); + sort_pairs(option_value_names); } /// Returns the long options that `--_prefix` could abbreviate: every @@ -304,6 +318,12 @@ struct Options { return g ? std::string_view(*g) : std::string_view{}; } + /// Returns the rfl::ValueName for `_path`, or empty string_view if none. + std::string_view find_value_name(const std::string_view _path) const { + const auto* vn = find_pair(option_value_names, _path); + return vn ? std::string_view(*vn) : std::string_view{}; + } + /// Whether the last rfl::Positional field is a list. It then takes every /// positional argument after those of the other positional fields. bool last_positional_is_list() const { @@ -366,11 +386,14 @@ struct cli_annotations { static constexpr bool is_positional = false; static constexpr bool is_hidden = false; static constexpr bool has_group = false; + static constexpr bool has_value_name = false; + static constexpr bool is_multi_token = false; static constexpr size_t num_implicit_value = 0; static constexpr rfl::internal::StringLiteral<1> short_name = ""; static constexpr int count = 0; static constexpr rfl::internal::StringLiteral<1> implicit_value = ""; static constexpr rfl::internal::StringLiteral<1> group_name = ""; + static constexpr rfl::internal::StringLiteral<1> value_name = ""; }; template @@ -426,6 +449,54 @@ struct cli_annotations> : cli_annotations_t { static constexpr auto group_name = _group; }; +template +struct cli_annotations> { + using Inner = cli_annotations_t; + using Info = typename Opt::AttrsInfo; + + static constexpr bool is_short = Info::is_short || Inner::is_short; + static constexpr bool is_positional = + Info::is_positional || Inner::is_positional; + static constexpr bool is_hidden = Info::is_hidden || Inner::is_hidden; + static constexpr bool has_group = Info::has_group || Inner::has_group; + static constexpr bool has_value_name = + Info::has_value_name || Inner::has_value_name; + static constexpr bool is_multi_token = + Info::is_multi_token || Inner::is_multi_token; + static constexpr size_t num_implicit_value = + Info::num_implicit_value + Inner::num_implicit_value; + static constexpr int count = Info::count + Inner::count; + + static constexpr auto short_name = []() { + if constexpr (Info::is_short) { + return Info::short_name; + } else { + return Inner::short_name; + } + }(); + static constexpr auto implicit_value = []() { + if constexpr (Info::num_implicit_value > 0) { + return Info::implicit_value; + } else { + return Inner::implicit_value; + } + }(); + static constexpr auto group_name = []() { + if constexpr (Info::has_group) { + return Info::group_name; + } else { + return Inner::group_name; + } + }(); + static constexpr auto value_name = []() { + if constexpr (Info::has_value_name) { + return Info::value_name; + } else { + return Inner::value_name; + } + }(); +}; + /// The CLI metadata of the _i-th field of a NamedTuple. InnerType is the /// declared type of the field, whichever wrappers it consists of. template @@ -601,6 +672,8 @@ Option implicit_value_option() { template Option option_for() { using U = unwrapped_option_t; + static_assert(!cli_annotations_t::is_multi_token || is_option_list_v, + "rfl::cli::attr::MultiToken can only wrap a list type (such as std::vector)."); if constexpr (cli_annotations_t::num_implicit_value > 0) { return implicit_value_option(); } @@ -612,7 +685,8 @@ Option option_for() { return Option{OptionKind::other}; } else { - return Option{OptionKind::value, is_option_list_v}; + return Option{OptionKind::value, is_option_list_v, {}, + cli_annotations_t::is_multi_token}; } } @@ -674,16 +748,19 @@ void collect_options(const std::string& _prefix, Options* _options) { constexpr bool is_hidden = Ann::is_hidden; constexpr auto group_name = Ann::has_group ? Ann::group_name.string_view() : std::string_view{}; + constexpr auto value_name = + Ann::has_value_name ? Ann::value_name.string_view() + : std::string_view{}; if constexpr (Ann::num_implicit_value > 0) { _options->add_leaf_option( std::move(path), implicit_value_option(), - is_hidden, group_name); + is_hidden, group_name, value_name); } else if constexpr (std::is_same_v) { _options->add_leaf_option(std::move(path), Option{OptionKind::flag}, - is_hidden, group_name); + is_hidden, group_name, value_name); } else if constexpr (is_open_option_v) { _options->add_leaf_option(std::move(path), Option{OptionKind::other}, - is_hidden, group_name); + is_hidden, group_name, value_name); } else if constexpr (parsing::is_string_map_v) { if constexpr (is_hidden) { _options->hidden_options.push_back(path); @@ -691,6 +768,10 @@ void collect_options(const std::string& _prefix, Options* _options) { if constexpr (!group_name.empty()) { _options->option_groups.emplace_back(path, std::string(group_name)); } + if constexpr (!value_name.empty()) { + _options->option_value_names.emplace_back(path, + std::string(value_name)); + } add_open_prefix(path + path_separator, _options); } else if constexpr (is_option_struct_v) { @@ -705,9 +786,14 @@ void collect_options(const std::string& _prefix, Options* _options) { path + path_separator, _options); } } else { + static_assert( + !Ann::is_multi_token || is_option_list_v, + "rfl::cli::attr::MultiToken can only wrap a list type (such as std::vector)."); _options->add_leaf_option( - std::move(path), Option{OptionKind::value, is_option_list_v}, - is_hidden, group_name); + std::move(path), + Option{OptionKind::value, is_option_list_v, {}, + Ann::is_multi_token}, + is_hidden, group_name, value_name); } } }; diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index 42eb81588..611b9bbc9 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -222,6 +222,7 @@ inline rfl::Result parse_string_views( if (option.kind == OptionKind::unknown && _options.reject_unknown) { return error("Unknown option '--" + key + "'."); } + bool consume_multi = false; if (eq == std::string_view::npos && option.kind == OptionKind::value && _options.separate_values) { // --key value (rfl::cli::SeparateOptionValues). A flag never takes @@ -230,6 +231,7 @@ inline rfl::Result parse_string_views( auto v = take_value(option, "--" + key, &i); if (!v) { return error(v.error().what()); } val = std::move(*v); + consume_multi = option.multi_token; } else if (eq == std::string_view::npos && option.kind == OptionKind::implicit_value) { @@ -239,6 +241,12 @@ inline rfl::Result parse_string_views( } const auto r = add_long(key, std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } + while (consume_multi && i + 1 < _args.size() && _args[i + 1] != "--" + && !looks_like_option(_args[i + 1])) { + const auto r2 = + add_long(key, std::string(_args[++i]), option, arg_raw); + if (!r2) { return error(r2.error().what()); } + } continue; } @@ -274,6 +282,7 @@ inline rfl::Result parse_string_views( const bool alone = j == 0 && rest.empty(); auto val = std::string(); + bool consume_multi = false; if (j == 0 && rest.starts_with('=')) { // -x=value, whatever -x is. Unlike getopt, where -f=csv gives // "=csv", the '=' is not part of the value. @@ -314,10 +323,17 @@ inline rfl::Result parse_string_views( auto v = take_value(option, name, &i); if (!v) { return error(v.error().what()); } val = std::move(*v); + consume_multi = option.multi_token; } const auto r = add_short(key, std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } + while (consume_multi && i + 1 < _args.size() && _args[i + 1] != "--" + && !looks_like_option(_args[i + 1])) { + const auto r2 = + add_short(key, std::string(_args[++i]), option, arg_raw); + if (!r2) { return error(r2.error().what()); } + } break; } continue; diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index 1439ca1eb..16fd6d8a7 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -1,9 +1,12 @@ #ifndef RFL_CLI_READ_HPP_ #define RFL_CLI_READ_HPP_ +#include #include +#include #include #include +#include #include "../Processors.hpp" #include "../SnakeCaseToKebabCase.hpp" @@ -18,10 +21,58 @@ namespace rfl::cli { +/// Result returned by `rfl::cli::read_detailed`: holds the parsed struct along +/// with the sorted canonical long names of every option and positional argument +/// that was explicitly passed on the command line (including options whose +/// given value equals their default). +template +struct ReadResult { + T value; + std::vector provided; + + /// Returns true if the canonical option or positional name `_name` was + /// explicitly supplied on the command line. + bool was_provided(const std::string_view _name) const { + const auto it = std::lower_bound(provided.begin(), provided.end(), _name); + return it != provided.end() && *it == _name; + } +}; + namespace internal { static_assert(list_delimiter_v> == array_delimiter); +/// Resolves the parsed arguments and reads them into T, also capturing the +/// sorted list of explicitly provided canonical option names. +template +rfl::Result> read_parsed_detailed(ParsedArgs _parsed, + const Options& _options) { + static_assert(!internal::keep_empty_items_v + || internal::list_delimiter_v.has_value(), + "rfl::cli::KeepEmptyItems has no effect with " + "rfl::cli::ListDelimiter<\"\">, which does not split lists, " + "so an empty item is kept as \"\" anyway. Remove one of " + "them."); + return resolve_args(std::move(_parsed), _options) + .and_then([](auto _args) -> rfl::Result> { + std::vector provided; + provided.reserve(_args.values.size()); + for (const auto& [key, _] : _args.values) { + provided.push_back(key); + } + const auto r = + Reader(internal::list_delimiter_v, + internal::keep_empty_items_v, + std::move(_args.verbatim_list)); + const auto var = CliVarType{&_args.values, "", std::nullopt, + &_args.later_occurrences}; + return Parser::read(r, var).transform( + [&](T&& _val) { + return ReadResult{std::move(_val), std::move(provided)}; + }); + }); +} + /// Resolves the parsed arguments and reads them into T. template rfl::Result read_parsed(ParsedArgs _parsed, const Options& _options) { @@ -43,6 +94,25 @@ rfl::Result read_parsed(ParsedArgs _parsed, const Options& _options) { }); } +/// Categorizes the arguments with `_parse`, which takes the options of T +/// (see make_options) and returns ParsedArgs, and turns them into ReadResult. +template +rfl::Result> parse_and_read_detailed(const ParseFn& _parse) { + using ProcessorsType = + rfl::internal::flatten_processors_t; + static_assert(!internal::has_app_v, + "rfl::cli::App turns on --help and --version, which " + "rfl::cli::read_detailed cannot report. Call rfl::cli::read_app " + "instead."); + const auto& options = cached_options(); + return check_short_names(options) + .and_then([&](bool) { return _parse(options); }) + .and_then([&](ParsedArgs _parsed) { + return read_parsed_detailed(std::move(_parsed), + options); + }); +} + /// Categorizes the arguments with `_parse`, which takes the options of T /// (see make_options) and returns ParsedArgs, and turns them into a struct. template @@ -139,6 +209,46 @@ rfl::Result read(int argc, wchar_t* argv[]) { return read(argc, static_cast(argv)); } +/// Like `rfl::cli::read`, returning `ReadResult` containing both the parsed +/// struct and the sorted canonical names of explicitly provided options. +template > + requires internal::StringRange || internal::WideStringRange +rfl::Result> read_detailed(R&& _args) { + return internal::parse_and_read_detailed( + [&](const auto& _options) { + return internal::parse_argv(std::forward(_args), _options); + }); +} + +template +rfl::Result> read_detailed(int argc, const char* const argv[]) { + return internal::parse_and_read_detailed( + [&](const auto& _options) { + return internal::parse_argv(argc, argv, _options); + }); +} + +template +rfl::Result> read_detailed(int argc, char* argv[]) { + return read_detailed(argc, static_cast(argv)); +} + +template +rfl::Result> read_detailed(int argc, + const wchar_t* const argv[]) { + return internal::parse_and_read_detailed( + [&](const auto& _options) { + return internal::parse_argv(argc, argv, _options); + }); +} + +template +rfl::Result> read_detailed(int argc, wchar_t* argv[]) { + return read_detailed(argc, + static_cast(argv)); +} + } // namespace rfl::cli #endif diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 3b5c6fc41..11b512aed 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -48,6 +48,7 @@ #include "../to_view.hpp" #include "App.hpp" #include "ListDelimiter.hpp" +#include "Opt.hpp" #include "OptionsFirst.hpp" #include "Reader.hpp" #include "options.hpp" @@ -96,6 +97,8 @@ struct UsageArg { std::string implicit_value; /// Whether the field is a list, which can be repeated. bool is_list = false; + /// Whether the field accepts multiple space-separated tokens (rfl::MultiToken). + bool multi_token = false; /// Whether the field is the last positional one and a list, so that it /// takes the remaining positional arguments. bool takes_rest = false; @@ -106,6 +109,8 @@ struct UsageArg { /// The placeholder for one value: "", "" or "". Lists /// are rendered from it with the list delimiter. std::string value = ""; + /// Whether `value` was explicitly set via rfl::ValueName. + bool has_custom_value_name = false; /// The allowed values of enums and literals. std::vector choices; std::string description; @@ -113,6 +118,8 @@ struct UsageArg { /// Rendered constraints, such as "Range: 1..65535.". std::vector constraints; std::optional default_value; + /// Display-only default value hint (from rfl::DefaultHint or attr::DefaultHint). + std::string default_hint; /// Optional help section header (from rfl::Group). std::string group; }; @@ -404,6 +411,7 @@ struct usage_peel_base { static constexpr std::string_view description = {}; static constexpr bool is_deprecated = false; static constexpr std::string_view deprecation_message = {}; + static constexpr std::string_view default_hint = {}; static constexpr bool has_outermost_default_val = false; static constexpr bool has_any_default_val = false; static constexpr bool has_nullable = false; @@ -423,6 +431,7 @@ struct usage_peel, _outermost> { static constexpr bool is_deprecated = Next::is_deprecated; static constexpr std::string_view deprecation_message = Next::deprecation_message; + static constexpr std::string_view default_hint = Next::default_hint; static constexpr bool has_outermost_default_val = Next::has_outermost_default_val; static constexpr bool has_any_default_val = Next::has_any_default_val; @@ -444,6 +453,7 @@ struct usage_peel, _outermost> { static constexpr bool is_deprecated = true; static constexpr std::string_view deprecation_message = Next::is_deprecated ? Next::deprecation_message : _msg.string_view(); + static constexpr std::string_view default_hint = Next::default_hint; static constexpr bool has_outermost_default_val = Next::has_outermost_default_val; static constexpr bool has_any_default_val = Next::has_any_default_val; @@ -455,11 +465,37 @@ struct usage_peel, _outermost> { } }; +template +struct usage_peel, _outermost> { + using Info = typename Opt::AttrsInfo; + using Next = usage_peel, _outermost>; + using CoreType = typename Next::CoreType; + static constexpr std::string_view description = + Info::description.empty() ? Next::description : Info::description; + static constexpr bool is_deprecated = + Info::is_deprecated || Next::is_deprecated; + static constexpr std::string_view deprecation_message = + Next::is_deprecated ? Next::deprecation_message + : Info::deprecation_message; + static constexpr std::string_view default_hint = + Info::default_hint.empty() ? Next::default_hint : Info::default_hint; + static constexpr bool has_outermost_default_val = + Next::has_outermost_default_val; + static constexpr bool has_any_default_val = Next::has_any_default_val; + static constexpr bool has_nullable = Next::has_nullable; + + static inline const CoreType* unwrap_ptr( + const Opt* _p) noexcept { + return Next::unwrap_ptr(_p ? &_p->value() : nullptr); + } +}; + template - requires(rfl::internal::is_short_v || rfl::internal::is_positional_v || - rfl::internal::is_transparent_wrapper_v || - parsing::is_rename_v || parsing::is_skip_v || - parsing::is_commented_v) + requires((rfl::internal::is_short_v || rfl::internal::is_positional_v || + rfl::internal::is_transparent_wrapper_v || + parsing::is_rename_v || parsing::is_skip_v || + parsing::is_commented_v) && + !is_cli_opt_v) struct usage_peel { using Next = usage_peel, _outermost>; using CoreType = typename Next::CoreType; @@ -467,6 +503,7 @@ struct usage_peel { static constexpr bool is_deprecated = Next::is_deprecated; static constexpr std::string_view deprecation_message = Next::deprecation_message; + static constexpr std::string_view default_hint = Next::default_hint; static constexpr bool has_outermost_default_val = Next::has_outermost_default_val; static constexpr bool has_any_default_val = Next::has_any_default_val; @@ -485,6 +522,7 @@ struct usage_peel, _outermost> { static constexpr bool is_deprecated = Next::is_deprecated; static constexpr std::string_view deprecation_message = Next::deprecation_message; + static constexpr std::string_view default_hint = Next::default_hint; static constexpr bool has_outermost_default_val = _outermost; static constexpr bool has_any_default_val = true; static constexpr bool has_nullable = Next::has_nullable; @@ -502,6 +540,7 @@ struct usage_peel, _outermost> { static constexpr bool is_deprecated = Next::is_deprecated; static constexpr std::string_view deprecation_message = Next::deprecation_message; + static constexpr std::string_view default_hint = Next::default_hint; static constexpr bool has_outermost_default_val = Next::has_outermost_default_val; static constexpr bool has_any_default_val = Next::has_any_default_val; @@ -523,6 +562,7 @@ struct usage_peel { static constexpr bool is_deprecated = Next::is_deprecated; static constexpr std::string_view deprecation_message = Next::deprecation_message; + static constexpr std::string_view default_hint = Next::default_hint; static constexpr bool has_outermost_default_val = Next::has_outermost_default_val; static constexpr bool has_any_default_val = Next::has_any_default_val; @@ -545,6 +585,7 @@ struct usage_peel { static constexpr bool is_deprecated = Next::is_deprecated; static constexpr std::string_view deprecation_message = Next::deprecation_message; + static constexpr std::string_view default_hint = Next::default_hint; static constexpr bool has_outermost_default_val = Next::has_outermost_default_val; static constexpr bool has_any_default_val = Next::has_any_default_val; @@ -607,6 +648,11 @@ class UsageWalker { if constexpr (Peel::is_deprecated) { _arg.deprecation = std::string(Peel::deprecation_message); } + if constexpr (!Peel::default_hint.empty()) { + if (_arg.default_hint.empty()) { + _arg.default_hint = std::string(Peel::default_hint); + } + } if constexpr (Peel::has_outermost_default_val) { if (_default_ptr != nullptr) { _arg.required = false; @@ -909,6 +955,7 @@ class UsageWalker { _arg.kind = option.kind; _arg.implicit_value = std::string(option.implicit_value); _arg.is_list = option.is_list; + _arg.multi_token = option.multi_token; const bool pure_flag = options_->pure_flags && _arg.kind == OptionKind::flag && !_arg.positional; if (pure_flag) { @@ -916,10 +963,19 @@ class UsageWalker { } if (_default && !(pure_flag && *_default == "false")) { _arg.default_value = std::move(_default); + } else if (!_arg.default_hint.empty() && + !(pure_flag && _arg.default_hint == "false")) { + _arg.default_value = _arg.default_hint; } if (const auto grp = options_->find_group(_arg.name); !grp.empty()) { _arg.group = std::string(grp); } + if (const auto vn = options_->find_value_name(_arg.name); !vn.empty()) { + _arg.value = (vn.front() == '<' && vn.back() == '>') + ? std::string(vn) + : "<" + std::string(vn) + ">"; + _arg.has_custom_value_name = true; + } args_.emplace_back(std::move(_arg)); } @@ -948,7 +1004,7 @@ class UsageWalker { /// (ListDelimiter<"">), every occurrence is one item: "". inline std::string usage_value_to_string(const UsageArg& _arg, const std::optional _delimiter) { - if (!_arg.is_list || !_delimiter) { + if (_arg.has_custom_value_name || !_arg.is_list || !_delimiter) { return _arg.value; } const auto d = std::string(1, *_delimiter); @@ -979,7 +1035,7 @@ inline std::string usage_arg_to_string(const UsageArg& _arg, str += "[=" + value + "]"; break; default: - str += "=" + value; + str += "=" + value + (_arg.multi_token ? "..." : ""); break; } return str; diff --git a/tests/cli/test_opt_and_provided.cpp b/tests/cli/test_opt_and_provided.cpp new file mode 100644 index 000000000..9c0521cad --- /dev/null +++ b/tests/cli/test_opt_and_provided.cpp @@ -0,0 +1,174 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_opt_and_provided { + +using namespace rfl::cli::attr; + +struct FlatOpts { + rfl::cli::Opt, Short<"o">, Group<"Output">, + ValueName<"path">, Desc<"Write output to path">> + output_dir; + + rfl::cli::Opt, Short<"v">, Group<"General">, + Desc<"Verbose logging">> + verbose = false; + + rfl::cli::Opt, Group<"Optimizer">, ValueName<"n">, + DefaultHint<"200">, Desc<"Optimization runs">> + optimize_runs; + + rfl::cli::Opt>, Group<"General">, + MultiToken, ValueName<"items">, Desc<"Multiple items">> + items; + + rfl::cli::Opt, Group<"General">, Implicit<"all">, + Desc<"Show report">> + report; + + rfl::cli::Opt, Group<"General">, + Deprecated<"Use --optimize-runs", "Legacy runs">> + old_runs; + + rfl::cli::Opt, Hidden> secret = false; + + rfl::cli::Opt, Positional, Desc<"Input file">> + input; +}; + +using CliSettings = + rfl::Processors>; + +TEST(cli, test_opt_parsing_and_unwrap) { + const auto res = rfl::cli::read( + {"-v", "-o", "/tmp/out", "--optimize-runs", "200", "--items", "a", "b", + "--report", "--secret", "file.sol"}); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(rfl::unwrap(res->output_dir), std::optional("/tmp/out")); + EXPECT_TRUE(rfl::unwrap(res->verbose)); + EXPECT_EQ(rfl::unwrap(res->optimize_runs), std::optional(200)); + ASSERT_TRUE(rfl::unwrap(res->items).has_value()); + EXPECT_EQ(*rfl::unwrap(res->items), (std::vector{"a", "b"})); + EXPECT_EQ(rfl::unwrap(res->report), std::optional("all")); + EXPECT_TRUE(rfl::unwrap(res->secret)); + EXPECT_EQ(rfl::unwrap(res->input), std::optional("file.sol")); + + // Opt is transparent to JSON serialization too. + const auto json = rfl::json::write(*res); + EXPECT_NE(json.find("\"output_dir\":\"/tmp/out\""), std::string::npos) << json; +} + +TEST(cli, test_opt_usage_and_default_hint) { + const auto help = rfl::cli::usage("tool", true); + ASSERT_TRUE(help) << help.error().what(); + + EXPECT_NE(help->find("\nOutput:\n"), std::string::npos) << *help; + EXPECT_NE(help->find("-o, --output-dir="), std::string::npos) << *help; + EXPECT_NE(help->find("Write output to path"), std::string::npos) << *help; + + EXPECT_NE(help->find("\nOptimizer:\n"), std::string::npos) << *help; + EXPECT_NE(help->find("--optimize-runs="), std::string::npos) << *help; + EXPECT_NE(help->find("Optimization runs. Default: 200."), std::string::npos) + << *help; + + EXPECT_NE(help->find("--items=..."), std::string::npos) << *help; + EXPECT_NE(help->find("--report[=]"), std::string::npos) << *help; + EXPECT_NE(help->find("Without a value: all."), std::string::npos) << *help; + EXPECT_NE(help->find("Legacy runs. Deprecated: Use --optimize-runs."), + std::string::npos) + << *help; + // Hidden option omitted from usage. + EXPECT_EQ(help->find("secret"), std::string::npos) << *help; +} + +TEST(cli, test_opt_value_name_brackets_and_default_hint_optional) { + struct Config { + rfl::cli::Opt, DefaultHint<"42">, Desc<"Answer">> answer; + rfl::cli::Opt>, ValueName<"">> + include_path; + }; + const auto empty = rfl::cli::read({}); + ASSERT_TRUE(empty) << empty.error().what(); + EXPECT_FALSE(rfl::unwrap(empty->answer).has_value()); + + const auto given = rfl::cli::read({"--answer=42"}); + ASSERT_TRUE(given) << given.error().what(); + EXPECT_EQ(rfl::unwrap(given->answer), std::optional(42)); + + const auto help = rfl::cli::usage("app", true); + ASSERT_TRUE(help) << help.error().what(); + EXPECT_NE(help->find("Answer. Default: 42."), std::string::npos) << *help; + // Already bracketed value names are not double-wrapped. + EXPECT_NE(help->find("--include-path="), std::string::npos) << *help; + EXPECT_EQ(help->find("<>"), std::string::npos) << *help; +} + +TEST(cli, test_opt_multi_token_long_short_and_double_dash) { + struct PhaserLike { + rfl::cli::Opt>, MultiToken, + ValueName<"">> + population; + rfl::cli::Opt>, Short<"p">, + MultiToken> + files; + std::optional rounds; + rfl::cli::Opt>, Positional> + input_files; + }; + + const auto r1 = rfl::cli::read( + {"--population", "a", "afc", "xadd", "--rounds", "10", "--", "prog.yul"}); + ASSERT_TRUE(r1) << r1.error().what(); + ASSERT_TRUE(rfl::unwrap(r1->population).has_value()); + EXPECT_EQ(*rfl::unwrap(r1->population), + (std::vector{"a", "afc", "xadd"})); + EXPECT_EQ(r1->rounds, 10); + ASSERT_TRUE(rfl::unwrap(r1->input_files).has_value()); + EXPECT_EQ(*rfl::unwrap(r1->input_files), + (std::vector{"prog.yul"})); + + const auto r2 = rfl::cli::read( + {"--population", "a", "b", "--population=c", "-p", "f1", "f2"}); + ASSERT_TRUE(r2) << r2.error().what(); + EXPECT_EQ(*rfl::unwrap(r2->population), + (std::vector{"a", "b", "c"})); + EXPECT_EQ(*rfl::unwrap(r2->files), (std::vector{"f1", "f2"})); + + const auto help = rfl::cli::usage("yul-phaser", true); + ASSERT_TRUE(help) << help.error().what(); + EXPECT_NE(help->find("--population=..."), std::string::npos) + << *help; + EXPECT_NE(help->find("-p, --files=..."), std::string::npos) << *help; +} + +TEST(cli, test_read_detailed_tracks_explicitly_provided) { + const auto res = rfl::cli::read_detailed( + {"-v", "--optimize-runs", "200", "--verbose=false"}); + // Duplicate --verbose should still fail cleanly. + EXPECT_FALSE(res); + + const auto ok = rfl::cli::read_detailed( + {"-o", "dir", "--verbose=false", "--optimize-runs", "200", "in.sol"}); + ASSERT_TRUE(ok) << ok.error().what(); + // Even though --verbose was explicitly set to its default value `false`, + // was_provided("verbose") is true! + EXPECT_FALSE(rfl::unwrap(ok->value.verbose)); + EXPECT_TRUE(ok->was_provided("verbose")); + EXPECT_TRUE(ok->was_provided("output-dir")); + EXPECT_TRUE(ok->was_provided("optimize-runs")); + EXPECT_TRUE(ok->was_provided("input")); + EXPECT_FALSE(ok->was_provided("items")); + EXPECT_FALSE(ok->was_provided("report")); + EXPECT_FALSE(ok->was_provided("secret")); + EXPECT_EQ(ok->provided, (std::vector{"input", "optimize-runs", + "output-dir", "verbose"})); +} + +} // namespace test_opt_and_provided