-
Notifications
You must be signed in to change notification settings - Fork 5
/
getopt_pp.cpp
307 lines (263 loc) · 8.95 KB
/
getopt_pp.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
GetOpt_pp: Yet another C++ version of getopt.
This file is part of GetOpt_pp.
Copyright (C) Daniel Gutson, FuDePAN 2007-2010
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt in the root directory or
copy at http://www.boost.org/LICENSE_1_0.txt)
GetOpt_pp IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <fstream>
#if __APPLE__
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#elif _WIN32
#include <stdio.h>
#define environ _environ
#else
#include <unistd.h>
#endif
#include "getopt_pp.h"
namespace GetOpt
{
GETOPT_INLINE Token* GetOpt_pp::_add_token(const std::string& value, Token::Type type)
{
Token* const ret = new Token(value, type);
if (_first_token == NULL)
_first_token = ret;
else
_last_token->link_to(ret);
_last_token = ret;
return ret;
}
GETOPT_INLINE void GetOpt_pp::_init_flags()
{
std::stringstream ss;
_flags = ss.flags();
}
GETOPT_INLINE void GetOpt_pp::_parse_sub_file(const std::string& file)
{
std::ifstream ifile(file.c_str());
if (!ifile)
throw OptionsFileNotFoundEx(file);
std::vector<std::string> args;
std::string arg;
while (ifile >> arg)
args.push_back(arg);
_parse(args);
}
GETOPT_INLINE void GetOpt_pp::_parse(const std::vector<std::string>& args)
{
bool any_option_processed = false;
const size_t argc = args.size();
size_t start = 0;
if ( _app_name.empty() )
{
_app_name = args[0];
start = 1;
}
// parse arguments by their '-' or '--':
// (this will be a state machine soon)
for (size_t i = start; i < argc; i++)
{
const std::string& currentArg = args[i];
if (currentArg[0] == '-' && currentArg.size() > 1)
{
// see what's next, differentiate whether it's short or long:
if (currentArg[1] == '-')
{
if ( currentArg.size() > 2 )
{
// long option
_longOps[currentArg.substr(2)].token = _add_token(currentArg.substr(2), Token::LongOption);
}
else
{
// it's the -- option alone
_longOps[currentArg].token = _add_token(currentArg, Token::GlobalArgument);
}
any_option_processed = true;
}
else
{
// check if it is a negative number: rules
// * floating point negative numbers are straight classified as 'arguments'
// * integer negative numbers of more than 1 digit length are also 'arguments'
// * integer negatives of 1 digit length can be either arguments or short options.
// * anything else: short options.
int anInt;
float aFloat;
std::stringstream dummy;
if ( convert(currentArg, anInt, dummy.flags()) == _Option::OK )
{
if ( currentArg.size() > 2 ) // if it's larger than -d (d=digit), then assume it's a negative number:
_add_token(currentArg, any_option_processed ? Token::UnknownYet : Token::GlobalArgument);
else // size == 2: it's a 1 digit negative number
_shortOps[currentArg[1]].token = _add_token(currentArg, Token::PossibleNegativeArgument);
}
else if ( convert(currentArg, aFloat, dummy.flags()) == _Option::OK )
_add_token(currentArg, any_option_processed ? Token::UnknownYet : Token::GlobalArgument);
else
{
// short option
// iterate over all of them, keeping the last one in currentData
// (so the intermediates will generate 'existent' arguments, as of '-abc')
for( size_t j = 1; j < currentArg.size(); j++ )
_shortOps[currentArg[j]].token = _add_token(std::string(currentArg, j, 1), Token::ShortOption);
}
any_option_processed = true;
}
}
else if ( currentArg[0] == '@' && currentArg.size() > 1 )
{
// suboptions file
_parse_sub_file(currentArg.substr(1));
}
else
{
_add_token(currentArg, any_option_processed ? Token::UnknownYet : Token::GlobalArgument);
}
}
_last = _Option::OK; // TODO: IMPROVE!!
}
GETOPT_INLINE void GetOpt_pp::_parse_env()
{
// this will be optimized in version 3
std::string var_name;
std::string var_value;
size_t var = 0;
std::string::size_type pos;
OptionData* data;
while (environ[var] != NULL)
{
var_name = environ[var];
pos = var_name.find('=');
if (pos != std::string::npos)
{
var_value = var_name.substr(pos + 1);
var_name = var_name.substr(0, pos);
if (_longOps.find(var_name) == _longOps.end())
{
data = &_longOps[var_name];
data->token = _add_token(var_name, Token::LongOption);
data->flags = OptionData::Envir;
_add_token(var_value, Token::OptionArgument);
}
}
else
(data = &_longOps[var_name])->flags = OptionData::Envir;
var++;
}
}
GETOPT_INLINE void GetOpt_pp::_argc_argv_to_vector(int argc, const char* const* const argv, std::vector<std::string>& args)
{
for (int i = 0; i < argc; i++)
args.push_back(argv[i]);
}
GETOPT_INLINE GetOpt_pp::TokensDeleter::~TokensDeleter()
{
Token* next;
Token* current(_first);
while (current != NULL)
{
next = current->next;
delete current;
current = next;
}
}
GETOPT_INLINE GetOpt_pp::GetOpt_pp(int argc, const char* const* const argv)
: _exc(std::ios_base::goodbit), _first_token(NULL), _last_token(NULL), _tokens_deleter(_first_token)
{
_init_flags();
std::vector<std::string> args;
_argc_argv_to_vector(argc, argv, args);
_parse(args);
}
GETOPT_INLINE GetOpt_pp::GetOpt_pp(int argc, const char* const* const argv, _EnvTag)
: _first_token(NULL), _last_token(NULL), _tokens_deleter(_first_token)
{
_init_flags();
std::vector<std::string> args;
_argc_argv_to_vector(argc, argv, args);
_parse(args);
_parse_env();
}
GETOPT_INLINE GetOpt_pp& GetOpt_pp::operator >> (const _Option& opt) throw(GetOptEx)
{
if (_last != _Option::ParsingError)
{
_last = opt(_shortOps, _longOps, _first_token, _flags);
switch (_last)
{
case _Option::OK:
break;
case _Option::OptionNotFound:
if (_exc & std::ios_base::eofbit)
throw OptionNotFoundEx();
break;
case _Option::BadType:
if (_exc & std::ios_base::failbit)
throw InvalidFormatEx();
break;
case _Option::NoArgs:
if (_exc & std::ios_base::eofbit)
throw ArgumentNotFoundEx();
break;
case _Option::TooManyArgs:
if (_exc & std::ios_base::failbit)
throw TooManyArgumentsEx();
break;
case _Option::OptionNotFound_NoEx:
break; // Ok, it will be read by casting to bool
case _Option::ParsingError:
break; // just to disable warning
}
}
else if (_exc & std::ios_base::failbit)
throw ParsingErrorEx();
return *this;
}
GETOPT_INLINE GetOpt_pp& GetOpt_pp::operator >> (std::ios_base & (*iomanip)(std::ios_base&))
{
std::stringstream ss;
ss.flags(_flags);
_flags = (ss << iomanip).flags();
return *this;
}
GETOPT_INLINE bool GetOpt_pp::options_remain() const
{
bool remain = false;
ShortOptions::const_iterator it = _shortOps.begin();
while (it != _shortOps.end() && !remain)
{
remain = (it->second.flags == OptionData::CmdLine_NotExtracted);
++it;
}
if (!remain)
{
LongOptions::const_iterator it = _longOps.begin();
while (it != _longOps.end() && !remain)
{
remain = (it->second.flags == OptionData::CmdLine_NotExtracted);
++it;
}
}
if (!remain)
{
// check for the global arguments:
Token* token = _first_token;
while (!remain && token != NULL)
{
remain = (token->type == Token::GlobalArgument || token->type == Token::UnknownYet);
token = token->next;
}
}
return remain;
}
}