ArgumentParser: Return leftover arguments from parse()

This commit is contained in:
apio 2023-03-29 22:07:42 +02:00
parent 75c48e996a
commit e1c03150f8
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 7 additions and 3 deletions

View File

@ -15,7 +15,7 @@ class ArgumentParser
Result<void> add_value_argument(StringView& out, char short_flag, StringView long_flag, bool value_required); Result<void> add_value_argument(StringView& out, char short_flag, StringView long_flag, bool value_required);
Result<void> add_value_argument(StringView& out, char short_flag, StringView long_flag, StringView fallback); Result<void> add_value_argument(StringView& out, char short_flag, StringView long_flag, StringView fallback);
void parse(int argc, char* const* argv); Result<Vector<StringView>> parse(int argc, char* const* argv);
private: private:
struct PositionalArgument struct PositionalArgument

View File

@ -49,10 +49,12 @@ static bool looks_like_long_flag(StringView arg)
return arg.length() > 2 && arg[0] == '-' && arg[1] == '-'; return arg.length() > 2 && arg[0] == '-' && arg[1] == '-';
} }
void ArgumentParser::parse(int argc, char* const* argv) Result<Vector<StringView>> ArgumentParser::parse(int argc, char* const* argv)
{ {
StringView program_name = argv[0]; StringView program_name = argv[0];
Vector<StringView> leftovers;
Option<ValueArgument> current_value_argument = {}; Option<ValueArgument> current_value_argument = {};
bool is_parsing_value_argument = false; bool is_parsing_value_argument = false;
@ -144,7 +146,7 @@ void ArgumentParser::parse(int argc, char* const* argv)
Option<PositionalArgument> current = m_positional_args.try_dequeue(); Option<PositionalArgument> current = m_positional_args.try_dequeue();
if (!current.has_value()) if (!current.has_value())
{ {
fprintf(stderr, "%s: unused argument '%s'\n", program_name.chars(), arg.chars()); TRY(leftovers.try_append(arg));
continue; continue;
} }
@ -172,4 +174,6 @@ void ArgumentParser::parse(int argc, char* const* argv)
} }
else { *arg.out = arg.fallback; } else { *arg.out = arg.fallback; }
} }
return leftovers;
} }