Port arg_parse.{cpp,hpp} to C++.

This commit is contained in:
Nicolás A. Ortega Froysa 2024-10-09 20:02:50 +02:00
parent 836daeb69b
commit e86ca506c1
2 changed files with 15 additions and 20 deletions

View File

@ -17,13 +17,11 @@
*/ */
#include "arg_parse.hpp" #include "arg_parse.hpp"
#include <string.h> enum cmd_id parse_args(const std::string &cmd) {
for(const auto &command : commands) {
enum cmd_id parse_args(const char *cmd) { for(const auto &alias : command.second) {
for(int i = 0; i < (int)ARRAY_LEN(commands); ++i) { if(cmd == alias)
for(int j = 0; j < (int)ARRAY_LEN(commands[i].str); ++j) { return command.first;
if(commands[i].str[j] && strcmp(commands[i].str[j], cmd) == 0)
return commands[i].id;
} }
} }

View File

@ -17,7 +17,10 @@
*/ */
#pragma once #pragma once
#include <stdio.h> #include <iostream>
#include <string>
#include <map>
#include <vector>
enum cmd_id { enum cmd_id {
CMD_UNKNOWN = 0, CMD_UNKNOWN = 0,
@ -26,35 +29,29 @@ enum cmd_id {
CMD_VERSION, CMD_VERSION,
}; };
struct cmd { static const std::map<enum cmd_id, std::vector<std::string>> commands = {
enum cmd_id id;
const char *str[3];
};
static const struct cmd commands[] = {
{ CMD_ADD, {"add", "new"} }, { CMD_ADD, {"add", "new"} },
{ CMD_HELP, {"help", "-h", "--help"} }, { CMD_HELP, {"help", "-h", "--help"} },
{ CMD_VERSION, {"version", "-v", "--version"} }, { CMD_VERSION, {"version", "-v", "--version"} },
}; };
static inline void print_version(void) { static inline void print_version(void) {
printf("menu-helper v%s\n\n", VERSION); std::cout << "menu-helper v" << VERSION << "\n" << std::endl;
} }
static inline void print_usage(void) { static inline void print_usage(void) {
printf("USAGE: menu-helper <cmd> [options]\n\n"); std::cout << "USAGE: menu-helper <cmd> [options]\n" << std::endl;
} }
static inline void print_help(void) { static inline void print_help(void) {
print_version(); print_version();
print_usage(); print_usage();
printf("COMMANDS:\n" std::cout << "COMMANDS:\n"
"\tadd, new Add a new recipe to the database\n" "\tadd, new Add a new recipe to the database\n"
"\thelp, -h, --help Show this help information.\n" "\thelp, -h, --help Show this help information.\n"
"\tversion, -v, --version Show version information.\n" "\tversion, -v, --version Show version information.\n"
"\n"); << std::endl;
} }
enum cmd_id parse_args(const std::string &cmd);
enum cmd_id parse_args(const char *cmd);