mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 23:07:35 +00:00
Userland+AK: Stop using getopt() for ArgsParser
This commit moves the implementation of getopt into AK, and converts its API to understand and use StringView instead of char*. Everything else is caught in the crossfire of making Option::accept_value() take a StringView instead of a char const*. With this, we must now pass a Span<StringView> to ArgsParser::parse(), applications using LibMain are unaffected, but anything not using that or taking its own argc/argv has to construct a Vector<StringView> for this method.
This commit is contained in:
parent
b2b851b361
commit
db886fe18b
43 changed files with 673 additions and 584 deletions
|
@ -4,6 +4,7 @@
|
|||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <AK/OptionParser.h>
|
||||
#include <AK/StringView.h>
|
||||
#include <AK/Vector.h>
|
||||
#include <getopt.h>
|
||||
|
@ -20,338 +21,74 @@ char* optarg = nullptr;
|
|||
// POSIX says, "When an element of argv[] contains multiple option characters,
|
||||
// it is unspecified how getopt() determines which options have already been
|
||||
// processed". Well, this is how we do it.
|
||||
static size_t s_index_into_multioption_argument = 0;
|
||||
|
||||
[[gnu::format(printf, 1, 2)]] static inline void report_error(char const* format, ...)
|
||||
{
|
||||
if (!opterr)
|
||||
return;
|
||||
|
||||
fputs("\033[31m", stderr);
|
||||
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
vfprintf(stderr, format, ap);
|
||||
va_end(ap);
|
||||
|
||||
fputs("\033[0m\n", stderr);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
class OptionParser {
|
||||
public:
|
||||
OptionParser(int argc, char* const* argv, StringView short_options, option const* long_options, int* out_long_option_index = nullptr);
|
||||
int getopt();
|
||||
|
||||
private:
|
||||
bool lookup_short_option(char option, int& needs_value) const;
|
||||
int handle_short_option();
|
||||
|
||||
option const* lookup_long_option(char* raw) const;
|
||||
int handle_long_option();
|
||||
|
||||
void shift_argv();
|
||||
bool find_next_option();
|
||||
|
||||
StringView current_arg() const
|
||||
{
|
||||
auto const* arg_ptr = m_argv[m_arg_index];
|
||||
if (arg_ptr == NULL)
|
||||
return {};
|
||||
return { arg_ptr, strlen(arg_ptr) };
|
||||
}
|
||||
|
||||
size_t m_argc { 0 };
|
||||
char* const* m_argv { nullptr };
|
||||
StringView m_short_options;
|
||||
option const* m_long_options { nullptr };
|
||||
int* m_out_long_option_index { nullptr };
|
||||
bool m_stop_on_first_non_option { false };
|
||||
|
||||
size_t m_arg_index { 0 };
|
||||
size_t m_consumed_args { 0 };
|
||||
};
|
||||
|
||||
OptionParser::OptionParser(int argc, char* const* argv, StringView short_options, option const* long_options, int* out_long_option_index)
|
||||
: m_argc(argc)
|
||||
, m_argv(argv)
|
||||
, m_short_options(short_options)
|
||||
, m_long_options(long_options)
|
||||
, m_out_long_option_index(out_long_option_index)
|
||||
{
|
||||
// In the following case:
|
||||
// $ foo bar -o baz
|
||||
// we want to parse the option (-o baz) first, and leave the argument (bar)
|
||||
// in argv after we return -1 when invoked the second time. So we reorder
|
||||
// argv to put options first and positional arguments next. To turn this
|
||||
// behavior off, start the short options spec with a "+". This is a GNU
|
||||
// extension that we support.
|
||||
m_stop_on_first_non_option = short_options.starts_with('+');
|
||||
|
||||
// See if we should reset the internal state.
|
||||
if (optreset || optind == 0) {
|
||||
optreset = 0;
|
||||
optind = 1;
|
||||
s_index_into_multioption_argument = 0;
|
||||
}
|
||||
|
||||
optopt = 0;
|
||||
optarg = nullptr;
|
||||
}
|
||||
|
||||
int OptionParser::getopt()
|
||||
{
|
||||
bool should_reorder_argv = !m_stop_on_first_non_option;
|
||||
int res = -1;
|
||||
|
||||
bool found_an_option = find_next_option();
|
||||
auto arg = current_arg();
|
||||
|
||||
if (!found_an_option) {
|
||||
res = -1;
|
||||
if (arg == "--")
|
||||
m_consumed_args = 1;
|
||||
else
|
||||
m_consumed_args = 0;
|
||||
} else {
|
||||
// Alright, so we have an option on our hands!
|
||||
bool is_long_option = arg.starts_with("--"sv);
|
||||
if (is_long_option)
|
||||
res = handle_long_option();
|
||||
else
|
||||
res = handle_short_option();
|
||||
|
||||
// If we encountered an error, return immediately.
|
||||
if (res == '?')
|
||||
return '?';
|
||||
}
|
||||
|
||||
if (should_reorder_argv)
|
||||
shift_argv();
|
||||
else
|
||||
VERIFY(optind == static_cast<int>(m_arg_index));
|
||||
optind += m_consumed_args;
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
bool OptionParser::lookup_short_option(char option, int& needs_value) const
|
||||
{
|
||||
Vector<StringView> parts = m_short_options.split_view(option, SplitBehavior::KeepEmpty);
|
||||
|
||||
VERIFY(parts.size() <= 2);
|
||||
if (parts.size() < 2) {
|
||||
// Haven't found the option in the spec.
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parts[1].starts_with("::"sv)) {
|
||||
// If an option is followed by two colons, it optionally accepts an
|
||||
// argument.
|
||||
needs_value = optional_argument;
|
||||
} else if (parts[1].starts_with(':')) {
|
||||
// If it's followed by one colon, it requires an argument.
|
||||
needs_value = required_argument;
|
||||
} else {
|
||||
// Otherwise, it doesn't accept arguments.
|
||||
needs_value = no_argument;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int OptionParser::handle_short_option()
|
||||
{
|
||||
StringView arg = current_arg();
|
||||
VERIFY(arg.starts_with('-'));
|
||||
|
||||
if (s_index_into_multioption_argument == 0) {
|
||||
// Just starting to parse this argument, skip the "-".
|
||||
s_index_into_multioption_argument = 1;
|
||||
}
|
||||
char option = arg[s_index_into_multioption_argument];
|
||||
s_index_into_multioption_argument++;
|
||||
|
||||
int needs_value = no_argument;
|
||||
bool ok = lookup_short_option(option, needs_value);
|
||||
if (!ok) {
|
||||
optopt = option;
|
||||
report_error("Unrecognized option \033[1m-%c\033[22m", option);
|
||||
return '?';
|
||||
}
|
||||
|
||||
// Let's see if we're at the end of this argument already.
|
||||
if (s_index_into_multioption_argument < arg.length()) {
|
||||
// This not yet the end.
|
||||
if (needs_value == no_argument) {
|
||||
optarg = nullptr;
|
||||
m_consumed_args = 0;
|
||||
} else {
|
||||
// Treat the rest of the argument as the value, the "-ovalue"
|
||||
// syntax.
|
||||
optarg = m_argv[m_arg_index] + s_index_into_multioption_argument;
|
||||
// Next time, process the next argument.
|
||||
s_index_into_multioption_argument = 0;
|
||||
m_consumed_args = 1;
|
||||
}
|
||||
} else {
|
||||
s_index_into_multioption_argument = 0;
|
||||
if (needs_value != required_argument) {
|
||||
optarg = nullptr;
|
||||
m_consumed_args = 1;
|
||||
} else if (m_arg_index + 1 < m_argc) {
|
||||
// Treat the next argument as a value, the "-o value" syntax.
|
||||
optarg = m_argv[m_arg_index + 1];
|
||||
m_consumed_args = 2;
|
||||
} else {
|
||||
report_error("Missing value for option \033[1m-%c\033[22m", option);
|
||||
return '?';
|
||||
}
|
||||
}
|
||||
|
||||
return option;
|
||||
}
|
||||
|
||||
option const* OptionParser::lookup_long_option(char* raw) const
|
||||
{
|
||||
StringView arg { raw, strlen(raw) };
|
||||
|
||||
for (size_t index = 0; m_long_options[index].name; index++) {
|
||||
auto& option = m_long_options[index];
|
||||
StringView name { option.name, strlen(option.name) };
|
||||
|
||||
if (!arg.starts_with(name))
|
||||
continue;
|
||||
|
||||
// It would be better to not write out the index at all unless we're
|
||||
// sure we've found the right option, but whatever.
|
||||
if (m_out_long_option_index)
|
||||
*m_out_long_option_index = index;
|
||||
|
||||
// Can either be "--option" or "--option=value".
|
||||
if (arg.length() == name.length()) {
|
||||
optarg = nullptr;
|
||||
return &option;
|
||||
}
|
||||
VERIFY(arg.length() > name.length());
|
||||
if (arg[name.length()] == '=') {
|
||||
optarg = raw + name.length() + 1;
|
||||
return &option;
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int OptionParser::handle_long_option()
|
||||
{
|
||||
VERIFY(current_arg().starts_with("--"sv));
|
||||
|
||||
// We cannot set optopt to anything sensible for long options, so set it to 0.
|
||||
optopt = 0;
|
||||
|
||||
auto* option = lookup_long_option(m_argv[m_arg_index] + 2);
|
||||
if (!option) {
|
||||
report_error("Unrecognized option \033[1m%s\033[22m", m_argv[m_arg_index]);
|
||||
return '?';
|
||||
}
|
||||
// lookup_long_option() will also set optarg if the value of the option is
|
||||
// specified using "--option=value" syntax.
|
||||
|
||||
// Figure out whether this option needs and/or has a value (also called "an
|
||||
// argument", but let's not call it that to distinguish it from argv
|
||||
// elements).
|
||||
switch (option->has_arg) {
|
||||
case no_argument:
|
||||
if (optarg) {
|
||||
report_error("Option \033[1m--%s\033[22m doesn't accept an argument", option->name);
|
||||
return '?';
|
||||
}
|
||||
m_consumed_args = 1;
|
||||
break;
|
||||
case optional_argument:
|
||||
m_consumed_args = 1;
|
||||
break;
|
||||
case required_argument:
|
||||
if (optarg) {
|
||||
// Value specified using "--option=value" syntax.
|
||||
m_consumed_args = 1;
|
||||
} else if (m_arg_index + 1 < m_argc) {
|
||||
// Treat the next argument as a value in "--option value" syntax.
|
||||
optarg = m_argv[m_arg_index + 1];
|
||||
m_consumed_args = 2;
|
||||
} else {
|
||||
report_error("Missing value for option \033[1m--%s\033[22m", option->name);
|
||||
return '?';
|
||||
}
|
||||
break;
|
||||
default:
|
||||
VERIFY_NOT_REACHED();
|
||||
}
|
||||
|
||||
// Now that we've figured the value out, see about reporting this option to
|
||||
// our caller.
|
||||
if (option->flag) {
|
||||
*option->flag = option->val;
|
||||
return 0;
|
||||
}
|
||||
return option->val;
|
||||
}
|
||||
|
||||
void OptionParser::shift_argv()
|
||||
{
|
||||
// We've just parsed an option (which perhaps has a value).
|
||||
// Put the option (along with it value, if any) in front of other arguments.
|
||||
VERIFY(optind <= static_cast<int>(m_arg_index));
|
||||
|
||||
if (optind == static_cast<int>(m_arg_index) || m_consumed_args == 0) {
|
||||
// Nothing to do!
|
||||
return;
|
||||
}
|
||||
|
||||
auto new_argv = const_cast<char**>(m_argv);
|
||||
char* buffer[m_consumed_args];
|
||||
memcpy(buffer, &new_argv[m_arg_index], sizeof(char*) * m_consumed_args);
|
||||
memmove(&new_argv[optind + m_consumed_args], &new_argv[optind], sizeof(char*) * (m_arg_index - optind));
|
||||
memcpy(&new_argv[optind], buffer, sizeof(char*) * m_consumed_args);
|
||||
}
|
||||
|
||||
bool OptionParser::find_next_option()
|
||||
{
|
||||
for (m_arg_index = optind; m_arg_index < m_argc && m_argv[m_arg_index]; m_arg_index++) {
|
||||
StringView arg = current_arg();
|
||||
// Anything that doesn't start with a "-" is not an option.
|
||||
// As a special case, a single "-" is not an option either.
|
||||
// (It's typically used by programs to refer to stdin).
|
||||
if (!arg.starts_with('-') || arg == "-") {
|
||||
if (m_stop_on_first_non_option)
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// As another special case, a "--" is not an option either, and we stop
|
||||
// looking for further options if we encounter it.
|
||||
if (arg == "--")
|
||||
return false;
|
||||
// Otherwise, we have found an option!
|
||||
return true;
|
||||
}
|
||||
|
||||
// Reached the end and still found no options.
|
||||
return false;
|
||||
}
|
||||
|
||||
Vector<StringView> s_args;
|
||||
OptionParser s_parser;
|
||||
}
|
||||
|
||||
int getopt(int argc, char* const* argv, char const* short_options)
|
||||
{
|
||||
option dummy { nullptr, 0, nullptr, 0 };
|
||||
OptionParser parser { argc, argv, { short_options, strlen(short_options) }, &dummy };
|
||||
return parser.getopt();
|
||||
s_args.clear_with_capacity();
|
||||
s_args.ensure_capacity(argc);
|
||||
for (auto i = 1; i < argc; ++i)
|
||||
s_args.append({ argv[i], strlen(argv[i]) });
|
||||
|
||||
if (optind == 0 || optreset == 1) {
|
||||
s_parser.reset_state();
|
||||
optind = 1;
|
||||
optreset = 0;
|
||||
}
|
||||
|
||||
auto result = s_parser.getopt(s_args.span(), { short_options, strlen(short_options) }, {}, {});
|
||||
|
||||
optind += result.consumed_args;
|
||||
optarg = result.optarg_value.map([](auto x) { return const_cast<char*>(x.characters_without_null_termination()); }).value_or(optarg);
|
||||
optopt = result.optopt_value.value_or(optopt);
|
||||
return result.result;
|
||||
}
|
||||
|
||||
int getopt_long(int argc, char* const* argv, char const* short_options, const struct option* long_options, int* out_long_option_index)
|
||||
{
|
||||
OptionParser parser { argc, argv, { short_options, strlen(short_options) }, long_options, out_long_option_index };
|
||||
return parser.getopt();
|
||||
s_args.clear_with_capacity();
|
||||
s_args.ensure_capacity(argc);
|
||||
for (auto i = 1; i < argc; ++i)
|
||||
s_args.append({ argv[i], strlen(argv[i]) });
|
||||
|
||||
size_t long_option_count = 0;
|
||||
for (auto option = long_options; option && option->name; option += 1)
|
||||
long_option_count++;
|
||||
|
||||
Vector<OptionParser::Option> translated_long_options;
|
||||
translated_long_options.ensure_capacity(long_option_count);
|
||||
for (size_t i = 0; i < long_option_count; ++i) {
|
||||
auto option = &long_options[i];
|
||||
|
||||
translated_long_options.append(OptionParser::Option {
|
||||
.name = { option->name, strlen(option->name) },
|
||||
.requirement = option->has_arg == no_argument
|
||||
? AK::OptionParser::ArgumentRequirement::NoArgument
|
||||
: option->has_arg == optional_argument
|
||||
? AK::OptionParser::ArgumentRequirement::HasOptionalArgument
|
||||
: AK::OptionParser::ArgumentRequirement::HasRequiredArgument,
|
||||
.flag = option->flag,
|
||||
.val = option->val,
|
||||
});
|
||||
}
|
||||
|
||||
if (optind == 0 || optreset == 1) {
|
||||
s_parser.reset_state();
|
||||
optind = 1;
|
||||
optreset = 0;
|
||||
}
|
||||
|
||||
auto result = s_parser.getopt(
|
||||
s_args.span(),
|
||||
{ short_options, strlen(short_options) },
|
||||
translated_long_options.span(),
|
||||
out_long_option_index ? *out_long_option_index : Optional<int&>());
|
||||
|
||||
optind += result.consumed_args;
|
||||
optarg = result.optarg_value.map([](auto x) { return const_cast<char*>(x.characters_without_null_termination()); }).value_or(optarg);
|
||||
optopt = result.optopt_value.value_or(optopt);
|
||||
return result.result;
|
||||
}
|
||||
|
|
|
@ -7,24 +7,15 @@
|
|||
|
||||
#include <AK/Format.h>
|
||||
#include <AK/JsonObject.h>
|
||||
#include <AK/OptionParser.h>
|
||||
#include <AK/StringBuilder.h>
|
||||
#include <LibCore/ArgsParser.h>
|
||||
#include <LibCore/Version.h>
|
||||
#include <getopt.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
static Optional<double> convert_to_double(char const* s)
|
||||
{
|
||||
char* p;
|
||||
double v = strtod(s, &p);
|
||||
if (isnan(v) || p == s)
|
||||
return {};
|
||||
return v;
|
||||
}
|
||||
|
||||
namespace Core {
|
||||
|
||||
ArgsParser::ArgsParser()
|
||||
|
@ -34,16 +25,18 @@ ArgsParser::ArgsParser()
|
|||
add_option(m_perform_autocomplete, "Perform autocompletion", "complete", 0, OptionHideMode::CommandLineAndMarkdown);
|
||||
}
|
||||
|
||||
bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_behavior)
|
||||
bool ArgsParser::parse(Span<StringView> arguments, FailureBehavior failure_behavior)
|
||||
{
|
||||
auto fail = [this, argv, failure_behavior] {
|
||||
auto fail = [this, name = arguments[0], failure_behavior] {
|
||||
if (failure_behavior == FailureBehavior::PrintUsage || failure_behavior == FailureBehavior::PrintUsageAndExit)
|
||||
print_usage(stderr, argv[0]);
|
||||
print_usage(stderr, name);
|
||||
if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
|
||||
exit(1);
|
||||
};
|
||||
|
||||
Vector<option> long_options;
|
||||
OptionParser parser;
|
||||
|
||||
Vector<OptionParser::Option> long_options;
|
||||
StringBuilder short_options_builder;
|
||||
|
||||
if (m_stop_on_first_non_option)
|
||||
|
@ -51,16 +44,16 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha
|
|||
|
||||
int index_of_found_long_option = -1;
|
||||
|
||||
// Tell getopt() to reset its internal state, and start scanning from optind = 1.
|
||||
// We could also set optreset = 1, but the host platform may not support that.
|
||||
optind = 0;
|
||||
|
||||
for (size_t i = 0; i < m_options.size(); i++) {
|
||||
auto& opt = m_options[i];
|
||||
if (opt.long_name) {
|
||||
option long_opt {
|
||||
opt.long_name,
|
||||
opt.argument_mode == OptionArgumentMode::Required ? required_argument : (opt.argument_mode == OptionArgumentMode::Optional ? optional_argument : no_argument),
|
||||
OptionParser::Option long_opt {
|
||||
{ opt.long_name, strlen(opt.long_name) },
|
||||
opt.argument_mode == OptionArgumentMode::Required
|
||||
? OptionParser::ArgumentRequirement::HasRequiredArgument
|
||||
: opt.argument_mode == OptionArgumentMode::Optional
|
||||
? OptionParser::ArgumentRequirement::HasOptionalArgument
|
||||
: OptionParser::ArgumentRequirement::NoArgument,
|
||||
&index_of_found_long_option,
|
||||
static_cast<int>(i)
|
||||
};
|
||||
|
@ -75,16 +68,20 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha
|
|||
short_options_builder.append(':');
|
||||
}
|
||||
}
|
||||
long_options.append({ 0, 0, 0, 0 });
|
||||
|
||||
auto short_options = short_options_builder.to_deprecated_string();
|
||||
|
||||
size_t option_index = 1;
|
||||
while (true) {
|
||||
int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
|
||||
auto result = parser.getopt(arguments.slice(1), short_options, long_options, {});
|
||||
option_index += result.consumed_args;
|
||||
|
||||
auto c = result.result;
|
||||
if (c == -1) {
|
||||
// We have reached the end.
|
||||
break;
|
||||
} else if (c == '?') {
|
||||
}
|
||||
|
||||
if (c == '?') {
|
||||
// There was an error, and getopt() has already
|
||||
// printed its error message.
|
||||
fail();
|
||||
|
@ -106,7 +103,7 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha
|
|||
}
|
||||
VERIFY(found_option);
|
||||
|
||||
char const* arg = found_option->argument_mode != OptionArgumentMode::None ? optarg : nullptr;
|
||||
StringView arg = found_option->argument_mode != OptionArgumentMode::None ? result.optarg_value.value_or({}) : StringView {};
|
||||
if (!found_option->accept_value(arg)) {
|
||||
warnln("\033[31mInvalid value for option \033[1m{}\033[22m\033[0m", found_option->name_for_display());
|
||||
fail();
|
||||
|
@ -125,14 +122,14 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha
|
|||
}
|
||||
|
||||
if (m_show_help) {
|
||||
print_usage(stdout, argv[0]);
|
||||
print_usage(stdout, arguments[0]);
|
||||
if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
|
||||
exit(0);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (m_perform_autocomplete) {
|
||||
autocomplete(stdout, { argv[0], strlen(argv[0]) }, ReadonlySpan<char const*> { argv + optind, static_cast<size_t>(argc - optind) });
|
||||
autocomplete(stdout, arguments[0], arguments.slice(option_index));
|
||||
if (failure_behavior == FailureBehavior::Exit || failure_behavior == FailureBehavior::PrintUsageAndExit)
|
||||
exit(0);
|
||||
return false;
|
||||
|
@ -140,7 +137,7 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha
|
|||
|
||||
// Now let's parse positional arguments.
|
||||
|
||||
int values_left = argc - optind;
|
||||
int values_left = arguments.size() - option_index;
|
||||
Vector<int, 16> num_values_for_arg;
|
||||
num_values_for_arg.resize(m_positional_args.size(), true);
|
||||
int total_values_required = 0;
|
||||
|
@ -174,7 +171,7 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha
|
|||
for (size_t i = 0; i < m_positional_args.size(); i++) {
|
||||
auto& arg = m_positional_args[i];
|
||||
for (int j = 0; j < num_values_for_arg[i]; j++) {
|
||||
char const* value = argv[optind++];
|
||||
StringView value = arguments[option_index++];
|
||||
if (!arg.accept_value(value)) {
|
||||
warnln("Invalid value for argument {}", arg.name);
|
||||
fail();
|
||||
|
@ -186,7 +183,7 @@ bool ArgsParser::parse(int argc, char* const* argv, FailureBehavior failure_beha
|
|||
return true;
|
||||
}
|
||||
|
||||
void ArgsParser::print_usage(FILE* file, char const* argv0)
|
||||
void ArgsParser::print_usage(FILE* file, StringView argv0)
|
||||
{
|
||||
char const* env_preference = getenv("ARGSPARSER_EMIT_MARKDOWN");
|
||||
if (env_preference != nullptr && env_preference[0] == '1' && env_preference[1] == 0) {
|
||||
|
@ -196,7 +193,7 @@ void ArgsParser::print_usage(FILE* file, char const* argv0)
|
|||
}
|
||||
}
|
||||
|
||||
void ArgsParser::print_usage_terminal(FILE* file, char const* argv0)
|
||||
void ArgsParser::print_usage_terminal(FILE* file, StringView argv0)
|
||||
{
|
||||
out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
|
||||
|
||||
|
@ -272,7 +269,7 @@ void ArgsParser::print_usage_terminal(FILE* file, char const* argv0)
|
|||
}
|
||||
}
|
||||
|
||||
void ArgsParser::print_usage_markdown(FILE* file, char const* argv0)
|
||||
void ArgsParser::print_usage_markdown(FILE* file, StringView argv0)
|
||||
{
|
||||
outln(file, "## Name\n\n{}", argv0);
|
||||
|
||||
|
@ -383,7 +380,7 @@ void ArgsParser::add_ignored(char const* long_name, char short_name, OptionHideM
|
|||
long_name,
|
||||
short_name,
|
||||
nullptr,
|
||||
[](char const*) {
|
||||
[](StringView) {
|
||||
return true;
|
||||
},
|
||||
hide_mode,
|
||||
|
@ -399,8 +396,8 @@ void ArgsParser::add_option(bool& value, char const* help_string, char const* lo
|
|||
long_name,
|
||||
short_name,
|
||||
nullptr,
|
||||
[&value](char const* s) {
|
||||
VERIFY(s == nullptr);
|
||||
[&value](StringView s) {
|
||||
VERIFY(s.is_empty());
|
||||
value = true;
|
||||
return true;
|
||||
},
|
||||
|
@ -417,8 +414,9 @@ void ArgsParser::add_option(char const*& value, char const* help_string, char co
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&value](char const* s) {
|
||||
value = s;
|
||||
[&value](StringView s) {
|
||||
VERIFY(s.length() == strlen(s.characters_without_null_termination()));
|
||||
value = s.characters_without_null_termination();
|
||||
return true;
|
||||
},
|
||||
hide_mode,
|
||||
|
@ -434,7 +432,7 @@ void ArgsParser::add_option(DeprecatedString& value, char const* help_string, ch
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&value](char const* s) {
|
||||
[&value](StringView s) {
|
||||
value = s;
|
||||
return true;
|
||||
},
|
||||
|
@ -451,8 +449,8 @@ void ArgsParser::add_option(StringView& value, char const* help_string, char con
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&value](char const* s) {
|
||||
value = { s, strlen(s) };
|
||||
[&value](StringView s) {
|
||||
value = s;
|
||||
return true;
|
||||
},
|
||||
hide_mode,
|
||||
|
@ -469,8 +467,7 @@ void ArgsParser::add_option(I& value, char const* help_string, char const* long_
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&value](char const* s) {
|
||||
auto view = StringView { s, strlen(s) };
|
||||
[&value](StringView view) {
|
||||
Optional<I> opt;
|
||||
if constexpr (IsSigned<I>)
|
||||
opt = view.to_int<I>();
|
||||
|
@ -499,8 +496,8 @@ void ArgsParser::add_option(double& value, char const* help_string, char const*
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&value](char const* s) {
|
||||
auto opt = convert_to_double(s);
|
||||
[&value](StringView s) {
|
||||
auto opt = s.to_double();
|
||||
value = opt.value_or(0.0);
|
||||
return opt.has_value();
|
||||
},
|
||||
|
@ -517,8 +514,8 @@ void ArgsParser::add_option(Optional<double>& value, char const* help_string, ch
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&value](char const* s) {
|
||||
value = convert_to_double(s);
|
||||
[&value](StringView s) {
|
||||
value = s.to_double();
|
||||
return value.has_value();
|
||||
},
|
||||
hide_mode,
|
||||
|
@ -534,8 +531,8 @@ void ArgsParser::add_option(Optional<size_t>& value, char const* help_string, ch
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&value](char const* s) {
|
||||
value = AK::StringUtils::convert_to_uint<size_t>({ s, strlen(s) });
|
||||
[&value](StringView s) {
|
||||
value = AK::StringUtils::convert_to_uint<size_t>(s);
|
||||
return value.has_value();
|
||||
},
|
||||
hide_mode,
|
||||
|
@ -551,10 +548,10 @@ void ArgsParser::add_option(Vector<size_t>& values, char const* help_string, cha
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&values, separator](char const* s) {
|
||||
[&values, separator](StringView s) {
|
||||
bool parsed_all_values = true;
|
||||
|
||||
StringView { s, strlen(s) }.for_each_split_view(separator, SplitBehavior::Nothing, [&](auto value) {
|
||||
s.for_each_split_view(separator, SplitBehavior::Nothing, [&](auto value) {
|
||||
if (auto maybe_value = AK::StringUtils::convert_to_uint<size_t>(value); maybe_value.has_value())
|
||||
values.append(*maybe_value);
|
||||
else
|
||||
|
@ -577,9 +574,8 @@ void ArgsParser::add_option(Vector<DeprecatedString>& values, char const* help_s
|
|||
long_name,
|
||||
short_name,
|
||||
value_name,
|
||||
[&values](char const* s) {
|
||||
DeprecatedString value = s;
|
||||
values.append(value);
|
||||
[&values](StringView s) {
|
||||
values.append(s);
|
||||
return true;
|
||||
},
|
||||
hide_mode
|
||||
|
@ -600,8 +596,9 @@ void ArgsParser::add_positional_argument(char const*& value, char const* help_st
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
1,
|
||||
[&value](char const* s) {
|
||||
value = s;
|
||||
[&value](StringView s) {
|
||||
VERIFY(s.length() == strlen(s.characters_without_null_termination()));
|
||||
value = s.characters_without_null_termination();
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
@ -615,7 +612,7 @@ void ArgsParser::add_positional_argument(DeprecatedString& value, char const* he
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
1,
|
||||
[&value](char const* s) {
|
||||
[&value](StringView s) {
|
||||
value = s;
|
||||
return true;
|
||||
}
|
||||
|
@ -630,8 +627,8 @@ void ArgsParser::add_positional_argument(StringView& value, char const* help_str
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
1,
|
||||
[&value](char const* s) {
|
||||
value = { s, strlen(s) };
|
||||
[&value](StringView s) {
|
||||
value = s;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
@ -645,8 +642,8 @@ void ArgsParser::add_positional_argument(int& value, char const* help_string, ch
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
1,
|
||||
[&value](char const* s) {
|
||||
auto opt = StringView { s, strlen(s) }.to_int();
|
||||
[&value](StringView s) {
|
||||
auto opt = s.to_int();
|
||||
value = opt.value_or(0);
|
||||
return opt.has_value();
|
||||
}
|
||||
|
@ -661,8 +658,8 @@ void ArgsParser::add_positional_argument(unsigned& value, char const* help_strin
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
1,
|
||||
[&value](char const* s) {
|
||||
auto opt = StringView { s, strlen(s) }.to_uint();
|
||||
[&value](StringView s) {
|
||||
auto opt = s.to_uint();
|
||||
value = opt.value_or(0);
|
||||
return opt.has_value();
|
||||
}
|
||||
|
@ -677,8 +674,8 @@ void ArgsParser::add_positional_argument(double& value, char const* help_string,
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
1,
|
||||
[&value](char const* s) {
|
||||
auto opt = convert_to_double(s);
|
||||
[&value](StringView s) {
|
||||
auto opt = s.to_double();
|
||||
value = opt.value_or(0.0);
|
||||
return opt.has_value();
|
||||
}
|
||||
|
@ -693,8 +690,9 @@ void ArgsParser::add_positional_argument(Vector<char const*>& values, char const
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
INT_MAX,
|
||||
[&values](char const* s) {
|
||||
values.append(s);
|
||||
[&values](StringView s) {
|
||||
VERIFY(s.length() == strlen(s.characters_without_null_termination()));
|
||||
values.append(s.characters_without_null_termination());
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
@ -708,7 +706,7 @@ void ArgsParser::add_positional_argument(Vector<DeprecatedString>& values, char
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
INT_MAX,
|
||||
[&values](char const* s) {
|
||||
[&values](StringView s) {
|
||||
values.append(s);
|
||||
return true;
|
||||
}
|
||||
|
@ -723,15 +721,15 @@ void ArgsParser::add_positional_argument(Vector<StringView>& values, char const*
|
|||
name,
|
||||
required == Required::Yes ? 1 : 0,
|
||||
INT_MAX,
|
||||
[&values](char const* s) {
|
||||
values.append({ s, strlen(s) });
|
||||
[&values](StringView s) {
|
||||
values.append(s);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
add_positional_argument(move(arg));
|
||||
}
|
||||
|
||||
void ArgsParser::autocomplete(FILE* file, StringView program_name, ReadonlySpan<char const*> remaining_arguments)
|
||||
void ArgsParser::autocomplete(FILE* file, StringView program_name, ReadonlySpan<StringView> remaining_arguments)
|
||||
{
|
||||
// We expect the full invocation of the program to be available as positional args,
|
||||
// e.g. `foo --bar arg -b` (program invoked as `foo --complete -- foo --bar arg -b`)
|
||||
|
@ -743,9 +741,7 @@ void ArgsParser::autocomplete(FILE* file, StringView program_name, ReadonlySpan<
|
|||
StringView option_to_complete;
|
||||
auto completing_option = false;
|
||||
|
||||
for (auto& arg : remaining_arguments) {
|
||||
StringView argument { arg, strlen(arg) };
|
||||
|
||||
for (auto& argument : remaining_arguments) {
|
||||
completing_option = false;
|
||||
if (skip_next) {
|
||||
argument_to_complete = argument;
|
||||
|
|
|
@ -51,7 +51,7 @@ public:
|
|||
char const* long_name { nullptr };
|
||||
char short_name { 0 };
|
||||
char const* value_name { nullptr };
|
||||
Function<bool(char const*)> accept_value;
|
||||
Function<bool(StringView)> accept_value;
|
||||
OptionHideMode hide_mode { OptionHideMode::None };
|
||||
|
||||
DeprecatedString name_for_display() const
|
||||
|
@ -67,34 +67,21 @@ public:
|
|||
char const* name { nullptr };
|
||||
int min_values { 0 };
|
||||
int max_values { 1 };
|
||||
Function<bool(char const*)> accept_value;
|
||||
Function<bool(StringView)> accept_value;
|
||||
};
|
||||
|
||||
bool parse(int argc, char* const* argv, FailureBehavior failure_behavior = FailureBehavior::PrintUsageAndExit);
|
||||
bool parse(Span<StringView> arguments, FailureBehavior failure_behavior = FailureBehavior::PrintUsageAndExit);
|
||||
bool parse(Main::Arguments const& arguments, FailureBehavior failure_behavior = FailureBehavior::PrintUsageAndExit)
|
||||
{
|
||||
if (arguments.argv == nullptr && arguments.argc == 0) {
|
||||
// Allocate the data from arguments.strings instead.
|
||||
Vector<DeprecatedString> strings;
|
||||
Vector<char const*> data;
|
||||
strings.ensure_capacity(arguments.strings.size());
|
||||
data.ensure_capacity(arguments.strings.size());
|
||||
for (auto& entry : arguments.strings) {
|
||||
strings.append(entry);
|
||||
data.append(strings.last().characters());
|
||||
}
|
||||
return parse(data.size(), const_cast<char* const*>(data.data()), failure_behavior);
|
||||
}
|
||||
|
||||
return parse(arguments.argc, arguments.argv, failure_behavior);
|
||||
return parse(arguments.strings, failure_behavior);
|
||||
}
|
||||
|
||||
// *Without* trailing newline!
|
||||
void set_general_help(char const* help_string) { m_general_help = help_string; };
|
||||
void set_stop_on_first_non_option(bool stop_on_first_non_option) { m_stop_on_first_non_option = stop_on_first_non_option; }
|
||||
void print_usage(FILE*, char const* argv0);
|
||||
void print_usage_terminal(FILE*, char const* argv0);
|
||||
void print_usage_markdown(FILE*, char const* argv0);
|
||||
void print_usage(FILE*, StringView argv0);
|
||||
void print_usage_terminal(FILE*, StringView argv0);
|
||||
void print_usage_markdown(FILE*, StringView argv0);
|
||||
void print_version(FILE*);
|
||||
|
||||
void add_option(Option&&);
|
||||
|
@ -125,7 +112,7 @@ public:
|
|||
void add_positional_argument(Vector<StringView>& value, char const* help_string, char const* name, Required required = Required::Yes);
|
||||
|
||||
private:
|
||||
void autocomplete(FILE*, StringView program_name, ReadonlySpan<char const*> remaining_arguments);
|
||||
void autocomplete(FILE*, StringView program_name, ReadonlySpan<StringView> remaining_arguments);
|
||||
|
||||
Vector<Option> m_options;
|
||||
Vector<Arg> m_positional_args;
|
||||
|
|
|
@ -56,6 +56,11 @@ static void handle_sigabrt(int)
|
|||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
Vector<StringView> arguments;
|
||||
arguments.ensure_capacity(argc);
|
||||
for (auto i = 0; i < argc; ++i)
|
||||
arguments.append({ argv[i], strlen(argv[i]) });
|
||||
|
||||
g_test_argc = argc;
|
||||
g_test_argv = argv;
|
||||
auto program_name = LexicalPath::basename(argv[0]);
|
||||
|
@ -100,7 +105,7 @@ int main(int argc, char** argv)
|
|||
.help_string = "Show progress with OSC 9 (true, false)",
|
||||
.long_name = "show-progress",
|
||||
.short_name = 'p',
|
||||
.accept_value = [&](auto* str) {
|
||||
.accept_value = [&](StringView str) {
|
||||
if ("true"sv == str)
|
||||
print_progress = true;
|
||||
else if ("false"sv == str)
|
||||
|
@ -120,7 +125,7 @@ int main(int argc, char** argv)
|
|||
args_parser.add_option(*entry.key, entry.value.get<0>().characters(), entry.value.get<1>().characters(), entry.value.get<2>());
|
||||
args_parser.add_positional_argument(specified_test_root, "Tests root directory", "path", Core::ArgsParser::Required::No);
|
||||
args_parser.add_positional_argument(common_path, "Path to tests-common.js", "common-path", Core::ArgsParser::Required::No);
|
||||
args_parser.parse(argc, argv);
|
||||
args_parser.parse(arguments);
|
||||
|
||||
if (per_file)
|
||||
print_json = true;
|
||||
|
|
|
@ -22,7 +22,13 @@ int TEST_MAIN(int argc, char** argv)
|
|||
warnln("Test main does not have a valid test name!");
|
||||
return 1;
|
||||
}
|
||||
int ret = ::Test::TestSuite::the().main(argv[0], argc, argv);
|
||||
|
||||
Vector<StringView> arguments;
|
||||
arguments.ensure_capacity(argc);
|
||||
for (auto i = 0; i < argc; ++i)
|
||||
arguments.append({ argv[i], strlen(argv[i]) });
|
||||
|
||||
int ret = ::Test::TestSuite::the().main(argv[0], arguments);
|
||||
::Test::TestSuite::release();
|
||||
return ret;
|
||||
}
|
||||
|
|
|
@ -56,7 +56,7 @@ void set_suite_setup_function(Function<void()> setup)
|
|||
TestSuite::the().set_suite_setup(move(setup));
|
||||
}
|
||||
|
||||
int TestSuite::main(DeprecatedString const& suite_name, int argc, char** argv)
|
||||
int TestSuite::main(DeprecatedString const& suite_name, Span<StringView> arguments)
|
||||
{
|
||||
m_suite_name = suite_name;
|
||||
|
||||
|
@ -71,7 +71,7 @@ int TestSuite::main(DeprecatedString const& suite_name, int argc, char** argv)
|
|||
args_parser.add_option(do_benchmarks_only, "Only run benchmarks.", "bench", 0);
|
||||
args_parser.add_option(do_list_cases, "List available test cases.", "list", 0);
|
||||
args_parser.add_positional_argument(search_string, "Only run matching cases.", "pattern", Core::ArgsParser::Required::No);
|
||||
args_parser.parse(argc, argv);
|
||||
args_parser.parse(arguments);
|
||||
|
||||
if (m_setup)
|
||||
m_setup();
|
||||
|
|
|
@ -33,7 +33,7 @@ public:
|
|||
}
|
||||
|
||||
int run(NonnullRefPtrVector<TestCase> const&);
|
||||
int main(DeprecatedString const& suite_name, int argc, char** argv);
|
||||
int main(DeprecatedString const& suite_name, Span<StringView> arguments);
|
||||
NonnullRefPtrVector<TestCase> find_cases(DeprecatedString const& search, bool find_tests, bool find_benchmarks);
|
||||
void add_case(NonnullRefPtr<TestCase> const& test_case)
|
||||
{
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue