1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 01:47:34 +00:00

Userland+Terminal: Port to new CArgsParser API

While at it, also add some niceties and fix some things.
This commit is contained in:
Sergey Bugaev 2020-01-27 20:25:36 +03:00 committed by Andreas Kling
parent 9276582535
commit f983dfe319
22 changed files with 392 additions and 653 deletions

View file

@ -27,74 +27,32 @@
#include <AK/ByteBuffer.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <LibCore/CArgsParser.h>
#include <LibCore/CFile.h>
#include <LibGUI/GApplication.h>
#include <LibGUI/GClipboard.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
struct Options {
String data;
String type { "text" };
StringView type { "text" };
};
void print_usage(FILE* stream, const char* argv0)
{
fprintf(
stream,
"Usage:\n"
"\t%s [--type type] text\n"
"\t%s [--type type] < file\n"
"\n"
"\t-t type, --type type\tPick a type.\n"
"\t-h, --help\t\tPrint this help message.\n",
argv0,
argv0);
}
Options parse_options(int argc, char* argv[])
{
const char* type = nullptr;
Vector<const char*> text;
CArgsParser args_parser;
args_parser.add_option(type, "Pick a type", "type", 't', "type");
args_parser.add_positional_argument(text, "Text to copy", "text", CArgsParser::Required::No);
args_parser.parse(argc, argv);
Options options;
options.type = type;
static struct option long_options[] = {
{ "type", required_argument, 0, 't' },
{ "help", no_argument, 0, 'h' },
{ 0, 0, 0, 0 }
};
while (true) {
int option_index;
int c = getopt_long(argc, argv, "t:h", long_options, &option_index);
if (c == -1)
break;
if (c == 0)
c = long_options[option_index].val;
switch (c) {
case 't':
options.type = optarg;
break;
case 'h':
print_usage(stdout, argv[0]);
exit(0);
default:
print_usage(stderr, argv[0]);
exit(1);
}
}
if (optind < argc) {
// Copy the rest of our command-line args.
StringBuilder builder;
bool first = true;
for (int i = optind; i < argc; i++) {
if (!first)
builder.append(' ');
first = false;
builder.append(argv[i]);
}
options.data = builder.to_string();
} else {
if (text.is_empty()) {
// Copy our stdin.
auto c_stdin = CFile::construct();
bool success = c_stdin->open(
@ -105,6 +63,17 @@ Options parse_options(int argc, char* argv[])
auto buffer = c_stdin->read_all();
dbg() << "Read size " << buffer.size();
options.data = String((char*)buffer.data(), buffer.size());
} else {
// Copy the rest of our command-line args.
StringBuilder builder;
bool first = true;
for (auto& word : text) {
if (!first)
builder.append(' ');
first = false;
builder.append(word);
}
options.data = builder.to_string();
}
return options;