-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargument_parser.cpp
97 lines (92 loc) · 2.48 KB
/
argument_parser.cpp
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
90
91
92
93
94
95
96
97
#include "argument_parser.h"
#include "string.h"
#include "exceptions.h"
#include <charconv>
#include <iostream>
#include <regex>
ArgumentParser::ArgumentParser(int argc, char *argv[])
{
for (int i = 1; i < argc; i++)
{
auto arg = argv[i];
// ----- helper lambdas -----
// performs char* to char* comparison, compares given string with arg
auto argIs = [&arg](const char *s)
{
return strcmp(arg, s) == 0;
};
// attempts to return the next argument, if there is no more avaliable, throws exception
// also escapes LF
auto nextArg = [&]()
{
if (i + 1 == argc)
throw TooFewArgumentsException();
string ret = argv[++i];
ret = regex_replace(ret, regex("\n"), "\\n");
return ret;
};
// options
if (argIs("-a") || argIs("--address"))
{
_ip = nextArg();
}
else if (argIs("-p") || argIs("--port"))
{
auto tmp = nextArg();
from_chars(tmp.begin().base(), tmp.end().base(), _port);
}
else if (argIs("-h") || argIs("--help"))
{
cout << _help << endl;
exit(0);
}
// commands
else if (argIs("register"))
{
setCommand(Command::REGISTER);
_params.push_back(nextArg());
_params.push_back(nextArg());
}
else if (argIs("login"))
{
setCommand(Command::LOGIN);
_params.push_back(nextArg());
_params.push_back(nextArg());
}
else if (argIs("list"))
{
setCommand(Command::LIST);
}
else if (argIs("send"))
{
setCommand(Command::SEND);
_params.push_back(nextArg());
_params.push_back(nextArg());
_params.push_back(nextArg());
}
else if (argIs("fetch"))
{
setCommand(Command::FETCH);
_params.push_back(nextArg());
}
else if (argIs("logout"))
{
setCommand(Command::LOGOUT);
}
else
{
if (_command == Command::UNKNOWN)
throw InvalidCommandException();
throw TooManyArgumentsException();
}
}
}
void ArgumentParser::setCommand(Command s)
{
if (_command == Command::UNKNOWN)
{
_command = s;
return;
}
throw CommandRedefinitionException();
}