-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathToolBase.cpp
More file actions
774 lines (686 loc) · 20.5 KB
/
ToolBase.cpp
File metadata and controls
774 lines (686 loc) · 20.5 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
#include "ToolBase.h"
#include <QTextStream>
#include <QTimer>
#include "Exceptions.h"
#include "Helper.h"
#include "Settings.h"
#include "VersatileFile.h"
ToolBase::ToolBase(int& argc, char *argv[])
: QCoreApplication(argc, argv)
, exit_event_loop_(true)
, exit_error_state_(false)
{
QCoreApplication::setApplicationVersion(version());
}
void ToolBase::setExitEventLoopAfterMain(bool exit_event_loop)
{
exit_event_loop_ = exit_event_loop;
}
void ToolBase::setExitErrorState(bool exit_error_state)
{
exit_error_state_ = exit_error_state;
}
QString ToolBase::version()
{
return QString(CPPCORE_VERSION);
}
qulonglong ToolBase::encryptionKey(QString context)
{
//get compiled-in key
QString crypt_key = QString(CRYPT_KEY).trimmed();
if (crypt_key=="") THROW(ProgrammingException, "Cannot decrypt string in context '" + context + "' because CRYPT_KEY is not set!");
//convert key to integer - a valid example key would be e.g. "0x0c2ad4a4acb9f023"
bool ok = true;
qulonglong crypt_key_int = crypt_key.toULongLong(&ok, 16);
if (!crypt_key.startsWith("0x") || !ok) THROW(ProgrammingException, "Cannot decrypt string in context '" + context + "' because CRYPT_KEY cannot be interpreted as a hex number!");
return crypt_key_int;
}
void ToolBase::setDescription(QString description)
{
description_ = description;
}
void ToolBase::setExtendedDescription(QStringList description)
{
description_extended_ = description;
}
void ToolBase::changeLog(int y, int m, int d, QString text)
{
changelog_.append(ChangeLogEntry(y, m, d, text));
}
void ToolBase::addFlag(QString name, QString desc)
{
ParameterData data(name, ParameterType::FLAG, desc, true, false);
addParameter(data);
}
void ToolBase::addInt(QString name, QString desc, bool optional, int default_value)
{
ParameterData data(name, ParameterType::INT, desc, optional, default_value);
addParameter(data);
}
void ToolBase::addFloat(QString name, QString desc, bool optional, double default_value)
{
ParameterData data(name, ParameterType::FLOAT, desc, optional, default_value);
addParameter(data);
}
void ToolBase::addEnum(QString name, QString desc, bool optional, QStringList values, QString default_value)
{
if (optional && !values.contains(default_value))
{
THROW(ProgrammingException, "Optional enum parameter '" + name + "' has invalid default value '" + default_value + "'. Valid are: '" + values.join(",") + "'!");
}
ParameterData data(name, ParameterType::ENUM, desc, optional, default_value);
data.options.insert("values", values);
addParameter(data);
}
void ToolBase::addString(QString name, QString desc, bool optional, QString default_value)
{
ParameterData data(name, ParameterType::STRING, desc, optional, default_value);
addParameter(data);
}
void ToolBase::addInfile(QString name, QString desc, bool optional, bool check_readable)
{
ParameterData data(name, ParameterType::INFILE, desc, optional, "");
data.options.insert("check_readable", check_readable);
addParameter(data);
}
void ToolBase::addOutfile(QString name, QString desc, bool optional, bool check_writable)
{
ParameterData data(name, ParameterType::OUTFILE, desc, optional, "");
data.options.insert("check_writable", check_writable);
addParameter(data);
}
void ToolBase::addInfileList(QString name, QString desc, bool optional, bool check_readable)
{
ParameterData data(name, ParameterType::INFILELIST, desc, optional, "");
data.options.insert("check_readable", check_readable);
addParameter(data);
}
bool ToolBase::getFlag(QString name) const
{
int index = checkParameterExists(name, ParameterType::FLAG);
return parameters_[index].value.toBool();
}
int ToolBase::getInt(QString name) const
{
int index = checkParameterExists(name, ParameterType::INT);
return parameters_[index].value.toInt();
}
double ToolBase::getFloat(QString name) const
{
int index = checkParameterExists(name, ParameterType::FLOAT);
return parameters_[index].value.toDouble();
}
QString ToolBase::getString(QString name) const
{
int index = checkParameterExists(name, ParameterType::STRING);
return parameters_[index].value.toString();
}
QString ToolBase::getEnum(QString name) const
{
int index = checkParameterExists(name, ParameterType::ENUM);
return parameters_[index].value.toString();
}
QString ToolBase::getInfile(QString name) const
{
int index = checkParameterExists(name, ParameterType::INFILE);
return parameters_[index].value.toString();
}
QString ToolBase::getOutfile(QString name) const
{
int index = checkParameterExists(name, ParameterType::OUTFILE);
return parameters_[index].value.toString();
}
QStringList ToolBase::getInfileList(QString name) const
{
int index = checkParameterExists(name, ParameterType::INFILELIST);
QStringList output = parameters_[index].value.toStringList();
if (output.count()==1 && output[0]=="") output.clear();
return output;
}
bool ToolBase::parseCommandLine()
{
QStringList args = QCoreApplication::arguments();
//no arguments => show help if a mandatory parameter is present
if (args.count()==1)
{
foreach(const ParameterData& data, parameters_)
{
if (!data.optional)
{
printHelp();
return false;
}
}
}
//special parameters
if(args.contains("--help") || args.contains("--h") || args.contains("-help"))
{
printHelp();
return false;
}
if(args.contains("--version"))
{
printVersion();
return false;
}
if(args.contains("--changelog"))
{
printChangelog();
return false;
}
if(args.contains("--tdx"))
{
storeTDXml();
return false;
}
//handle settings override
int settings_idx = args.indexOf("--settings");
if(settings_idx!=-1)
{
if (settings_idx==args.count()-1) THROW(CommandLineParsingException, "Parameter '--settings' given without argument.");
Settings::setSettingsOverride(args[settings_idx+1]);
args.removeAt(settings_idx);
args.removeAt(settings_idx);
}
//parse command line
for (int i=1; i<args.count(); ++i)
{
QString par = args[i];
//error: trailing argument
if (par[0] != '-')
{
THROW(CommandLineParsingException, "Trailing parameter '" + par + "' given.");
}
par = par.mid(1);
//error: parameter unknown
int index = parameterIndex(par);
if (index==-1)
{
THROW(CommandLineParsingException, "Unknown parameter '" + par + "' given.");
}
ParameterData& data = parameters_[index];
//error: parameter without argument
if (data.type!=ParameterType::FLAG && (i+1>=args.count() || (args[i+1]!="-" && args[i+1][0]=='-')))
{
THROW(CommandLineParsingException, "Parameter '" + par + "' given without argument.");
}
//error: parameter given more than once
if (data.value.isValid())
{
THROW(CommandLineParsingException, "Parameter '" + par + "' given more than once.");
}
//FLAG
if (data.type==ParameterType::FLAG)
{
data.value = true;
}
//INT
else if (data.type==ParameterType::INT)
{
++i;
bool ok = false;
data.value = args[i].toInt(&ok);
if (!ok)
{
THROW(CommandLineParsingException, "Value '" + args[i] + "' given for parameter '" + par + "' cannot be converted to integer.");
}
}
//FLOAT
else if (data.type==ParameterType::FLOAT)
{
++i;
bool ok = false;
data.value = args[i].toDouble(&ok);
if (!ok)
{
THROW(CommandLineParsingException, "Value '" + args[i] + "' given for parameter '" + par + "' cannot be converted to float.");
}
}
//ENUM
else if (data.type==ParameterType::ENUM)
{
++i;
QStringList values = data.options["values"].toStringList();
if (!values.contains(args[i]))
{
THROW(CommandLineParsingException, "Value '" + args[i] +"' given for enum parameter '" + par + "' is not valid. Valid are: '" + values.join(",") + "'.");
}
data.value = args[i];
}
//STRING
else if (data.type==ParameterType::STRING)
{
++i;
data.value = args[i];
}
//INFILE
else if (data.type==ParameterType::INFILE)
{
++i;
if (args[i]!="" && data.options["check_readable"].toBool())
{
if (!VersatileFile(args[i]).isReadable())
{
THROW(CommandLineParsingException, "Input file '" + args[i] +"' given for parameter '" + par + "' is not readable.");
}
}
data.value = args[i];
}
//OUTFILE
else if (data.type==ParameterType::OUTFILE)
{
++i;
if (args[i]!="" && data.options["check_writable"].toBool())
{
if (!Helper::isWritable(args[i]))
{
THROW(CommandLineParsingException, "Output file '" + args[i] +"' given for parameter '" + par + "' is not writable.");
}
}
data.value = args[i];
}
//INFILELIST
else if (data.type==ParameterType::INFILELIST)
{
QStringList files;
int j=i+1;
while(j<args.count() && args[j][0]!='-')
{
if (data.options["check_readable"].toBool())
{
if (!VersatileFile(args[j]).isReadable())
{
THROW(CommandLineParsingException, "Input file '" + args[j] +"' given for parameter '" + par + "' is not readable.");
}
}
files.append(args[j]);
++j;
}
i=j-1;
data.value = files;
}
//UNKNOWN
else
{
THROW(ProgrammingException, "Unknown ToolBase parameter type!");
}
}
//check for missing mandatory parameters
for (int i=0; i<parameters_.count(); ++i)
{
ParameterData& data = parameters_[i];
if (data.optional && !data.value.isValid())
{
data.value = data.default_value;
}
else if(!data.value.isValid())
{
THROW(CommandLineParsingException, "Mandatory parameter '" + data.name + "' not given.");
}
}
return true;
}
void ToolBase::printVersion() const
{
QTextStream stream(stdout);
stream << QCoreApplication::applicationName() << " " << QCoreApplication::applicationVersion() << Qt::endl;
stream << Qt::endl;
}
void ToolBase::printChangelog() const
{
QTextStream stream(stdout);
stream << QCoreApplication::applicationName() << " " << QCoreApplication::applicationVersion() << Qt::endl;
stream << Qt::endl;
foreach(const ChangeLogEntry& e, changelog_)
{
stream << e.date.toString("yyyy-MM-dd") << " " << e.text.trimmed() << Qt::endl;
}
}
void ToolBase::printHelp() const
{
QTextStream stream(stdout);
// find out longest parameter name and matching offset
int max_name = 0;
foreach(const ParameterData& data, parameters_)
{
max_name = qMax(max_name, data.name.length() + typeToArgString(data.type).length());
}
int offset = qMax(20, max_name + 5);
//print general info
stream << QCoreApplication::applicationName() + " (" + QCoreApplication::applicationVersion() + ")" << Qt::endl;
stream << "" << Qt::endl;
stream << description_ << Qt::endl;
QStringList ext = description_extended_;
if (!ext.isEmpty())
{
stream << "" << Qt::endl;
foreach(QString e, ext)
{
stream << e << Qt::endl;
}
}
// print mandatory parameters
bool first_mandatory = true;
foreach(const ParameterData& data, parameters_)
{
if (data.optional) continue;
//header
if (first_mandatory)
{
stream << "" << Qt::endl;
stream << "Mandatory parameters:" << Qt::endl;
first_mandatory = false;
}
//standard output
QString line_start = " -" + data.name + " " + typeToArgString(data.type);
stream << line_start.leftJustified(offset, ' ') << data.desc << Qt::endl;
//special handling of ENUM
if (data.type==ParameterType::ENUM)
{
stream << QString(offset, ' ') << "Valid: '" << data.options["values"].toStringList().join(',') + "'" << Qt::endl;
}
}
// print optional parameters
bool first_optional = true;
foreach(const ParameterData& data, parameters_)
{
if (!data.optional) continue;
//header
if (first_optional)
{
stream << "" << Qt::endl;
stream << "Optional parameters:" << Qt::endl;
first_optional = false;
}
//standard output
QString line_start = " -" + data.name + " " + typeToArgString(data.type);
stream << line_start.leftJustified(offset, ' ') << data.desc << Qt::endl;
stream << QString(offset, ' ') << "Default value: '" << data.default_value.toString() << "'" << Qt::endl;
//special handling of ENUM
if (data.type==ParameterType::ENUM)
{
stream << QString(offset, ' ') << "Valid: '" << data.options["values"].toStringList().join(',') + "'" << Qt::endl;
}
}
// print special parameters
stream << "" << Qt::endl;
stream << "Special parameters:" << Qt::endl;
stream << QString(" --help").leftJustified(offset, ' ') << "Shows this help and exits." << Qt::endl;
stream << QString(" --version").leftJustified(offset, ' ') << "Prints version and exits." << Qt::endl;
stream << QString(" --changelog").leftJustified(offset, ' ') << "Prints changeloge and exits." << Qt::endl;
stream << QString(" --tdx").leftJustified(offset, ' ') << "Writes a Tool Definition Xml file. The file name is the application name with the suffix '.tdx'." << Qt::endl;
stream << QString(" --settings [file]").leftJustified(offset, ' ') << "Settings override file (no other settings files are used)." << Qt::endl;
stream << "" << Qt::endl;
}
void ToolBase::storeTDXml() const
{
QString filename = QCoreApplication::applicationFilePath() + ".tdx";
//write to stream
QSharedPointer<QFile> out_file = Helper::openFileForWriting(filename);
QTextStream stream(out_file.data());
stream.setEncoding(QStringConverter::Utf8);
stream << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" << Qt::endl;
stream << "<TDX version=\"1\">" << Qt::endl;
stream << " <Tool name=\"" << QCoreApplication::applicationName() << "\" version=\"" << QCoreApplication::applicationVersion() << "\">" << Qt::endl;
stream << " <Description>" << description_ << "</Description>" << Qt::endl;
QStringList ext = description_extended_;
if (!ext.isEmpty())
{
stream << " <ExtendedDescription>" << Qt::endl;
foreach(QString e, ext)
{
stream << e << Qt::endl;
}
stream << " </ExtendedDescription>" << Qt::endl;
}
foreach(const ParameterData& data, parameters_)
{
QString tag_name = typeToString(data.type).toLower();
tag_name[0] = tag_name[0].toUpper();
tag_name.replace("list", "List");
stream << " <" << tag_name << " name=\"" << data.name << "\">" << Qt::endl;
stream << " <Description>" << data.desc << "</Description>" << Qt::endl;
switch (data.type)
{
case ParameterType::STRING:
case ParameterType::INT:
case ParameterType::FLOAT:
if (data.optional)
{
stream << " <Optional defaultValue=\"" << data.default_value.toString() << "\" />" << Qt::endl;
}
break;
case ParameterType::INFILE:
case ParameterType::INFILELIST:
case ParameterType::OUTFILE:
if (data.optional)
{
stream << " <Optional />" << Qt::endl;
}
break;
case ParameterType::ENUM:
stream << " <Optional defaultValue=\"" << data.default_value.toString() << "\" />" << Qt::endl;
foreach(const QString& value, data.options["values"].toStringList())
{
stream << " <Value>" << value << "</Value>" << Qt::endl;
}
break;
case ParameterType::FLAG:
case ParameterType::NONE:
break;
}
stream << " </" << tag_name << ">" << Qt::endl;
}
stream << " </Tool>" << Qt::endl;
stream << "</TDX>" << Qt::endl;
}
int ToolBase::execute()
{
QTimer::singleShot(0, this, SLOT(executeInternal()));
return exec();
}
void ToolBase::executeInternal()
{
setup();
sortChangeLog();
//execute main method only if no special parameters were set
bool execute_main = parseCommandLine();
if (execute_main)
{
main();
}
if (!execute_main || exit_event_loop_)
{
exit(0);
}
if (exit_error_state_)
{
exit(1);
}
}
int ToolBase::parameterIndex(QString name) const
{
for (int i=0; i<parameters_.count(); ++i)
{
if (parameters_[i].name==name) return i;
}
return -1;
}
void ToolBase::addParameter(const ToolBase::ParameterData& data)
{
if (parameterIndex(data.name)!=-1)
{
THROW(ProgrammingException, QCoreApplication::applicationName() + " parameter '" + data.name + "' declared twice!");
}
parameters_.append(data);
}
int ToolBase::checkParameterExists(QString name, ParameterType type) const
{
int index = parameterIndex(name);
if (index==-1)
{
THROW(ProgrammingException, QCoreApplication::applicationName() + " parameter '" + name + "' not declared, but used!");
}
if (parameters_[index].type!=type)
{
THROW(ProgrammingException, QCoreApplication::applicationName() + " parameter '" + name + "' is expected to have type '" + typeToString(type) + "', but has type '" + typeToString(parameters_[index].type) + "'!");
}
return index;
}
void ToolBase::sortChangeLog()
{
std::sort(changelog_.begin(), changelog_.end(), [](const ChangeLogEntry& a, const ChangeLogEntry& b){ return a.date>b.date; } );
}
QString ToolBase::typeToString(ToolBase::ParameterType type) const
{
if (type==ParameterType::NONE)
{
return "NONE";
}
else if (type==ParameterType::FLAG)
{
return "FLAG";
}
else if (type==ParameterType::INT)
{
return "INT";
}
else if (type==ParameterType::FLOAT)
{
return "FLOAT";
}
else if (type==ParameterType::ENUM)
{
return "ENUM";
}
else if (type==ParameterType::STRING)
{
return "STRING";
}
else if (type==ParameterType::INFILE)
{
return "INFILE";
}
else if (type==ParameterType::OUTFILE)
{
return "OUTFILE";
}
else if (type==ParameterType::INFILELIST)
{
return "INFILELIST";
}
THROW(ProgrammingException, "Unknown ToolBase parameter type!");
}
QString ToolBase::typeToArgString(ToolBase::ParameterType type) const
{
if (type==ParameterType::FLAG)
{
return "";
}
else if (type==ParameterType::INT)
{
return "<int>";
}
else if (type==ParameterType::FLOAT)
{
return "<float>";
}
else if (type==ParameterType::ENUM)
{
return "<enum>";
}
else if (type==ParameterType::STRING)
{
return "<string>";
}
else if (type==ParameterType::INFILE)
{
return "<file>";
}
else if (type==ParameterType::OUTFILE)
{
return "<file>";
}
else if (type==ParameterType::INFILELIST)
{
return "<filelist>";
}
THROW(ProgrammingException, "Unknown ToolBase parameter type!");
}
ToolBase::ParameterData::ParameterData()
: name()
, type(ParameterType::NONE)
, desc("Invalid uninitialized parameter")
, optional(false)
, default_value("Schwenker")
, value()
{
}
ToolBase::ParameterData::ParameterData(QString n, ParameterType t, QString d, bool o, QVariant v)
: name (n)
, type(t)
, desc(d)
, optional(o)
, default_value(v)
, value()
{
}
bool ToolBase::notify(QObject* receiver, QEvent* event)
{
try
{
return QCoreApplication::notify(receiver, event);
}
catch(CommandLineParsingException& e)
{
QTextStream stream(stderr);
stream << QCoreApplication::applicationName() << " " << version() << Qt::endl;
stream << "Command line parsing exception: " << e.message() << Qt::endl;
stream << "Call this tool with the argument '--help' for help." << Qt::endl;
exit(1);
}
catch(ToolFailedException& e)
{
QTextStream stream(stderr);
stream << QCoreApplication::applicationName() << " " << version() << Qt::endl;
stream << e.message() << Qt::endl;
exit(1);
}
catch(ProgrammingException& e)
{
QTextStream stream(stderr);
stream << QCoreApplication::applicationName() << " " << version() << Qt::endl;
stream << "Programming exception: " << e.message() << Qt::endl;
stream << "Location : " << e.file() << ":" << e.line() << Qt::endl;
stream << "This should not happen, please report the error to the developers!" << Qt::endl;
exit(1);
}
catch(Exception& e)
{
QTextStream stream(stderr);
stream << QCoreApplication::applicationName() << " " << version() << Qt::endl;
stream << "Exception: " << e.message() << Qt::endl;
stream << "Location : " << e.file() << ":" << e.line() << Qt::endl;
exit(1);
}
catch(std::exception& e)
{
QTextStream stream(stderr);
stream << QCoreApplication::applicationName() << " " << version() << Qt::endl;
stream << "Exception: " << e.what() << Qt::endl;
exit(1);
}
catch(...)
{
QTextStream stream(stderr);
stream << QCoreApplication::applicationName() << " " << version() << Qt::endl;
stream << "Unknown exception!" << Qt::endl;
exit(1);
}
return false;
}
ToolBase::ChangeLogEntry::ChangeLogEntry(int y, int m, int d, QString t)
: date(y, m, d)
, text(t)
{
}