1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
/*
* This file is part of smolbote. It's copyrighted by the contributors recorded
* in the version control history of the file, available from its original
* location: https://neueland.iserlohn-fortress.net/cgit/smolbote
*
* SPDX-License-Identifier: GPL-3.0
*/
#ifndef SMOLBOTE_CMD_HPP
#define SMOLBOTE_CMD_HPP
#include "version.h"
#include <QCommandLineParser>
#include <QCoreApplication>
#include <functional>
#include <iostream>
namespace command_line
{
template <typename T>
using subcommand_fn = std::function<int(const QStringList &, T &)>;
template <typename T>
using map = std::unordered_map<std::string, subcommand_fn<T>>;
// a helper function to join the keys of a command_map into a string
template <typename T>
[[nodiscard]] inline QString join_keys(const map<T> &map, const QString sep = ", ")
{
QString k;
for(auto it = map.cbegin(); it != map.cend(); ++it) {
k += QString::fromStdString(it->first);
if(std::next(it) != map.cend()) {
k += sep;
}
}
return k;
}
template <typename T>
[[nodiscard]] std::function<int(T &)> process(T &app, const map<T> &map, const std::string &d)
{
const QCommandLineOption build({ "b", "build" }, "Display build information.");
const QCommandLineOption config({ "c", "config" }, "Set the configuration file.", "file");
const QCommandLineOption noRemote("no-remote", "Do not accept or send remote commands.");
QCommandLineParser parser;
parser.setApplicationDescription("smolbote: yet another no-frills browser");
parser.setOptionsAfterPositionalArgumentsMode(QCommandLineParser::ParseAsPositionalArguments);
parser.addHelpOption();
parser.addVersionOption();
parser.addOption(build);
parser.addOption(config);
parser.addOption(noRemote);
parser.addPositionalArgument("subcommand", QString("%1; default: %2").arg(join_keys(map), QString::fromStdString(d)));
parser.addPositionalArgument("urls", "List of URLs to open.");
parser.process(app);
if(parser.isSet(build)) {
std::cout << app.applicationName().toStdString() << " " << poi_Version << std::endl;
exit(0);
}
if constexpr(requires { app.loadConfiguration(parser.value(config)); }) {
app.loadConfiguration(parser.value(config));
} else {
qDebug("warning: cannot init configuration");
}
if constexpr(requires { app.enableRemote(true); }) {
app.enableRemote(!parser.isSet(noRemote));
}
const auto args = parser.positionalArguments();
if(args.count() >= 1) {
auto i = map.find(args.first().toStdString());
if(i != map.end())
return std::bind(i->second, args, std::placeholders::_1);
}
return std::bind(map.at(d), args, std::placeholders::_1);
}
} // namespace
#endif
|