mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 15:10:19 +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
Notes:
sideshowbarker
2024-07-17 22:55:25 +09:00
Author: https://github.com/alimpfard Commit: https://github.com/SerenityOS/serenity/commit/db886fe18b Pull-request: https://github.com/SerenityOS/serenity/pull/17538 Reviewed-by: https://github.com/ADKaster
43 changed files with 673 additions and 584 deletions
|
@ -2,9 +2,9 @@ set(AK_SOURCES
|
|||
Assertions.cpp
|
||||
Base64.cpp
|
||||
CircularBuffer.cpp
|
||||
DOSPackedTime.cpp
|
||||
DeprecatedFlyString.cpp
|
||||
DeprecatedString.cpp
|
||||
DOSPackedTime.cpp
|
||||
Error.cpp
|
||||
FloatingPointStringConversions.cpp
|
||||
FlyString.cpp
|
||||
|
@ -16,10 +16,10 @@ set(AK_SOURCES
|
|||
JsonParser.cpp
|
||||
JsonPath.cpp
|
||||
JsonValue.cpp
|
||||
kmalloc.cpp
|
||||
LexicalPath.cpp
|
||||
MemoryStream.cpp
|
||||
NumberFormat.cpp
|
||||
OptionParser.cpp
|
||||
Random.cpp
|
||||
StackInfo.cpp
|
||||
Stream.cpp
|
||||
|
@ -32,10 +32,11 @@ set(AK_SOURCES
|
|||
Time.cpp
|
||||
URL.cpp
|
||||
URLParser.cpp
|
||||
UUID.cpp
|
||||
Utf16View.cpp
|
||||
Utf32View.cpp
|
||||
Utf8View.cpp
|
||||
UUID.cpp
|
||||
kmalloc.cpp
|
||||
)
|
||||
# AK sources are included from many different places, such as the Kernel, LibC, and Loader
|
||||
list(TRANSFORM AK_SOURCES PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/")
|
||||
|
|
283
AK/OptionParser.cpp
Normal file
283
AK/OptionParser.cpp
Normal file
|
@ -0,0 +1,283 @@
|
|||
/*
|
||||
* Copyright (c) 2023, Ali Mohammad Pur <mpfard@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <AK/OptionParser.h>
|
||||
|
||||
namespace AK {
|
||||
|
||||
void OptionParser::reset_state()
|
||||
{
|
||||
m_arg_index = 0;
|
||||
m_consumed_args = 0;
|
||||
m_index_into_multioption_argument = 0;
|
||||
m_stop_on_first_non_option = false;
|
||||
}
|
||||
|
||||
OptionParser::GetOptResult OptionParser::getopt(Span<StringView> args, StringView short_options, Span<Option const> long_options, Optional<int&> out_long_option_index)
|
||||
{
|
||||
m_args = args;
|
||||
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('+');
|
||||
|
||||
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 {
|
||||
.result = '?',
|
||||
.optopt_value = m_optopt_value,
|
||||
.optarg_value = m_optarg_value,
|
||||
.consumed_args = 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (should_reorder_argv)
|
||||
shift_argv();
|
||||
|
||||
m_arg_index += m_consumed_args;
|
||||
|
||||
return {
|
||||
.result = res,
|
||||
.optopt_value = m_optopt_value,
|
||||
.optarg_value = m_optarg_value,
|
||||
.consumed_args = m_consumed_args,
|
||||
};
|
||||
}
|
||||
|
||||
Optional<OptionParser::ArgumentRequirement> OptionParser::lookup_short_option_requirement(char option) 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 {};
|
||||
}
|
||||
|
||||
if (parts[1].starts_with("::"sv)) {
|
||||
// If an option is followed by two colons, it optionally accepts an
|
||||
// argument.
|
||||
return ArgumentRequirement::HasOptionalArgument;
|
||||
}
|
||||
if (parts[1].starts_with(':')) {
|
||||
// If it's followed by one colon, it requires an argument.
|
||||
return ArgumentRequirement::HasRequiredArgument;
|
||||
}
|
||||
// Otherwise, it doesn't accept arguments.
|
||||
return ArgumentRequirement::NoArgument;
|
||||
}
|
||||
|
||||
int OptionParser::handle_short_option()
|
||||
{
|
||||
StringView arg = current_arg();
|
||||
VERIFY(arg.starts_with('-'));
|
||||
|
||||
if (m_index_into_multioption_argument == 0) {
|
||||
// Just starting to parse this argument, skip the "-".
|
||||
m_index_into_multioption_argument = 1;
|
||||
}
|
||||
char option = arg[m_index_into_multioption_argument];
|
||||
m_index_into_multioption_argument++;
|
||||
|
||||
auto maybe_requirement = lookup_short_option_requirement(option);
|
||||
if (!maybe_requirement.has_value()) {
|
||||
m_optopt_value = option;
|
||||
reportln("Unrecognized option \x1b[1m-{:c}\x1b[22m", option);
|
||||
return '?';
|
||||
}
|
||||
|
||||
auto argument_requirement = *maybe_requirement;
|
||||
|
||||
// Let's see if we're at the end of this argument already.
|
||||
if (m_index_into_multioption_argument < arg.length()) {
|
||||
// This not yet the end.
|
||||
if (argument_requirement == ArgumentRequirement::NoArgument) {
|
||||
m_optarg_value = {};
|
||||
m_consumed_args = 0;
|
||||
} else {
|
||||
// Treat the rest of the argument as the value, the "-ovalue"
|
||||
// syntax.
|
||||
m_optarg_value = m_args[m_arg_index].substring_view(m_index_into_multioption_argument);
|
||||
// Next time, process the next argument.
|
||||
m_index_into_multioption_argument = 0;
|
||||
m_consumed_args = 1;
|
||||
}
|
||||
} else {
|
||||
m_index_into_multioption_argument = 0;
|
||||
if (argument_requirement != ArgumentRequirement::HasRequiredArgument) {
|
||||
m_optarg_value = StringView();
|
||||
m_consumed_args = 1;
|
||||
} else if (m_arg_index + 1 < m_args.size()) {
|
||||
// Treat the next argument as a value, the "-o value" syntax.
|
||||
m_optarg_value = m_args[m_arg_index + 1];
|
||||
m_consumed_args = 2;
|
||||
} else {
|
||||
reportln("Missing value for option \x1b[1m-{:c}\x1b[22m", option);
|
||||
return '?';
|
||||
}
|
||||
}
|
||||
|
||||
return option;
|
||||
}
|
||||
|
||||
Optional<OptionParser::Option const&> OptionParser::lookup_long_option(StringView arg) const
|
||||
{
|
||||
for (size_t index = 0; index < m_long_options.size(); index++) {
|
||||
auto& option = m_long_options[index];
|
||||
|
||||
if (!arg.starts_with(option.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.has_value())
|
||||
*m_out_long_option_index = index;
|
||||
|
||||
// Can either be "--option" or "--option=value".
|
||||
if (arg.length() == option.name.length()) {
|
||||
m_optarg_value = {};
|
||||
return option;
|
||||
}
|
||||
|
||||
if (arg[option.name.length()] == '=') {
|
||||
m_optarg_value = arg.substring_view(option.name.length() + 1);
|
||||
return option;
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
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.
|
||||
m_optopt_value = 0;
|
||||
|
||||
auto option = lookup_long_option(m_args[m_arg_index].substring_view(2));
|
||||
if (!option.has_value()) {
|
||||
reportln("Unrecognized option \x1b[1m{}\x1b[22m", m_args[m_arg_index]);
|
||||
return '?';
|
||||
}
|
||||
// lookup_long_option() will also set an override for 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->requirement) {
|
||||
case ArgumentRequirement::NoArgument:
|
||||
if (m_optarg_value.has_value()) {
|
||||
reportln("Option \x1b[1m--{}\x1b[22m doesn't accept an argument", option->name);
|
||||
return '?';
|
||||
}
|
||||
m_consumed_args = 1;
|
||||
break;
|
||||
case ArgumentRequirement::HasOptionalArgument:
|
||||
m_consumed_args = 1;
|
||||
break;
|
||||
case ArgumentRequirement::HasRequiredArgument:
|
||||
if (m_optarg_value.has_value()) {
|
||||
// Value specified using "--option=value" syntax.
|
||||
m_consumed_args = 1;
|
||||
} else if (m_arg_index + 1 < m_args.size()) {
|
||||
// Treat the next argument as a value in "--option value" syntax.
|
||||
m_optarg_value = m_args[m_arg_index + 1];
|
||||
m_consumed_args = 2;
|
||||
} else {
|
||||
reportln("Missing value for option \x1b[1m--{}\x1b[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 != nullptr) {
|
||||
*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 its value, if any) in front of other arguments.
|
||||
if (m_consumed_args == 0 || m_skipped_arguments == 0) {
|
||||
// Nothing to do!
|
||||
return;
|
||||
}
|
||||
// x -a b c d
|
||||
// ---- consumed
|
||||
// ->
|
||||
// -a b x c d
|
||||
|
||||
StringView buffer[2]; // We consume at most 2 arguments in one call.
|
||||
Span<StringView> buffer_bytes { buffer, array_size(buffer) };
|
||||
m_args.slice(m_arg_index, m_consumed_args).copy_to(buffer_bytes);
|
||||
m_args.slice(m_arg_index - m_skipped_arguments, m_skipped_arguments).copy_to(m_args.slice(m_arg_index + m_consumed_args - m_skipped_arguments));
|
||||
buffer_bytes.slice(0, m_consumed_args).copy_to(m_args.slice(m_arg_index - m_skipped_arguments, m_consumed_args));
|
||||
}
|
||||
|
||||
bool OptionParser::find_next_option()
|
||||
{
|
||||
for (m_skipped_arguments = 0; m_arg_index < m_args.size(); m_skipped_arguments++, 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;
|
||||
}
|
||||
|
||||
}
|
84
AK/OptionParser.h
Normal file
84
AK/OptionParser.h
Normal file
|
@ -0,0 +1,84 @@
|
|||
/*
|
||||
* Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
|
||||
* Copyright (c) 2023, Ali Mohammad Pur <mpfard@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/Format.h>
|
||||
#include <AK/StringView.h>
|
||||
#include <AK/Vector.h>
|
||||
|
||||
namespace AK {
|
||||
|
||||
class OptionParser {
|
||||
public:
|
||||
enum class ArgumentRequirement {
|
||||
NoArgument,
|
||||
HasOptionalArgument,
|
||||
HasRequiredArgument,
|
||||
};
|
||||
// Note: This is weird, but this class is used as a backend for getopt, so we're mirroring getopt here.
|
||||
struct Option {
|
||||
StringView name;
|
||||
ArgumentRequirement requirement;
|
||||
int* flag;
|
||||
int val;
|
||||
};
|
||||
|
||||
struct GetOptResult {
|
||||
int result; // Whatever getopt is supposed to return.
|
||||
Optional<int> optopt_value; // The new contents of `optopt' after this call
|
||||
Optional<StringView> optarg_value; // The new contents of `optarg' after this call
|
||||
size_t consumed_args;
|
||||
};
|
||||
|
||||
GetOptResult getopt(Span<StringView> args, StringView short_options, Span<Option const> long_options, Optional<int&> out_long_option_index);
|
||||
void reset_state();
|
||||
|
||||
private:
|
||||
Optional<ArgumentRequirement> lookup_short_option_requirement(char option) const;
|
||||
int handle_short_option();
|
||||
|
||||
Optional<Option const&> lookup_long_option(StringView raw) const;
|
||||
int handle_long_option();
|
||||
|
||||
void shift_argv();
|
||||
bool find_next_option();
|
||||
|
||||
StringView current_arg() const
|
||||
{
|
||||
if (m_arg_index >= m_args.size())
|
||||
return {};
|
||||
|
||||
return m_args[m_arg_index];
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
static void reportln(CheckedFormatString<Args...> format_string, Args&&... args)
|
||||
{
|
||||
warnln(format_string.view(), forward<Args>(args)...);
|
||||
}
|
||||
|
||||
// NOTE: These are ephemeral, and effectively only last for one call of `getopt()'.
|
||||
Span<StringView> m_args {};
|
||||
StringView m_short_options {};
|
||||
Span<Option const> m_long_options {};
|
||||
mutable Optional<int&> m_out_long_option_index {};
|
||||
mutable Optional<int> m_optopt_value {};
|
||||
mutable Optional<StringView> m_optarg_value {};
|
||||
|
||||
size_t m_arg_index { 0 };
|
||||
size_t m_skipped_arguments { 0 };
|
||||
size_t m_consumed_args { 0 };
|
||||
size_t m_index_into_multioption_argument { 0 };
|
||||
bool m_stop_on_first_non_option { false };
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#if USING_AK_GLOBALLY
|
||||
using AK::OptionParser;
|
||||
#endif
|
|
@ -283,7 +283,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
|
||||
auto open_file = [&](StringView path, Core::File::OpenMode mode = Core::File::OpenMode::Read) -> ErrorOr<NonnullOwnPtr<Core::File>> {
|
||||
if (path.is_empty()) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return Error::from_string_literal("Must provide all command line options");
|
||||
}
|
||||
|
||||
|
|
|
@ -52,8 +52,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.long_name = "header-include-path",
|
||||
.short_name = 'i',
|
||||
.value_name = "path",
|
||||
.accept_value = [&](char const* s) {
|
||||
s_header_search_paths.append({ s, strlen(s) });
|
||||
.accept_value = [&](StringView s) {
|
||||
s_header_search_paths.append(s);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
|
|
@ -31,6 +31,11 @@ using Test::Crash;
|
|||
|
||||
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]) });
|
||||
|
||||
bool do_all_crash_types = false;
|
||||
bool do_segmentation_violation = false;
|
||||
bool do_division_by_zero = false;
|
||||
|
@ -84,11 +89,11 @@ int main(int argc, char** argv)
|
|||
if (argc == 1) {
|
||||
do_all_crash_types = true;
|
||||
} else if (argc != 2) {
|
||||
args_parser.print_usage(stderr, argv[0]);
|
||||
args_parser.print_usage(stderr, arguments[0]);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
args_parser.parse(argc, argv);
|
||||
args_parser.parse(arguments);
|
||||
|
||||
Crash::RunType run_type = do_all_crash_types ? Crash::RunType::UsingChildProcess
|
||||
: Crash::RunType::UsingCurrentProcess;
|
||||
|
|
|
@ -13,6 +13,11 @@
|
|||
|
||||
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]) });
|
||||
|
||||
char const* target = nullptr;
|
||||
int max_file_size = 1024 * 1024;
|
||||
int count = 1024;
|
||||
|
@ -21,7 +26,7 @@ int main(int argc, char** argv)
|
|||
args_parser.add_option(max_file_size, "Maximum file size to generate", "max-size", 's', "size");
|
||||
args_parser.add_option(count, "Number of truncations to run", "number", 'n', "number");
|
||||
args_parser.add_positional_argument(target, "Target file path", "target");
|
||||
args_parser.parse(argc, argv);
|
||||
args_parser.parse(arguments);
|
||||
|
||||
int fd = creat(target, 0666);
|
||||
if (fd < 0) {
|
||||
|
|
|
@ -60,6 +60,11 @@ bool write_block(int fd, int seed, off_t block, AK::ByteBuffer& buffer)
|
|||
|
||||
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]) });
|
||||
|
||||
char const* target = nullptr;
|
||||
int min_block_offset = 0;
|
||||
int block_length = 2048;
|
||||
|
@ -82,7 +87,7 @@ int main(int argc, char** argv)
|
|||
args_parser.add_option(stop_mode, "Stop after first error", "abort-on-error", 'a');
|
||||
args_parser.add_option(uninitialized_mode, "Don't pre-initialize block range", "uninitialized", 'u');
|
||||
args_parser.add_positional_argument(target, "Target device/file path", "target");
|
||||
args_parser.parse(argc, argv);
|
||||
args_parser.parse(arguments);
|
||||
|
||||
auto buffer_result = AK::ByteBuffer::create_zeroed(block_size);
|
||||
if (buffer_result.is_error()) {
|
||||
|
|
|
@ -12,68 +12,44 @@
|
|||
|
||||
class ParserResult {
|
||||
public:
|
||||
ParserResult(Vector<DeprecatedString> const& arguments)
|
||||
ParserResult(Vector<StringView> arguments)
|
||||
: arguments(move(arguments))
|
||||
{
|
||||
argv = new char*[arguments.size() + 1];
|
||||
argc = 0;
|
||||
for (auto& argument : arguments) {
|
||||
auto char_argument = new char[argument.length() + 1];
|
||||
memcpy(char_argument, argument.characters(), argument.length());
|
||||
char_argument[argument.length()] = '\0';
|
||||
argv[argc++] = char_argument;
|
||||
}
|
||||
argv[argc] = nullptr;
|
||||
}
|
||||
|
||||
ParserResult(ParserResult&& other)
|
||||
{
|
||||
arguments = move(other.arguments);
|
||||
result = other.result;
|
||||
argv = other.argv;
|
||||
argc = other.argc;
|
||||
|
||||
other.argv = nullptr;
|
||||
other.argc = 0;
|
||||
}
|
||||
|
||||
ParserResult& operator=(ParserResult&& other)
|
||||
{
|
||||
if (this != &other) {
|
||||
arguments = move(other.arguments);
|
||||
result = other.result;
|
||||
argv = other.argv;
|
||||
argc = other.argc;
|
||||
|
||||
other.argv = nullptr;
|
||||
other.argc = 0;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ParserResult()
|
||||
{
|
||||
for (size_t i = 0; i < argc; ++i)
|
||||
delete[] argv[i];
|
||||
delete[] argv;
|
||||
}
|
||||
|
||||
Vector<StringView> arguments;
|
||||
bool result { false };
|
||||
char** argv { nullptr };
|
||||
size_t argc { 0 };
|
||||
};
|
||||
|
||||
static ParserResult run_parser(Vector<DeprecatedString> arguments, Function<void(Core::ArgsParser&)> parser_initialization = {})
|
||||
static ParserResult run_parser(Vector<StringView> arguments, Function<void(Core::ArgsParser&)> parser_initialization = {})
|
||||
{
|
||||
Core::ArgsParser parser;
|
||||
if (parser_initialization)
|
||||
parser_initialization(parser);
|
||||
|
||||
auto parse_result = ParserResult { arguments };
|
||||
parse_result.result = parser.parse(parse_result.argc, parse_result.argv, Core::ArgsParser::FailureBehavior::Ignore);
|
||||
auto parse_result = ParserResult { move(arguments) };
|
||||
parse_result.result = parser.parse(parse_result.arguments, Core::ArgsParser::FailureBehavior::Ignore);
|
||||
return parse_result;
|
||||
}
|
||||
|
||||
TEST_CASE(no_arguments)
|
||||
{
|
||||
auto parser_result = run_parser({ "app" });
|
||||
auto parser_result = run_parser({ "app"sv });
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
}
|
||||
|
||||
|
@ -81,7 +57,7 @@ TEST_CASE(bool_option)
|
|||
{
|
||||
// Short option
|
||||
bool force = false;
|
||||
auto parser_result = run_parser({ "app", "-f" }, [&](auto& parser) {
|
||||
auto parser_result = run_parser({ "app"sv, "-f"sv }, [&](auto& parser) {
|
||||
parser.add_option(force, "force", nullptr, 'f');
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -89,7 +65,7 @@ TEST_CASE(bool_option)
|
|||
|
||||
// Short option, not given
|
||||
force = false;
|
||||
parser_result = run_parser({ "app" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv }, [&](auto& parser) {
|
||||
parser.add_option(force, "force", nullptr, 'f');
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -97,7 +73,7 @@ TEST_CASE(bool_option)
|
|||
|
||||
// Long option
|
||||
force = false;
|
||||
parser_result = run_parser({ "app", "--force" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "--force"sv }, [&](auto& parser) {
|
||||
parser.add_option(force, "force", "force", '\0');
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -105,7 +81,7 @@ TEST_CASE(bool_option)
|
|||
|
||||
// Long option, not given
|
||||
force = false;
|
||||
parser_result = run_parser({ "app" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv }, [&](auto& parser) {
|
||||
parser.add_option(force, "force", "force", '\0');
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -113,7 +89,7 @@ TEST_CASE(bool_option)
|
|||
|
||||
// Allow both short and long option, provide short
|
||||
force = false;
|
||||
parser_result = run_parser({ "app", "-f" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "-f"sv }, [&](auto& parser) {
|
||||
parser.add_option(force, "force", "force", 'f');
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -121,7 +97,7 @@ TEST_CASE(bool_option)
|
|||
|
||||
// Allow both short and long option, provide long
|
||||
force = false;
|
||||
parser_result = run_parser({ "app", "--force" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "--force"sv }, [&](auto& parser) {
|
||||
parser.add_option(force, "force", "force", 'f');
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -129,7 +105,7 @@ TEST_CASE(bool_option)
|
|||
|
||||
// Allow both short and long option, provide both
|
||||
force = false;
|
||||
parser_result = run_parser({ "app", "--force", "-f" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "--force"sv, "-f"sv }, [&](auto& parser) {
|
||||
parser.add_option(force, "force", "force", 'f');
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -140,7 +116,7 @@ TEST_CASE(positional_string_argument)
|
|||
{
|
||||
// Single required string argument
|
||||
DeprecatedString name = "";
|
||||
auto parser_result = run_parser({ "app", "buggie" }, [&](auto& parser) {
|
||||
auto parser_result = run_parser({ "app"sv, "buggie"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(name, "name", "name", Core::ArgsParser::Required::Yes);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -148,7 +124,7 @@ TEST_CASE(positional_string_argument)
|
|||
|
||||
// Single required string argument, not given
|
||||
name = "";
|
||||
parser_result = run_parser({ "app" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(name, "name", "name", Core::ArgsParser::Required::Yes);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, false);
|
||||
|
@ -156,7 +132,7 @@ TEST_CASE(positional_string_argument)
|
|||
|
||||
// Single optional string argument
|
||||
name = "";
|
||||
parser_result = run_parser({ "app", "buggie" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "buggie"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(name, "name", "name", Core::ArgsParser::Required::No);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -164,7 +140,7 @@ TEST_CASE(positional_string_argument)
|
|||
|
||||
// Single optional string argument, not given
|
||||
name = "";
|
||||
parser_result = run_parser({ "app" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(name, "name", "name", Core::ArgsParser::Required::No);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -176,7 +152,7 @@ TEST_CASE(positional_vector_string_argument)
|
|||
Vector<StringView> values;
|
||||
|
||||
// Zero or more positional arguments, zero given
|
||||
auto parser_result = run_parser({ "app" }, [&](auto& parser) {
|
||||
auto parser_result = run_parser({ "app"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(values, "values", "values", Core::ArgsParser::Required::No);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -184,7 +160,7 @@ TEST_CASE(positional_vector_string_argument)
|
|||
|
||||
// Zero or more positional arguments, one given
|
||||
values = {};
|
||||
parser_result = run_parser({ "app", "one" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "one"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(values, "values", "values", Core::ArgsParser::Required::No);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -194,7 +170,7 @@ TEST_CASE(positional_vector_string_argument)
|
|||
|
||||
// Zero or more positional arguments, two given
|
||||
values = {};
|
||||
parser_result = run_parser({ "app", "one", "two" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "one"sv, "two"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(values, "values", "values", Core::ArgsParser::Required::No);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -206,7 +182,7 @@ TEST_CASE(positional_vector_string_argument)
|
|||
|
||||
// One or more positional arguments, zero given
|
||||
values = {};
|
||||
parser_result = run_parser({ "app" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(values, "values", "values", Core::ArgsParser::Required::Yes);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, false);
|
||||
|
@ -214,7 +190,7 @@ TEST_CASE(positional_vector_string_argument)
|
|||
|
||||
// One or more positional arguments, one given
|
||||
values = {};
|
||||
parser_result = run_parser({ "app", "one" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "one"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(values, "values", "values", Core::ArgsParser::Required::Yes);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -224,7 +200,7 @@ TEST_CASE(positional_vector_string_argument)
|
|||
|
||||
// One or more positional arguments, two given
|
||||
values = {};
|
||||
parser_result = run_parser({ "app", "one", "two" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "one"sv, "two"sv }, [&](auto& parser) {
|
||||
parser.add_positional_argument(values, "values", "values", Core::ArgsParser::Required::Yes);
|
||||
});
|
||||
EXPECT_EQ(parser_result.result, true);
|
||||
|
@ -242,7 +218,7 @@ TEST_CASE(combination_of_bool_options_with_positional_vector_string)
|
|||
// Expected: all arguments fill as given
|
||||
bool bool_opt1 = false;
|
||||
bool bool_opt2 = false;
|
||||
auto parser_result = run_parser({ "app", "-b", "-c", "one", "two" }, [&](auto& parser) {
|
||||
auto parser_result = run_parser({ "app"sv, "-b"sv, "-c"sv, "one"sv, "two"sv }, [&](auto& parser) {
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
parser.add_positional_argument(positionals, "pos", "pos", Core::ArgsParser::Required::No);
|
||||
|
@ -261,7 +237,7 @@ TEST_CASE(combination_of_bool_options_with_positional_vector_string)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "one", "two" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "one"sv, "two"sv }, [&](auto& parser) {
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
parser.add_positional_argument(positionals, "pos", "pos", Core::ArgsParser::Required::No);
|
||||
|
@ -280,7 +256,7 @@ TEST_CASE(combination_of_bool_options_with_positional_vector_string)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "-b", "-c" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "-b"sv, "-c"sv }, [&](auto& parser) {
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
parser.add_positional_argument(positionals, "pos", "pos", Core::ArgsParser::Required::No);
|
||||
|
@ -295,7 +271,7 @@ TEST_CASE(combination_of_bool_options_with_positional_vector_string)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "--", "-b", "-c" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "--"sv, "-b"sv, "-c"sv }, [&](auto& parser) {
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
parser.add_positional_argument(positionals, "pos", "pos", Core::ArgsParser::Required::No);
|
||||
|
@ -314,7 +290,7 @@ TEST_CASE(combination_of_bool_options_with_positional_vector_string)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "-b", "--", "-c" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "-b"sv, "--"sv, "-c"sv }, [&](auto& parser) {
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
parser.add_positional_argument(positionals, "pos", "pos", Core::ArgsParser::Required::No);
|
||||
|
@ -332,7 +308,7 @@ TEST_CASE(combination_of_bool_options_with_positional_vector_string)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "-b", "-d", "-c" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "-b"sv, "-d"sv, "-c"sv }, [&](auto& parser) {
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
parser.add_positional_argument(positionals, "pos", "pos", Core::ArgsParser::Required::No);
|
||||
|
@ -347,7 +323,7 @@ TEST_CASE(stop_on_first_non_option)
|
|||
bool bool_opt1 = false;
|
||||
bool bool_opt2 = false;
|
||||
Vector<StringView> positionals;
|
||||
auto parser_result = run_parser({ "app", "-b", "-c", "one" }, [&](auto& parser) {
|
||||
auto parser_result = run_parser({ "app"sv, "-b"sv, "-c"sv, "one"sv }, [&](auto& parser) {
|
||||
parser.set_stop_on_first_non_option(false);
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
|
@ -365,7 +341,7 @@ TEST_CASE(stop_on_first_non_option)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "-b", "one", "-c" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "-b"sv, "one"sv, "-c"sv }, [&](auto& parser) {
|
||||
parser.set_stop_on_first_non_option(false);
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
|
@ -383,7 +359,7 @@ TEST_CASE(stop_on_first_non_option)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "-b", "-c", "one" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "-b"sv, "-c"sv, "one"sv }, [&](auto& parser) {
|
||||
parser.set_stop_on_first_non_option(true);
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
|
@ -401,7 +377,7 @@ TEST_CASE(stop_on_first_non_option)
|
|||
bool_opt1 = false;
|
||||
bool_opt2 = false;
|
||||
positionals = {};
|
||||
parser_result = run_parser({ "app", "-b", "one", "-c" }, [&](auto& parser) {
|
||||
parser_result = run_parser({ "app"sv, "-b"sv, "one"sv, "-c"sv }, [&](auto& parser) {
|
||||
parser.set_stop_on_first_non_option(true);
|
||||
parser.add_option(bool_opt1, "bool_opt1", nullptr, 'b');
|
||||
parser.add_option(bool_opt2, "bool_opt2", nullptr, 'c');
|
||||
|
|
|
@ -589,6 +589,11 @@ constexpr int exit_read_file_failure = 3;
|
|||
|
||||
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]) });
|
||||
|
||||
int timeout = 10;
|
||||
bool enable_debug_printing = false;
|
||||
bool disable_core_dumping = false;
|
||||
|
@ -602,7 +607,7 @@ int main(int argc, char** argv)
|
|||
args_parser.add_option(timeout, "Seconds before test should timeout", "timeout", 't', "seconds");
|
||||
args_parser.add_option(enable_debug_printing, "Enable debug printing", "debug", 'd');
|
||||
args_parser.add_option(disable_core_dumping, "Disable core dumping", "disable-core-dump", 0);
|
||||
args_parser.parse(argc, argv);
|
||||
args_parser.parse(arguments);
|
||||
|
||||
#if !defined(AK_OS_MACOS) && !defined(AK_OS_EMSCRIPTEN)
|
||||
if (disable_core_dumping && prctl(PR_SET_DUMPABLE, 0, 0) < 0) {
|
||||
|
|
|
@ -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)
|
||||
{
|
||||
|
|
|
@ -226,8 +226,7 @@ ErrorOr<int> Shell::builtin_bg(Main::Arguments arguments)
|
|||
.name = "job-id",
|
||||
.min_values = 0,
|
||||
.max_values = 1,
|
||||
.accept_value = [&](auto value_ptr) -> bool {
|
||||
StringView value { value_ptr, strlen(value_ptr) };
|
||||
.accept_value = [&](StringView value) -> bool {
|
||||
// Check if it's a pid (i.e. literal integer)
|
||||
if (auto number = value.to_uint(); number.has_value()) {
|
||||
job_id = number.value();
|
||||
|
@ -598,8 +597,7 @@ ErrorOr<int> Shell::builtin_fg(Main::Arguments arguments)
|
|||
.name = "job-id",
|
||||
.min_values = 0,
|
||||
.max_values = 1,
|
||||
.accept_value = [&](auto const* value_ptr) -> bool {
|
||||
StringView value { value_ptr, strlen(value_ptr) };
|
||||
.accept_value = [&](StringView value) -> bool {
|
||||
// Check if it's a pid (i.e. literal integer)
|
||||
if (auto number = value.to_uint(); number.has_value()) {
|
||||
job_id = number.value();
|
||||
|
@ -670,8 +668,7 @@ ErrorOr<int> Shell::builtin_disown(Main::Arguments arguments)
|
|||
.name = "job-id",
|
||||
.min_values = 0,
|
||||
.max_values = INT_MAX,
|
||||
.accept_value = [&](auto const* value_ptr) -> bool {
|
||||
StringView value { value_ptr, strlen(value_ptr) };
|
||||
.accept_value = [&](StringView value) -> bool {
|
||||
// Check if it's a pid (i.e. literal integer)
|
||||
if (auto number = value.to_uint(); number.has_value()) {
|
||||
job_ids.append(number.value());
|
||||
|
@ -955,7 +952,7 @@ ErrorOr<int> Shell::builtin_shift(Main::Arguments arguments)
|
|||
|
||||
ErrorOr<int> Shell::builtin_source(Main::Arguments arguments)
|
||||
{
|
||||
char const* file_to_source = nullptr;
|
||||
StringView file_to_source;
|
||||
Vector<StringView> args;
|
||||
|
||||
Core::ArgsParser parser;
|
||||
|
@ -1084,8 +1081,7 @@ ErrorOr<int> Shell::builtin_wait(Main::Arguments arguments)
|
|||
.name = "job-id",
|
||||
.min_values = 0,
|
||||
.max_values = INT_MAX,
|
||||
.accept_value = [&](auto const* value_ptr) -> bool {
|
||||
StringView value { value_ptr, strlen(value_ptr) };
|
||||
.accept_value = [&](StringView value) -> bool {
|
||||
// Check if it's a pid (i.e. literal integer)
|
||||
if (auto number = value.to_uint(); number.has_value()) {
|
||||
job_ids.append(number.value());
|
||||
|
@ -1299,7 +1295,7 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
|
||||
Core::ArgsParser user_parser;
|
||||
|
||||
Vector<char const*> descriptors;
|
||||
Vector<StringView> descriptors;
|
||||
Variant<Core::ArgsParser::Option, Core::ArgsParser::Arg, Empty> current;
|
||||
DeprecatedString current_variable;
|
||||
// if max > 1 or min < 1, or explicit `--list`.
|
||||
|
@ -1369,8 +1365,8 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
warnln("Defined option must have at least one of --long-name or --short-name");
|
||||
return false;
|
||||
}
|
||||
option.accept_value = [&, current_variable, treat_arg_as_list, type](auto value) {
|
||||
auto result = MUST(try_convert({ value, strlen(value) }, type));
|
||||
option.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) {
|
||||
auto result = MUST(try_convert(value, type));
|
||||
if (result.has_value()) {
|
||||
auto value = result.release_value();
|
||||
if (treat_arg_as_list)
|
||||
|
@ -1391,8 +1387,8 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
warnln("Defined positional argument must have a name");
|
||||
return false;
|
||||
}
|
||||
arg.accept_value = [&, current_variable, treat_arg_as_list, type](auto value) {
|
||||
auto result = MUST(try_convert({ value, strlen(value) }, type));
|
||||
arg.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) {
|
||||
auto result = MUST(try_convert(value, type));
|
||||
if (result.has_value()) {
|
||||
auto value = result.release_value();
|
||||
if (treat_arg_as_list)
|
||||
|
@ -1427,8 +1423,9 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Set the general help string for the parser",
|
||||
.long_name = "general-help",
|
||||
.value_name = "string",
|
||||
.accept_value = [&](auto value) {
|
||||
user_parser.set_general_help(value);
|
||||
.accept_value = [&](StringView value) {
|
||||
VERIFY(strlen(value.characters_without_null_termination()) == value.length());
|
||||
user_parser.set_general_help(value.characters_without_null_termination());
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
@ -1469,13 +1466,12 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Define the type of the option or argument being described",
|
||||
.long_name = "type",
|
||||
.value_name = "type",
|
||||
.accept_value = [&](auto name) {
|
||||
.accept_value = [&](StringView ty) {
|
||||
if (current.has<Empty>()) {
|
||||
warnln("Must be defining an argument or option to use --type");
|
||||
return false;
|
||||
}
|
||||
|
||||
StringView ty { name, strlen(name) };
|
||||
if (ty == "bool") {
|
||||
if (auto option = current.get_pointer<Core::ArgsParser::Option>()) {
|
||||
if (option->value_name != nullptr) {
|
||||
|
@ -1513,14 +1509,15 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Set the help string of the option or argument being defined",
|
||||
.long_name = "help-string",
|
||||
.value_name = "string",
|
||||
.accept_value = [&](auto value) {
|
||||
.accept_value = [&](StringView value) {
|
||||
return current.visit(
|
||||
[](Empty) {
|
||||
warnln("Must be defining an option or argument to use --help-string");
|
||||
return false;
|
||||
},
|
||||
[&](auto& option) {
|
||||
option.help_string = value;
|
||||
VERIFY(value.length() == strlen(value.characters_without_null_termination()));
|
||||
option.help_string = value.characters_without_null_termination();
|
||||
return true;
|
||||
});
|
||||
},
|
||||
|
@ -1530,7 +1527,7 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Set the long name of the option being defined",
|
||||
.long_name = "long-name",
|
||||
.value_name = "name",
|
||||
.accept_value = [&](auto value) {
|
||||
.accept_value = [&](StringView value) {
|
||||
auto option = current.get_pointer<Core::ArgsParser::Option>();
|
||||
if (!option) {
|
||||
warnln("Must be defining an option to use --long-name");
|
||||
|
@ -1540,7 +1537,8 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
warnln("Repeated application of --long-name is not allowed, current option has long name set to \"{}\"", option->long_name);
|
||||
return false;
|
||||
}
|
||||
option->long_name = value;
|
||||
VERIFY(value.length() == strlen(value.characters_without_null_termination()));
|
||||
option->long_name = value.characters_without_null_termination();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
@ -1549,13 +1547,13 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Set the short name of the option being defined",
|
||||
.long_name = "short-name",
|
||||
.value_name = "char",
|
||||
.accept_value = [&](auto value) {
|
||||
.accept_value = [&](StringView value) {
|
||||
auto option = current.get_pointer<Core::ArgsParser::Option>();
|
||||
if (!option) {
|
||||
warnln("Must be defining an option to use --short-name");
|
||||
return false;
|
||||
}
|
||||
if (strlen(value) != 1) {
|
||||
if (value.length() != 1) {
|
||||
warnln("Option short name ('{}') must be exactly one character long", value);
|
||||
return false;
|
||||
}
|
||||
|
@ -1572,7 +1570,7 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Set the value name of the option being defined",
|
||||
.long_name = "value-name",
|
||||
.value_name = "string",
|
||||
.accept_value = [&](auto value) {
|
||||
.accept_value = [&](StringView value) {
|
||||
return current.visit(
|
||||
[](Empty) {
|
||||
warnln("Must be defining an option or a positional argument to use --value-name");
|
||||
|
@ -1588,7 +1586,8 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
return false;
|
||||
}
|
||||
|
||||
option.value_name = value;
|
||||
VERIFY(value.length() == strlen(value.characters_without_null_termination()));
|
||||
option.value_name = value.characters_without_null_termination();
|
||||
return true;
|
||||
},
|
||||
[&](Core::ArgsParser::Arg& arg) {
|
||||
|
@ -1597,7 +1596,8 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
return false;
|
||||
}
|
||||
|
||||
arg.name = value;
|
||||
VERIFY(value.length() == strlen(value.characters_without_null_termination()));
|
||||
arg.name = value.characters_without_null_termination();
|
||||
return true;
|
||||
});
|
||||
},
|
||||
|
@ -1626,14 +1626,14 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Set the minimum required number of positional descriptors for the argument being described",
|
||||
.long_name = "min",
|
||||
.value_name = "n",
|
||||
.accept_value = [&](auto value) {
|
||||
.accept_value = [&](StringView value) {
|
||||
auto arg = current.get_pointer<Core::ArgsParser::Arg>();
|
||||
if (!arg) {
|
||||
warnln("Must be describing a positional argument to use --min");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto number = StringView { value, strlen(value) }.to_uint();
|
||||
auto number = value.to_uint();
|
||||
if (!number.has_value()) {
|
||||
warnln("Invalid value for --min: '{}', expected a non-negative number", value);
|
||||
return false;
|
||||
|
@ -1654,14 +1654,14 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
.help_string = "Set the maximum required number of positional descriptors for the argument being described",
|
||||
.long_name = "max",
|
||||
.value_name = "n",
|
||||
.accept_value = [&](auto value) {
|
||||
.accept_value = [&](StringView value) {
|
||||
auto arg = current.get_pointer<Core::ArgsParser::Arg>();
|
||||
if (!arg) {
|
||||
warnln("Must be describing a positional argument to use --max");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto number = StringView { value, strlen(value) }.to_uint();
|
||||
auto number = value.to_uint();
|
||||
if (!number.has_value()) {
|
||||
warnln("Invalid value for --max: '{}', expected a non-negative number", value);
|
||||
return false;
|
||||
|
@ -1702,7 +1702,7 @@ ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
|
|||
if (!commit())
|
||||
return 2;
|
||||
|
||||
if (!user_parser.parse(static_cast<int>(descriptors.size()), const_cast<char* const*>(descriptors.data()), Core::ArgsParser::FailureBehavior::Ignore))
|
||||
if (!user_parser.parse(descriptors, Core::ArgsParser::FailureBehavior::Ignore))
|
||||
return 1;
|
||||
|
||||
return 0;
|
||||
|
|
|
@ -31,15 +31,15 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
"preserve",
|
||||
'p',
|
||||
"attributes",
|
||||
[&preserve](char const* s) {
|
||||
if (!s) {
|
||||
[&preserve](StringView s) {
|
||||
if (s.is_empty()) {
|
||||
preserve = Core::DeprecatedFile::PreserveMode::Permissions | Core::DeprecatedFile::PreserveMode::Ownership | Core::DeprecatedFile::PreserveMode::Timestamps;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool values_ok = true;
|
||||
|
||||
StringView { s, strlen(s) }.for_each_split_view(',', SplitBehavior::Nothing, [&](StringView value) {
|
||||
s.for_each_split_view(',', SplitBehavior::Nothing, [&](StringView value) {
|
||||
if (value == "mode"sv) {
|
||||
preserve |= Core::DeprecatedFile::PreserveMode::Permissions;
|
||||
} else if (value == "ownership"sv) {
|
||||
|
|
|
@ -169,19 +169,19 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
|
||||
if (selected_options_count == 0) {
|
||||
warnln("cut: you must specify a list of bytes, or fields");
|
||||
args_parser.print_usage(stderr, arguments.strings[0].characters_without_null_termination());
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (selected_options_count > 1) {
|
||||
warnln("cut: you must specify only one of bytes, or fields");
|
||||
args_parser.print_usage(stderr, arguments.strings[0].characters_without_null_termination());
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (delimiter.length() != 1) {
|
||||
warnln("cut: the delimiter must be a single character");
|
||||
args_parser.print_usage(stderr, arguments.strings[0].characters_without_null_termination());
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
@ -200,7 +200,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
auto expansion_successful = expand_list(ranges_list, ranges_vector);
|
||||
|
||||
if (!expansion_successful) {
|
||||
args_parser.print_usage(stderr, arguments.strings[0].characters_without_null_termination());
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
|
|
@ -66,8 +66,7 @@ ErrorOr<void> parse_args(Main::Arguments arguments, Vector<DeprecatedString>& fi
|
|||
"time",
|
||||
0,
|
||||
"time-type",
|
||||
[&du_option](auto const* option_ptr) {
|
||||
StringView option { option_ptr, strlen(option_ptr) };
|
||||
[&du_option](StringView option) {
|
||||
if (option == "mtime"sv || option == "modification"sv)
|
||||
du_option.time_type = DuOption::TimeType::Modification;
|
||||
else if (option == "ctime"sv || option == "status"sv || option == "use"sv)
|
||||
|
@ -87,7 +86,7 @@ ErrorOr<void> parse_args(Main::Arguments arguments, Vector<DeprecatedString>& fi
|
|||
nullptr,
|
||||
'k',
|
||||
nullptr,
|
||||
[&du_option](auto const*) {
|
||||
[&du_option](StringView) {
|
||||
du_option.block_size = 1024;
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -83,7 +83,7 @@ ErrorOr<int> serenity_main(Main::Arguments args)
|
|||
.long_name = "regexp",
|
||||
.short_name = 'e',
|
||||
.value_name = "Pattern",
|
||||
.accept_value = [&](auto* str) {
|
||||
.accept_value = [&](StringView str) {
|
||||
patterns.append(str);
|
||||
return true;
|
||||
},
|
||||
|
@ -97,7 +97,7 @@ ErrorOr<int> serenity_main(Main::Arguments args)
|
|||
.argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
|
||||
.help_string = "Action to take for binary files ([binary], text, skip)",
|
||||
.long_name = "binary-mode",
|
||||
.accept_value = [&](auto* str) {
|
||||
.accept_value = [&](StringView str) {
|
||||
if ("text"sv == str)
|
||||
binary_mode = BinaryFileMode::Text;
|
||||
else if ("binary"sv == str)
|
||||
|
@ -135,7 +135,7 @@ ErrorOr<int> serenity_main(Main::Arguments args)
|
|||
.long_name = "color",
|
||||
.short_name = 0,
|
||||
.value_name = "WHEN",
|
||||
.accept_value = [&](auto* str) {
|
||||
.accept_value = [&](StringView str) {
|
||||
if ("never"sv == str)
|
||||
colored_output = false;
|
||||
else if ("always"sv == str)
|
||||
|
|
|
@ -45,8 +45,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
"monochrome",
|
||||
'm',
|
||||
nullptr,
|
||||
[](char const* s) {
|
||||
VERIFY(s == nullptr);
|
||||
[](StringView s) {
|
||||
VERIFY(s.is_empty());
|
||||
use_color = false;
|
||||
return true;
|
||||
},
|
||||
|
|
|
@ -227,7 +227,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
return 0;
|
||||
}
|
||||
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
|
|
@ -33,7 +33,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
args_parser.parse(arguments);
|
||||
|
||||
if (paths.size() < 2) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
|
|
@ -35,12 +35,12 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
"body-numbering",
|
||||
'b',
|
||||
"style",
|
||||
[&number_style](char const* s) {
|
||||
if (!strcmp(s, "t"))
|
||||
[&number_style](StringView s) {
|
||||
if (s == "t"sv)
|
||||
number_style = NumberNonEmptyLines;
|
||||
else if (!strcmp(s, "a"))
|
||||
else if (s == "a"sv)
|
||||
number_style = NumberAllLines;
|
||||
else if (!strcmp(s, "n"))
|
||||
else if (s == "n"sv)
|
||||
number_style = NumberNoLines;
|
||||
else
|
||||
return false;
|
||||
|
|
|
@ -63,7 +63,7 @@ ErrorOr<int> serenity_main(Main::Arguments args)
|
|||
auto number = StringView { omit_pid_value, strlen(omit_pid_value) }.to_uint();
|
||||
if (!number.has_value()) {
|
||||
warnln("Invalid value for -o");
|
||||
args_parser.print_usage(stderr, args.argv[0]);
|
||||
args_parser.print_usage(stderr, args.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
pid_to_omit = number.value();
|
||||
|
|
|
@ -172,8 +172,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.long_name = "header",
|
||||
.short_name = 'H',
|
||||
.value_name = "key:value",
|
||||
.accept_value = [&](auto* s) {
|
||||
StringView header { s, strlen(s) };
|
||||
.accept_value = [&](StringView header) {
|
||||
auto split = header.find(':');
|
||||
if (!split.has_value())
|
||||
return false;
|
||||
|
@ -186,8 +185,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.long_name = "auth",
|
||||
.short_name = 'u',
|
||||
.value_name = "username:password",
|
||||
.accept_value = [&](auto* s) {
|
||||
StringView input { s, strlen(s) };
|
||||
.accept_value = [&](StringView input) {
|
||||
if (!input.contains(':'))
|
||||
return false;
|
||||
|
||||
|
|
|
@ -72,7 +72,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
}
|
||||
|
||||
if (pid_argument.is_empty() && command.is_empty() && !all_processes) {
|
||||
args_parser.print_usage(stdout, arguments.argv[0]);
|
||||
args_parser.print_usage(stdout, arguments.strings[0]);
|
||||
print_types();
|
||||
return 0;
|
||||
}
|
||||
|
|
|
@ -242,7 +242,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
args_parser.parse(arguments);
|
||||
|
||||
if (arguments.argc < 3) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return Error::from_errno(EINVAL);
|
||||
}
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
args_parser.parse(arguments);
|
||||
|
||||
if (!force && paths.is_empty()) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
|
|
@ -326,7 +326,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.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)
|
||||
|
|
|
@ -108,8 +108,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
nullptr,
|
||||
't',
|
||||
"format",
|
||||
[&string_offset_format](char const* s) {
|
||||
StringView value = { s, strlen(s) };
|
||||
[&string_offset_format](StringView value) {
|
||||
if (value == "d") {
|
||||
string_offset_format = StringOffsetFormat::Decimal;
|
||||
} else if (value == "o") {
|
||||
|
|
|
@ -69,7 +69,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
}
|
||||
|
||||
if (syscall_arguments.is_empty()) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
|
|
@ -107,7 +107,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
args_parser.parse(arguments);
|
||||
|
||||
if (!show_all && variables.is_empty()) {
|
||||
args_parser.print_usage(stdout, arguments.argv[0]);
|
||||
args_parser.print_usage(stdout, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
|
|
@ -150,7 +150,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
args_parser.parse(arguments);
|
||||
|
||||
if (arguments.strings.size() <= 2 && arguments.strings[1] != "list"sv) {
|
||||
args_parser.print_usage_terminal(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage_terminal(stderr, arguments.strings[0]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
|
@ -25,8 +25,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.long_name = "unveil",
|
||||
.short_name = 'u',
|
||||
.value_name = "path",
|
||||
.accept_value = [&](auto* s) {
|
||||
StringView path { s, strlen(s) };
|
||||
.accept_value = [&](StringView path) {
|
||||
if (path.is_empty())
|
||||
return false;
|
||||
auto maybe_error = Core::System::unveil(path, permissions);
|
||||
|
@ -41,7 +40,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.help_string = "Lock the veil",
|
||||
.long_name = "lock",
|
||||
.short_name = 'l',
|
||||
.accept_value = [&](auto*) {
|
||||
.accept_value = [&](StringView) {
|
||||
auto maybe_error = Core::System::unveil(nullptr, nullptr);
|
||||
if (maybe_error.is_error()) {
|
||||
warnln("unveil(nullptr, nullptr): {}", maybe_error.error());
|
||||
|
@ -54,8 +53,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.name = "path",
|
||||
.min_values = 0,
|
||||
.max_values = INT_MAX,
|
||||
.accept_value = [&](auto* s) {
|
||||
auto maybe_error = Core::System::access({ s, strlen(s) }, X_OK);
|
||||
.accept_value = [&](StringView s) {
|
||||
auto maybe_error = Core::System::access(s, X_OK);
|
||||
if (maybe_error.is_error())
|
||||
warnln("'{}' - fail: {}", s, maybe_error.error());
|
||||
else
|
||||
|
|
|
@ -141,8 +141,7 @@ static void parse_args(Main::Arguments arguments, TopOption& top_option)
|
|||
"sort-by",
|
||||
's',
|
||||
nullptr,
|
||||
[&top_option](char const* s) {
|
||||
StringView sort_by_option { s, strlen(s) };
|
||||
[&top_option](StringView sort_by_option) {
|
||||
if (sort_by_option == "pid"sv)
|
||||
top_option.sort_by = TopOption::SortBy::Pid;
|
||||
else if (sort_by_option == "tid"sv)
|
||||
|
|
|
@ -111,19 +111,19 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
|
||||
if (!transform_flag && !delete_flag && !squeeze_flag) {
|
||||
warnln("tr: Missing operand");
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (delete_flag && squeeze_flag && to_chars.is_empty()) {
|
||||
warnln("tr: Combined delete and squeeze operations need two sets of characters");
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (delete_flag && !squeeze_flag && !to_chars.is_empty()) {
|
||||
warnln("tr: Only one set of characters may be given when deleting without squeezing");
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
|
|
@ -33,12 +33,12 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
args_parser.parse(arguments);
|
||||
|
||||
if (resize.is_empty() && reference.is_empty()) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!resize.is_empty() && !reference.is_empty()) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
@ -61,7 +61,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
|
||||
auto size_opt = str.to_int<off_t>();
|
||||
if (!size_opt.has_value()) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
size = size_opt.value();
|
||||
|
|
|
@ -48,7 +48,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
if (*test_name == 'k')
|
||||
return kill_test();
|
||||
if (*test_name != 'n') {
|
||||
args_parser.print_usage(stdout, arguments.argv[0]);
|
||||
args_parser.print_usage(stdout, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
|
|
@ -190,7 +190,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
}
|
||||
|
||||
if (!s_disassembly_attempted) {
|
||||
args_parser.print_usage(stderr, arguments.argv[0]);
|
||||
args_parser.print_usage(stderr, arguments.strings[0]);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
|
|
|
@ -296,9 +296,9 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.long_name = "link",
|
||||
.short_name = 'l',
|
||||
.value_name = "file",
|
||||
.accept_value = [&](char const* str) {
|
||||
if (auto v = StringView { str, strlen(str) }; !v.is_empty()) {
|
||||
modules_to_link_in.append(v);
|
||||
.accept_value = [&](StringView str) {
|
||||
if (!str.is_empty()) {
|
||||
modules_to_link_in.append(str);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
@ -310,8 +310,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
|||
.long_name = "arg",
|
||||
.short_name = 0,
|
||||
.value_name = "u64",
|
||||
.accept_value = [&](char const* str) -> bool {
|
||||
if (auto v = StringView { str, strlen(str) }.to_uint<u64>(); v.has_value()) {
|
||||
.accept_value = [&](StringView str) -> bool {
|
||||
if (auto v = str.to_uint<u64>(); v.has_value()) {
|
||||
values_to_push.append(v.value());
|
||||
return true;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue