Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ The `--` separator forces all subsequent tokens into positional:
./app --verbose -- --not-a-flag.txt
```

A token that starts with `-` and a digit or `.`, such as `-5`, `-1.5` or
`-1e3`, is a negative number, so it is read as a positional argument (or as
the value of a short option: `-n -5`). `-inf` and `-nan` start with a letter
and are read as short options; pass them after `--` or as `--offset=-inf`.

As in argparse, this changes if the struct has a short option whose name
looks like a number, such as `rfl::Short<"1", bool>` for `ls -1`. Then such a
token is a short option, and negative positional arguments need `--`:
`./app -1 -- -5`. Right after a short option, such a token is still read as
that option's value, as any other token is: `-n -1` sets `n` to `-1`.

## Short aliases

Wrap a field with `rfl::Short<"x", T>` to add a single-character alias:
Expand Down Expand Up @@ -109,7 +120,9 @@ struct Config {
Parsing proceeds in three stages:

1. **`parse_argv`** — categorizes raw tokens into `named`, `short_args`,
and `positional` buckets (`ParsedArgs` struct). No type information needed.
and `positional` buckets (`ParsedArgs` struct). No type information
needed, except that `rfl::cli::read` tells it whether a short option's
name looks like a number. On its own, it reads `-5` as a short option.
2. **`resolve_args`** — uses compile-time metadata from the target struct to
map short aliases to long names, reclaim values from bool short flags,
and merge positional arguments. Produces a flat `map<string, string>`.
Expand Down
51 changes: 36 additions & 15 deletions include/rfl/cli/parse_argv.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,15 @@ inline bool looks_like_option(std::string_view _token) noexcept {
&& _token[1] != '.';
}

/// Parses command-line arguments into categorized buckets.
/// Handles three types of arguments:
/// - Long options: --key=value or --flag (stored in `named`)
/// - Short options: -x value, -x=value, or -x (stored in `short_args`)
/// - Positional arguments: bare arguments not prefixed with dashes (stored in `positional`)
/// The special argument "--" forces all subsequent arguments to be treated as positional.
/// @param argc Number of command-line arguments
/// @param argv Array of command-line argument strings
/// @return A Result containing ParsedArgs with categorized arguments or an error
/// --key=value / --flag → named
/// -x value / -x=value / -x → short_args
/// bare arguments → positional
/// -- → everything after goes to positional
inline rfl::Result<ParsedArgs> parse_argv(int argc, char* argv[]) {
namespace internal {

/// Parses command-line arguments as parse_argv does. A token that looks like
/// a negative number (-5, -.5) is a positional argument unless
/// `_negative_numbers_are_options` is true, as it is when the target struct
/// has a short option whose name looks like a number (rfl::Short<"1", ...>).
/// Then such tokens are short options, as in argparse.
inline rfl::Result<ParsedArgs> parse_args(int argc, char* argv[],
bool _negative_numbers_are_options) {
if (argc < 0 || (argc > 0 && !argv)) {
return error("Invalid argc/argv.");
}
Expand Down Expand Up @@ -91,7 +86,11 @@ inline rfl::Result<ParsedArgs> parse_argv(int argc, char* argv[]) {
}

// Short argument: -x value, -x=value, or -x (bool).
if (arg_raw.size() >= 2 && arg_raw[0] == '-') {
// A negative number such as -5 or -.5 is not an option; it falls through
// to positional, unless the struct has a short option such as -1.
if (looks_like_option(arg_raw)
|| (_negative_numbers_are_options && arg_raw.size() >= 2
&& arg_raw[0] == '-')) {
const auto arg = arg_raw.substr(1);
const auto eq = arg.find('=');

Expand Down Expand Up @@ -121,6 +120,28 @@ inline rfl::Result<ParsedArgs> parse_argv(int argc, char* argv[]) {
return result;
}

} // namespace internal

/// Parses command-line arguments into categorized buckets.
/// Handles three types of arguments:
/// - Long options: --key=value or --flag (stored in `named`)
/// - Short options: -x value, -x=value, or -x (stored in `short_args`)
/// - Positional arguments: bare arguments not prefixed with dashes (stored in `positional`)
/// The special argument "--" forces all subsequent arguments to be treated as positional.
/// Without the target struct, a token such as -5 or -.5 is a short option.
/// rfl::cli::read, which knows the struct, reads it as a negative number
/// unless the struct has a short option like rfl::Short<"1", ...>.
/// @param argc Number of command-line arguments
/// @param argv Array of command-line argument strings
/// @return A Result containing ParsedArgs with categorized arguments or an error
/// --key=value / --flag → named
/// -x value / -x=value / -x → short_args
/// bare arguments → positional
/// -- → everything after goes to positional
inline rfl::Result<ParsedArgs> parse_argv(int argc, char* argv[]) {
return internal::parse_args(argc, argv, true);
}

/// Parses wide-character command-line arguments into categorized buckets.
/// Converts each wide string to UTF-8 and delegates to the narrow parse_argv.
/// @param argc Number of wide-character command-line arguments
Expand Down
6 changes: 5 additions & 1 deletion include/rfl/cli/read.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ namespace rfl::cli {
template <class T, class... Ps>
rfl::Result<T> read(int argc, char* argv[]) {
using ProcessorsType = Processors<SnakeCaseToKebabCase, Ps...>;
return parse_argv(argc, argv)
using NT = rfl::internal::processed_t<T, ProcessorsType>;
constexpr bool negative_numbers_are_options =
internal::has_numeric_short_name<NT>(
std::make_index_sequence<NT::size()>{});
return internal::parse_args(argc, argv, negative_numbers_are_options)
.and_then(resolve_args<T, ProcessorsType>)
.and_then([](auto _args) -> rfl::Result<T> {
const auto r = Reader();
Expand Down
16 changes: 16 additions & 0 deletions include/rfl/cli/resolve_args.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include <map>
#include <set>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "../Result.hpp"
Expand Down Expand Up @@ -148,6 +150,20 @@ void collect_short_bool_names(
std::index_sequence<>
) {}

/// Returns true if a field of NamedTupleType has a short name that looks
/// like a number, such as rfl::Short<"1", ...>. Then, as in argparse,
/// parse_argv treats tokens like -5 and -.5 as short options rather than as
/// negative numbers.
template <class NamedTupleType, size_t... _is>
consteval bool has_numeric_short_name(std::index_sequence<_is...>) {
const auto is_numeric = [](std::string_view _name) {
return !_name.empty()
&& ((_name[0] >= '0' && _name[0] <= '9') || _name[0] == '.');
};
return (is_numeric(get_short_name<NamedTupleType, _is>().string_view())
|| ...);
}

} // namespace internal

/// Resolves ParsedArgs into a flat key-value map using compile-time
Expand Down
110 changes: 110 additions & 0 deletions tests/cli/test_positional.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#include <gtest/gtest.h>
#include <rfl.hpp>
#include <rfl/cli.hpp>
#include <cmath>
#include <map>
#include <optional>
#include <string>

namespace test_positional {
Expand Down Expand Up @@ -95,4 +98,111 @@ TEST(cli, test_positional_optional_missing) {
EXPECT_FALSE(result.value().optional_file().has_value());
}

struct NumberConfig {
rfl::Positional<int> count;
rfl::Positional<double> offset;
};

TEST(cli, test_positional_negative_numbers) {
const char* args[] = {"program", "-5", "-.5"};
const auto result = rfl::cli::read<NumberConfig>(3, const_cast<char**>(args));
ASSERT_TRUE(result) << result.error().what();
EXPECT_EQ(result.value().count(), -5);
EXPECT_DOUBLE_EQ(result.value().offset(), -0.5);
}

TEST(cli, test_positional_negative_number_forms) {
const auto read = [](const char* _count, const char* _offset) {
const char* args[] = {"program", _count, _offset};
return rfl::cli::read<NumberConfig>(3, const_cast<char**>(args));
};

const auto a = read("-10", "-1.5");
ASSERT_TRUE(a) << a.error().what();
EXPECT_EQ(a.value().count(), -10);
EXPECT_DOUBLE_EQ(a.value().offset(), -1.5);

const auto b = read("-0", "-1e3");
ASSERT_TRUE(b) << b.error().what();
EXPECT_EQ(b.value().count(), 0);
EXPECT_DOUBLE_EQ(b.value().offset(), -1000.0);
}

// -inf and -nan start with a letter, so they are short options. They need
// "--" (or --offset=-inf).
TEST(cli, test_positional_negative_infinity_needs_separator) {
const char* args[] = {"program", "-5", "-inf"};
const auto result = rfl::cli::read<NumberConfig>(3, const_cast<char**>(args));
ASSERT_FALSE(result);
EXPECT_TRUE(std::string(result.error().what())
.starts_with("Unknown short argument: -i"))
<< result.error().what();

const char* separated[] = {"program", "--", "-5", "-inf"};
const auto r =
rfl::cli::read<NumberConfig>(4, const_cast<char**>(separated));
ASSERT_TRUE(r) << r.error().what();
EXPECT_EQ(r.value().count(), -5);
EXPECT_TRUE(std::isinf(r.value().offset()));
EXPECT_LT(r.value().offset(), 0.0);
}

struct NegativeOptions {
int x;
rfl::Short<"n", int> n;
};

TEST(cli, test_negative_option_values) {
const char* args[] = {"program", "--x=-5", "-n", "-7"};
const auto result =
rfl::cli::read<NegativeOptions>(4, const_cast<char**>(args));
ASSERT_TRUE(result) << result.error().what();
EXPECT_EQ(result.value().x, -5);
EXPECT_EQ(result.value().n(), -7);

const char* with_eq[] = {"program", "--x=-5", "-n=-7"};
const auto r = rfl::cli::read<NegativeOptions>(3, const_cast<char**>(with_eq));
ASSERT_TRUE(r) << r.error().what();
EXPECT_EQ(r.value().n(), -7);
}

// As in argparse: if a short option's name looks like a number, tokens that
// look like negative numbers are short options.
struct Ls {
rfl::Short<"1", std::optional<bool>> one_per_line;
rfl::Positional<std::optional<int>> count;
};

TEST(cli, test_digit_short_option) {
const char* args[] = {"ls", "-1"};
const auto result = rfl::cli::read<Ls>(2, const_cast<char**>(args));
ASSERT_TRUE(result) << result.error().what();
EXPECT_EQ(result.value().one_per_line(), std::optional<bool>(true));
EXPECT_FALSE(result.value().count().has_value());
}

TEST(cli, test_digit_short_option_makes_negative_numbers_options) {
const char* args[] = {"ls", "-5"};
const auto result = rfl::cli::read<Ls>(2, const_cast<char**>(args));
ASSERT_FALSE(result);
EXPECT_EQ(std::string(result.error().what()), "Unknown short argument: -5");

const char* separated[] = {"ls", "-1", "--", "-5"};
const auto r = rfl::cli::read<Ls>(4, const_cast<char**>(separated));
ASSERT_TRUE(r) << r.error().what();
EXPECT_EQ(r.value().one_per_line(), std::optional<bool>(true));
EXPECT_EQ(r.value().count(), std::optional<int>(-5));
}

// parse_argv does not know the struct, so it reads such tokens as short
// options. Only rfl::cli::read applies the rule.
TEST(cli, test_parse_argv_reads_negative_numbers_as_options) {
const char* args[] = {"program", "-1", "x", "-5"};
const auto parsed = rfl::cli::parse_argv(4, const_cast<char**>(args));
ASSERT_TRUE(parsed) << parsed.error().what();
EXPECT_EQ(parsed.value().short_args,
(std::map<std::string, std::string>{{"1", "x"}, {"5", ""}}));
EXPECT_TRUE(parsed.value().positional.empty());
}

} // namespace test_positional