mf/main.cpp

92 lines
2.2 KiB
C++

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include "database.h"
#include "subcommands.h"
#include "blankie/cliparse.h"
void sqlite_error_logger(void*, int error_code, const char* message) {
// For some reason, Sqlite3Statement::bind_text causes this
if (error_code == SQLITE_SCHEMA) {
return;
}
fprintf(stderr, "sqlite: (%d) %s\n", error_code, message);
}
void exit_handler() {
sqlite3_shutdown();
}
void real_main(int argc, char** argv);
int main(int argc, char** argv) {
sqlite3_config(SQLITE_CONFIG_LOG, sqlite_error_logger, nullptr);
int error_code = sqlite3_initialize();
if (error_code != SQLITE_OK) {
throw Sqlite3Exception(error_code, nullptr);
}
atexit(exit_handler);
try {
real_main(argc, argv);
} catch (...) {
sqlite3_shutdown();
throw;
}
}
void real_main(int argc, char** argv) {
Parser parser("mf", {
{"directory", 'C', false, blankie::cliparse::ArgumentRequired::Yes},
}, 1, ~static_cast<size_t>(0));
try {
parser.parse(argc, argv);
} catch (const blankie::cliparse::invalid_argument_count& e) {
fprintf(stderr, HELP_TEXT, parser.program_name);
exit(1);
} catch (const blankie::cliparse::exception& e) {
fprintf(stderr, "failed to parse arguments: %s\n", e.what());
exit(1);
}
if (parser.flag('C')->used) {
if (chdir(parser.flag('C')->argument)) {
perror("failed to chdir");
exit(1);
}
}
auto is = [&](const char* subcommand) {
return strcmp(parser.arguments[0], subcommand) == 0;
};
if (is("create")) {
subcommand_create(parser);
} else if (is("search")) {
subcommand_search(parser);
} else if (is("prune")) {
subcommand_prune(parser);
} else if (is("info") || is("show")) {
subcommand_info(parser);
} else if (is("delete")) {
subcommand_delete(parser);
} else if (is("edit")) {
subcommand_edit(parser);
} else if (is("get")) {
subcommand_get(parser);
} else if (is("set")) {
subcommand_set(parser);
} else {
fprintf(stderr, HELP_TEXT, parser.program_name);
exit(1);
}
}