Files
kindle2notes/typefactory/main.cpp
T

117 lines
2.8 KiB
C++

#include <array>
#include <getopt.h>
#include <iostream>
#include <string>
#include "convertasciidoc.h"
#include "convertlatex.h"
#include "convertmarkdown.h"
#include "convertorg.h"
#include "typefactory.h"
#ifndef KINDLE2NOTES_VERSION
#define KINDLE2NOTES_VERSION "unknown"
#endif
using ConverterFactory = TypeFactory<std::string, Converter, std::string>;
static constexpr std::array<const char *, 4> kSupportedTypes = {
"latex", "md", "org", "adoc"
};
struct CliArgs {
std::string input;
std::string output;
std::string type;
bool version = false;
};
static void print_usage (const char *argv0) {
std::cerr << "Usage: " << argv0
<< " --input <file> --output <file> --type <type>\n"
<< " " << argv0 << " --version\n";
}
static void print_supported_types() {
std::cerr << "Supported types:";
for (const char *type : kSupportedTypes)
std::cerr << ' ' << type;
std::cerr << '\n';
}
static ConverterFactory build_converter_factory() {
ConverterFactory factory;
factory.registerType<ConverterAsciiDoc> ("adoc");
factory.registerType<ConverterLatex> ("latex");
factory.registerType<ConverterMarkdown> ("md");
factory.registerType<ConverterOrg> ("org");
return factory;
}
static bool parse_args (int argc, char **argv, CliArgs &out) {
static option long_opts[] = {
{"input", required_argument, nullptr, 'i'},
{"output", required_argument, nullptr, 'o'},
{"type", required_argument, nullptr, 't'},
{"version", no_argument, nullptr, 'v'},
{"help", no_argument, nullptr, 'h'},
{nullptr, 0, nullptr, 0 }
};
int c = 0;
while ((c = ::getopt_long (argc, argv, "i:o:t:vh", long_opts, nullptr)) != -1) {
switch (c) {
case 'i':
out.input = optarg;
break;
case 'o':
out.output = optarg;
break;
case 't':
out.type = optarg;
break;
case 'v':
out.version = true;
break;
case 'h':
print_usage (argv[0]);
return false;
default:
print_usage (argv[0]);
return false;
}
}
if (!out.version &&
(out.input.empty() || out.output.empty() || out.type.empty())) {
print_usage (argv[0]);
return false;
}
return true;
}
int main (int argc, char **argv) {
CliArgs args;
if (!parse_args (argc, argv, args))
return 1;
if (args.version) {
std::cout << "kindle2notes " << KINDLE2NOTES_VERSION << '\n';
return 0;
}
const ConverterFactory factory = build_converter_factory();
if (!factory.contains (args.type)) {
std::cerr << "Unsupported output type: " << args.type << '\n';
print_supported_types();
return 1;
}
const auto converter = factory.create (args.type, args.input);
if (!converter->save (args.output))
return converter->error_code();
return 0;
}