/
mythcommandlineparser.cpp
3056 lines (2668 loc) · 93 KB
/
mythcommandlineparser.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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: c++ -*-
*
* Class CommandLineArg
* Class MythCommandLineParser
*
* Copyright (C) Raymond Wagner 2011
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#if defined ANDROID && __ANDROID_API__ < 24
// ftello and fseeko do not exist in android before api level 24
#define ftello ftell
#define fseeko fseek
#endif
// C++ headers
#include <algorithm>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unistd.h>
// System headers
#include <sys/types.h>
#ifndef _WIN32
# include <sys/ioctl.h>
# include <pwd.h>
# include <grp.h>
# if defined(__linux__) || defined(__LINUX__)
# include <sys/prctl.h>
# endif // linux
#endif // not _WIN32
// Qt headers
#include <QtGlobal>
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QRegularExpression>
#include <QSize>
#include <QString>
#include <QTextStream>
#include <QVariant>
#include <QVariantList>
#include <QVariantMap>
#include <utility>
// MythTV headers
#include "mythcommandlineparser.h"
#include "mythcorecontext.h"
#include "exitcodes.h"
#include "mythconfig.h"
#include "mythlogging.h"
#include "mythversion.h"
#include "logging.h"
#include "mythmiscutil.h"
#include "mythdate.h"
static constexpr int k_defaultWidth = 79;
/** \fn GetTermWidth(void)
* \brief returns terminal width, or 79 on error
*/
static int GetTermWidth(void)
{
#if defined(_WIN32) || defined(Q_OS_ANDROID)
return k_defaultWidth;
#else
struct winsize ws {};
if (ioctl(0, TIOCGWINSZ, &ws) != 0)
return k_defaultWidth;
return static_cast<int>(ws.ws_col);
#endif
}
static QByteArray strip_quotes(const QByteArray& array)
{
return ((array.startsWith('"') && array.endsWith('"') ) ||
(array.startsWith('\'') && array.endsWith('\''))
) ? array.mid(1, array.size() - 2) : array;
}
static void wrapList(QStringList &list, int width)
{
// Set a minimum width of 5 to prevent a crash; if this is triggered,
// something has gone seriously wrong and the result won't really be usable
width = std::max(width, 5);
for (int i = 0; i < list.size(); i++)
{
QString string = list.at(i);
if( string.size() <= width )
continue;
QString left = string.left(width);
bool inserted = false;
while( !inserted && !left.endsWith(" " ))
{
if( string.mid(left.size(), 1) == " " )
{
list.replace(i, left);
list.insert(i+1, string.mid(left.size()).trimmed());
inserted = true;
}
else
{
left.chop(1);
if( !left.contains(" ") )
{
// Line is too long, just hyphenate it
list.replace(i, left + "-");
list.insert(i+1, string.mid(left.size()));
inserted = true;
}
}
}
if( !inserted )
{
left.chop(1);
list.replace(i, left);
list.insert(i+1, string.mid(left.size()).trimmed());
}
}
}
/**
* Parse a string into separate tokens. This function understands
* quoting and the escape character.
*/
QStringList MythCommandLineParser::MythSplitCommandString(const QString &line)
{
QStringList fields;
/**
* States for the command line parser.
*/
enum states {
START, ///< No current token.
INTEXT, ///< Collecting token text.
INSQUOTE, ///< Collecting token, inside single quotes.
INDQUOTE, ///< Collecting token, inside double quotes.
ESCTEXT, ///< Saw backslash. Returns to generic text.
ESCSQUOTE, ///< Saw backslash. Returns to single quotes.
ESCDQUOTE, ///< Saw backslash. Returns to double quotes.
};
states state = START;
int tokenStart = -1;
for (int i = 0; i < line.size(); i++)
{
const QChar c = line.at(i);
switch (state) {
case START:
tokenStart = i;
if (c.isSpace()) break;
if (c == '\'') state = INSQUOTE;
else if (c == '\"') state = INDQUOTE;
else if (c == '\\') state = ESCTEXT;
else state = INTEXT;
break;
case INTEXT:
if (c.isSpace()) {
fields += line.mid(tokenStart, i - tokenStart);
state = START;
break;
}
else if (c == '\'') state = INSQUOTE;
else if (c == '\"') state = INDQUOTE;
else if (c == '\\') state = ESCTEXT;
break;
case INSQUOTE:
if (c == '\'') state = INTEXT;
else if (c == '\\') state = ESCSQUOTE;
break;
case INDQUOTE:
if (c == '\"') state = INTEXT;
else if (c == '\\') state = ESCDQUOTE;
break;
case ESCTEXT: state = INTEXT; break;
case ESCSQUOTE: state = INSQUOTE; break;
case ESCDQUOTE: state = INDQUOTE; break;
}
}
if (state != START)
fields += line.mid(tokenStart);
return fields;
}
/** \fn NamedOptType
* \brief Return character string describing type of result from parser pass
*/
const char* MythCommandLineParser::NamedOptType(Result type)
{
switch (type)
{
case Result::kEnd:
return "kEnd";
case Result::kEmpty:
return "kEmpty";
case Result::kOptOnly:
return "kOptOnly";
case Result::kOptVal:
return "kOptVal";
case Result::kCombOptVal:
return "kCombOptVal";
case Result::kArg:
return "kArg";
case Result::kPassthrough:
return "kPassthrough";
case Result::kInvalid:
return "kInvalid";
}
return "kUnknown";
}
/** \defgroup commandlineparser Command Line Processing
* \ingroup libmythbase
* \brief Utility responsible for processing arguments from the command line
*
* This fundamental design for this utility is a class that can be modularly
* configured with different optional arguments and behaviors, let process
* the received input arguments, and then persist for the results to be read
* out as needed.
*
* In typical use, one will subclass MythCommandLineParser() and overwrite
* the LoadArguments() and GetHelpHeader() virtual functions. LoadArguments()
* is a convenient place to define default behaviors and accepted arguments.
* GetHelpHeader() is called for text describing the application, used when
* calling the '--help' argument. This utility will automatically handle help
* output, as well as check relationships between arguments.
*/
/** \class CommandLineArg
* \ingroup commandlineparser
* \brief Definition for a single command line option
*
* This class contains instructions for the command line parser about what
* options to process from the command line. Each instance can correspond
* to multiple argument keywords, and stores a default value, whether it
* has been supplied, help text, and optional interdependencies with other
* CommandLineArgs.
*/
/** \brief Default constructor for CommandLineArg class
*
* This constructor is for use with command line parser, defining an option
* that can be used on the command line, and should be reported in --help
* printouts
*/
CommandLineArg::CommandLineArg(const QString& name, QMetaType::Type type,
QVariant def, QString help, QString longhelp) :
ReferenceCounter(QString("CommandLineArg:%1").arg(name)),
m_name(name), m_type(type), m_default(std::move(def)),
m_help(std::move(help)), m_longhelp(std::move(longhelp))
{
if ((m_type != QMetaType::QString) && (m_type != QMetaType::QStringList) &&
(m_type != QMetaType::QVariantMap))
m_converted = true;
}
/** \brief Reduced constructor for CommandLineArg class
*
* This constructor is for internal use within the command line parser. It
* is intended for use in supplementary data storage for information not
* supplied directly on the command line.
*/
CommandLineArg::CommandLineArg(const QString& name, QMetaType::Type type, QVariant def)
: ReferenceCounter(QString("CommandLineArg:%1").arg(name)),
m_name(name), m_type(type), m_default(std::move(def))
{
if ((m_type != QMetaType::QString) && (m_type != QMetaType::QStringList) &&
(m_type != QMetaType::QVariantMap))
m_converted = true;
}
/** \brief Dummy constructor for CommandLineArg class
*
* This constructor is for internal use within the command line parser. It
* is used as a placeholder for defining relations between different command
* line arguments, and is reconciled with the proper argument of the same
* name prior to parsing inputs.
*/
CommandLineArg::CommandLineArg(const QString& name) :
ReferenceCounter(QString("CommandLineArg:%1").arg(name)),
m_name(name)
{
}
/** \brief Return string containing all possible keyword triggers for this
* argument
*/
QString CommandLineArg::GetKeywordString(void) const
{
// this may cause problems if the terminal is too narrow, or if too
// many keywords for the same argument are used
return m_keywords.join(", ");
}
/** \brief Return length of full keyword string for use in determining indent
* of help text
*/
int CommandLineArg::GetKeywordLength(void) const
{
int len = GetKeywordString().length();
QList<CommandLineArg*>::const_iterator i1;
for (i1 = m_parents.begin(); i1 != m_parents.end(); ++i1)
len = std::max(len, (*i1)->GetKeywordLength()+2);
return len;
}
/** \brief Return string containing help text with desired offset
*
* This function returns a string containing all usable keywords and the
* shortened help text, for use with the general help printout showing all
* options. It automatically accounts for terminal width, and wraps the text
* accordingly.
*
* The group option acts as a filter, only returning text if the argument is
* part of the group the parser is currently printing options for.
*
* Child arguments will not produce help text on their own, but only indented
* beneath each of the marked parent arguments. The force option specifies
* that the function is being called by the parent argument, and help should
* be output.
*/
QString CommandLineArg::GetHelpString(int off, const QString& group, bool force) const
{
QString helpstr;
QTextStream msg(&helpstr, QIODevice::WriteOnly);
int termwidth = GetTermWidth();
if (termwidth < off)
{
if (off > 70)
{
// developer has configured some absurdly long command line
// arguments, but we still need to do something
termwidth = off+40;
}
else
{
// user is running uselessly narrow console, use a sane console
// width instead
termwidth = k_defaultWidth;
}
}
if (m_help.isEmpty() && !force)
// only print if there is a short help to print
return helpstr;
if ((m_group != group) && !force)
// only print if looping over the correct group
return helpstr;
if (!m_parents.isEmpty() && !force)
{
// only print if an independent option, not subject
// to a parent option
return helpstr;
}
if (!m_deprecated.isEmpty())
// option is marked as deprecated, do not show
return helpstr;
if (!m_removed.isEmpty())
// option is marked as removed, do not show
return helpstr;
QString pad;
pad.fill(' ', off);
// print the first line with the available keywords
QStringList hlist = m_help.split('\n');
wrapList(hlist, termwidth-off);
msg << " ";
if (!m_parents.isEmpty())
msg << " ";
msg << GetKeywordString().leftJustified(off, ' ')
<< hlist.takeFirst() << Qt::endl;
// print remaining lines with necessary padding
for (const auto & line : std::as_const(hlist))
msg << pad << line << Qt::endl;
// loop through any child arguments to print underneath
for (auto * arg : std::as_const(m_children))
msg << arg->GetHelpString(off, group, true);
msg.flush();
return helpstr;
}
/** \brief Return string containing extended help text
*
* This function returns a longer version of the help text than that provided
* with the list of arguments, intended for more detailed, specific
* information. This also documents the type of argument it takes, default
* value, and any relational dependencies with other arguments it might have.
*/
QString CommandLineArg::GetLongHelpString(QString keyword) const
{
QString helpstr;
QTextStream msg(&helpstr, QIODevice::WriteOnly);
int termwidth = GetTermWidth();
// help called for an argument that is not me, this should not happen
if (!m_keywords.contains(keyword))
return helpstr;
// argument has been marked as removed, so warn user of such
if (!m_removed.isEmpty())
{
PrintRemovedWarning(keyword);
// argument has been marked as deprecated, so warn user of such
}
else if (!m_deprecated.isEmpty())
{
PrintDeprecatedWarning(keyword);
}
msg << "Option: " << keyword << Qt::endl << Qt::endl;
bool first = true;
// print all related keywords, padding for multiples
for (const auto & word : std::as_const(m_keywords))
{
if (word != keyword)
{
if (first)
{
msg << "Aliases: " << word << Qt::endl;
first = false;
}
else
msg << " " << word << Qt::endl;
}
}
// print type and default for the stored value
msg << "Type: " << QMetaType(m_type).name() << Qt::endl;
if (m_default.canConvert<QString>())
msg << "Default: " << m_default.toString() << Qt::endl;
QStringList help;
if (m_longhelp.isEmpty())
help = m_help.split("\n");
else
help = m_longhelp.split("\n");
wrapList(help, termwidth-13);
// print description, wrapping and padding as necessary
msg << "Description: " << help.takeFirst() << Qt::endl;
for (const auto & line : std::as_const(help))
msg << " " << line << Qt::endl;
QList<CommandLineArg*>::const_iterator i2;
// loop through the four relation types and print
if (!m_parents.isEmpty())
{
msg << Qt::endl << "Can be used in combination with:" << Qt::endl;
for (auto * parent : std::as_const(m_parents))
msg << " " << parent->GetPreferredKeyword()
.toLocal8Bit().constData();
msg << Qt::endl;
}
if (!m_children.isEmpty())
{
msg << Qt::endl << "Allows the use of:" << Qt::endl;
for (i2 = m_children.constBegin(); i2 != m_children.constEnd(); ++i2)
msg << " " << (*i2)->GetPreferredKeyword()
.toLocal8Bit().constData();
msg << Qt::endl;
}
if (!m_requires.isEmpty())
{
msg << Qt::endl << "Requires the use of:" << Qt::endl;
for (i2 = m_requires.constBegin(); i2 != m_requires.constEnd(); ++i2)
msg << " " << (*i2)->GetPreferredKeyword()
.toLocal8Bit().constData();
msg << Qt::endl;
}
if (!m_blocks.isEmpty())
{
msg << Qt::endl << "Prevents the use of:" << Qt::endl;
for (i2 = m_blocks.constBegin(); i2 != m_blocks.constEnd(); ++i2)
msg << " " << (*i2)->GetPreferredKeyword()
.toLocal8Bit().constData();
msg << Qt::endl;
}
msg.flush();
return helpstr;
}
/** \brief Set option as provided on command line with no value
*
* This specifies that an option is given, but there is no corresponding
* value, meaning this can only be used on a boolean, integer, and string
* arguments. All other will return false.
*/
bool CommandLineArg::Set(const QString& opt)
{
m_usedKeyword = opt;
switch (m_type)
{
case QMetaType::Bool:
m_stored = QVariant(!m_default.toBool());
break;
case QMetaType::Int:
if (m_stored.isNull())
m_stored = QVariant(1);
else
m_stored = QVariant(m_stored.toInt() + 1);
break;
case QMetaType::QString:
m_stored = m_default;
break;
default:
std::cerr << "Command line option did not receive value:" << std::endl
<< " " << opt.toLocal8Bit().constData() << std::endl;
return false;
}
m_given = true;
return true;
}
/** \brief Set option as provided on command line with value
*/
bool CommandLineArg::Set(const QString& opt, const QByteArray& val)
{
QVariantList vlist;
QList<QByteArray> blist;
QVariantMap vmap;
m_usedKeyword = opt;
switch (m_type)
{
case QMetaType::Bool:
std::cerr << "Boolean type options do not accept values:" << std::endl
<< " " << opt.toLocal8Bit().constData() << std::endl;
return false;
case QMetaType::QString:
m_stored = QVariant(val);
break;
case QMetaType::Int:
m_stored = QVariant(val.toInt());
break;
case QMetaType::UInt:
m_stored = QVariant(val.toUInt());
break;
case QMetaType::LongLong:
m_stored = QVariant(val.toLongLong());
break;
case QMetaType::Double:
m_stored = QVariant(val.toDouble());
break;
case QMetaType::QDateTime:
m_stored = QVariant(MythDate::fromString(QString(val)));
break;
case QMetaType::QStringList:
if (!m_stored.isNull())
vlist = m_stored.toList();
vlist << val;
m_stored = QVariant(vlist);
break;
case QMetaType::QVariantMap:
if (!val.contains('='))
{
std::cerr << "Command line option did not get expected "
<< "key/value pair" << std::endl;
return false;
}
blist = val.split('=');
if (!m_stored.isNull())
vmap = m_stored.toMap();
vmap[QString(strip_quotes(blist[0]))] = QVariant(strip_quotes(blist[1]));
m_stored = QVariant(vmap);
break;
case QMetaType::QSize:
if (!val.contains('x'))
{
std::cerr << "Command line option did not get expected "
<< "XxY pair" << std::endl;
return false;
}
blist = val.split('x');
m_stored = QVariant(QSize(blist[0].toInt(), blist[1].toInt()));
break;
default:
m_stored = QVariant(val);
}
m_given = true;
return true;
}
/** \brief Set argument as parent of given child
*/
CommandLineArg* CommandLineArg::SetParentOf(const QString &opt)
{
m_children << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as parent of multiple children
*/
CommandLineArg* CommandLineArg::SetParentOf(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
m_children << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as child of given parent
*/
CommandLineArg* CommandLineArg::SetParent(const QString &opt)
{
m_parents << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as child of multiple parents
*/
CommandLineArg* CommandLineArg::SetParent(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
m_parents << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as child of given parent
*/
CommandLineArg* CommandLineArg::SetChildOf(const QString &opt)
{
m_parents << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as child of multiple parents
*/
CommandLineArg* CommandLineArg::SetChildOf(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
m_parents << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as parent of given child
*/
CommandLineArg* CommandLineArg::SetChild(const QString& opt)
{
m_children << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as parent of multiple children
*/
CommandLineArg* CommandLineArg::SetChild(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
m_children << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as parent of given child and mark as required
*/
CommandLineArg* CommandLineArg::SetRequiredChild(const QString& opt)
{
m_children << new CommandLineArg(opt);
m_requires << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as parent of multiple children and mark as required
*/
CommandLineArg* CommandLineArg::SetRequiredChild(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
{
m_children << new CommandLineArg(opt);
m_requires << new CommandLineArg(opt);
}
return this;
}
/** \brief Set argument as child required by given parent
*/
CommandLineArg* CommandLineArg::SetRequiredChildOf(const QString& opt)
{
m_parents << new CommandLineArg(opt);
m_requiredby << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as child required by multiple parents
*/
CommandLineArg* CommandLineArg::SetRequiredChildOf(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
{
m_parents << new CommandLineArg(opt);
m_requiredby << new CommandLineArg(opt);
}
return this;
}
/** \brief Set argument as requiring given option
*/
CommandLineArg* CommandLineArg::SetRequires(const QString& opt)
{
m_requires << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as requiring multiple options
*/
CommandLineArg* CommandLineArg::SetRequires(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
m_requires << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as incompatible with given option
*/
CommandLineArg* CommandLineArg::SetBlocks(const QString &opt)
{
m_blocks << new CommandLineArg(opt);
return this;
}
/** \brief Set argument as incompatible with multiple options
*/
CommandLineArg* CommandLineArg::SetBlocks(const QStringList& opts)
{
for (const auto& opt : std::as_const(opts))
m_blocks << new CommandLineArg(opt);
return this;
}
/** \brief Set option as deprecated
*/
CommandLineArg* CommandLineArg::SetDeprecated(QString depstr)
{
if (depstr.isEmpty())
depstr = "and will be removed in a future version.";
m_deprecated = depstr;
return this;
}
/** \brief Set option as removed
*/
CommandLineArg* CommandLineArg::SetRemoved(QString remstr, QString remver)
{
if (remstr.isEmpty())
remstr = "and is no longer available in this version.";
m_removed = remstr;
m_removedversion = std::move(remver);
return this;
}
/** \brief Internal use, set argument as parent of given child
*
* This option is intended for internal use only, as part of reconciling
* dummy options with their matched real counterparts.
*/
void CommandLineArg::SetParentOf(CommandLineArg *other, bool forward)
{
bool replaced = false;
other->IncrRef();
for (int i = 0; i < m_children.size(); i++)
{
if (m_children[i]->m_name == other->m_name)
{
m_children[i]->DecrRef();
m_children.replace(i, other);
replaced = true;
break;
}
}
if (!replaced)
m_children << other;
if (forward)
other->SetChildOf(this, false);
}
/** \brief Internal use, set argument as child of given parent
*
* This option is intended for internal use only, as part of reconciling
* dummy options with their matched real counterparts.
*/
void CommandLineArg::SetChildOf(CommandLineArg *other, bool forward)
{
bool replaced = false;
other->IncrRef();
for (int i = 0; i < m_parents.size(); i++)
{
if (m_parents[i]->m_name == other->m_name)
{
m_parents[i]->DecrRef();
m_parents.replace(i, other);
replaced = true;
break;
}
}
if (!replaced)
m_parents << other;
if (forward)
other->SetParentOf(this, false);
}
/** \brief Internal use, set argument as requiring given option
*
* This option is intended for internal use only, as part of reconciling
* dummy options with their matched real counterparts.
*/
void CommandLineArg::SetRequires(CommandLineArg *other, bool /*forward*/)
{
bool replaced = false;
other->IncrRef();
for (int i = 0; i < m_requires.size(); i++)
{
if (m_requires[i]->m_name == other->m_name)
{
m_requires[i]->DecrRef();
m_requires.replace(i, other);
replaced = true;
break;
}
}
if (!replaced)
m_requires << other;
// requirements need not be reciprocal
// if (forward)
// other->SetRequires(this, false);
}
/** \brief Internal use, set argument as incompatible with given option
*
* This option is intended for internal use only, as part of reconciling
* dummy options with their matched real counterparts.
*/
void CommandLineArg::SetBlocks(CommandLineArg *other, bool forward)
{
bool replaced = false;
other->IncrRef();
for (int i = 0; i < m_blocks.size(); i++)
{
if (m_blocks[i]->m_name == other->m_name)
{
m_blocks[i]->DecrRef();
m_blocks.replace(i, other);
replaced = true;
break;
}
}
if (!replaced)
m_blocks << other;
if (forward)
other->SetBlocks(this, false);
}
/** \brief Mark a list of arguments as mutually exclusive
*/
void CommandLineArg::AllowOneOf(const QList<CommandLineArg*>& args)
{
// TODO: blocks do not get set properly if multiple dummy arguments
// are provided. since this method will not have access to the
// argument list, this issue will have to be resolved later in
// ReconcileLinks().
// loop through all but the last entry
for (auto i1 = args.cbegin(); i1 != args.cend()-1; ++i1)
{
// loop through the next to the last entry
// and block use with the current
for (auto i2 = i1+1; i2 != args.cend(); ++i2)
{
(*i1)->SetBlocks(*i2);
}
if ((*i1)->m_type == QMetaType::UnknownType)
(*i1)->DecrRef();
}
}
/** \brief Convert stored string value from QByteArray to QString
*
* This is a work around to delay string processing until after QApplication
* has been initialized, to allow the locale to be configured and unicode
* handling to work properly
*/
void CommandLineArg::Convert(void)
{
if (!QCoreApplication::instance())
// QApplication not available, no sense doing anything yet
return;
if (m_converted)
// already run, abort
return;
if (!m_given)
{
// nothing to work on, abort
m_converted = true;
return;
}
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
auto storedType = static_cast<QMetaType::Type>(m_stored.type());
#else
auto storedType = m_stored.typeId();
#endif
if (m_type == QMetaType::QString)
{
if (storedType == QMetaType::QByteArray)
{
m_stored = QString::fromLocal8Bit(m_stored.toByteArray());
}
// else
// not sure why this isnt a bytearray, but ignore it and
// set it as converted
}
else if (m_type == QMetaType::QStringList)
{
if (storedType == QMetaType::QVariantList)
{
QVariantList vlist = m_stored.toList();
QStringList slist;
for (const auto& item : std::as_const(vlist))
slist << QString::fromLocal8Bit(item.toByteArray());