File: GetOpt.cpp

package info (click to toggle)
monkeystudio 1.9.0.4%2Bgit20161218-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 41,500 kB
  • ctags: 22,118
  • sloc: cpp: 144,671; ansic: 33,969; python: 2,922; makefile: 127; sh: 122; php: 73; cs: 69
file content (769 lines) | stat: -rw-r--r-- 21,179 bytes parent folder | download | duplicates (2)
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
/****************************************************************************
    Copyright (C) 2005 - 2011  Filipe AZEVEDO & The Monkey Studio Team
    http://monkeystudio.org licensing under the GNU GPL.

    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 St, Fifth Floor, Boston, MA  02110-1301  USA
****************************************************************************/
#include "GetOpt.h"

#include <QApplication>
#include <QFileInfo>
#include <QStack>
#include <QDebug>

/**
    \class GetOpt

    \brief A command line option parser.

    This class helps to overcome the repetitive, tedious and
    error-prone task of parsing the command line options passed to your
    application by the user. Specify the acceptable syntax with a
    minimum of statements in a readable way, check it against the
    actual arguments passed and find the retrieved values in variables
    of your program. The name \em GetOpt is based on similar utilities
    build into the Unix shell and other languages.

    A command line that a user might have entered is:

    \code
    app -v --config=my.cnf -Wall input.dat
    \endcode

    The typical usage has three stages:

    -# Construct a parser specifying what arguments to parse
    -# Set up the list of allowed and required options
    -# Run the parser

    For the first step there are three different constructors that
    either take arguments directly from \c main(), \c QApplication or a
    user specified list. Setting up the accepted syntax is done by a
    set of \c add functions like addSwitch(). The final step of running
    the parser is simply done by calling parse().

    A short example implementing a \c --verbose switch:

    \code
    int main(int argc, char **argv)
    {
        GetOpt opts(argc, argv);
        bool verbose;
        opts.addSwitch("verbose", &verbose);
        if (!opts.parse())
            return 1;
        if (verbose)
            cout << "VERBOSE mode on" << endl;
        ...
    \endcode

    For a better understanding of the function names we'll better
    define some terms used in the API and its documentation:

    - \em Argument An argument is a plain text token like e.g. a file
    name one typically passes to an editor when invoking it.
    - \em Switch A switch is an on/off kind of argument without the need
        of additional information. Example: \c --debug.
    - \em Option An option is a normally optional argument with a key-value
    syntax like \c --output=out.txt or \c -I/usr/include.
    - \em Short \em Option A short option is a one letter option with a
    preceding dash. Like \c -v.
    - \em Long \em Option A long option has a more verbose,
    multi-letter name like \c --debug.
    .

    \author froglogic GbR <contact@froglogic.com>
*/


/**
    Constructs a command line parser from the arguments stored in a
    previously created QApplication instance.

    Example usage:
    \code
    QApplication a(argc, argv);

    GetOpt opt;
    \endcode

    This constructor is probably the most convenient one to use in a
    regular Qt application. Note that QApplication may already have
    removed Qt (or X11) specific arguments. Also see
    QApplication::argv() and QApplication::argc().
    */
GetOpt::GetOpt()
{
    if ( !qApp )
    {
        qFatal( "GetOpt: requires a QApplication instance to be constructed first" );
    }

#if QT_VERSION < 0x050000
    init( qApp->argc(), qApp->argv(), 1 );
#else
    args = qApp->arguments();
    
    if ( !args.isEmpty() ) {
        args.removeFirst();
    }
    
    init( 0, 0 );
#endif
}

/**
    \internal
    */
GetOpt::GetOpt( int offset )
{
    if ( !qApp )
    {
        qFatal( "GetOpt: requires a QApplication instance to be constructed first" );
    }

#if QT_VERSION < 0x050000
    init( qApp->argc(), qApp->argv(), offset );
#else
    args = qApp->arguments();
    
    for ( int i = 0; i < offset; i++ ) {
        if ( !args.isEmpty() ) {
            args.removeFirst();
        }
    }
    
    init( 0, 0 );
#endif
}

/**
    Construct a command line parser from the array \a argv of string
    pointers with the size \a argc. Those parameters have the form
    typically found in the \c main() function. That means that you can
    simply pass on the arguments specified by the user of your
    application.

    Example usage:

    \code
    int main(int argc, char **argv) {
        GetOpt opt(argc, argv);
        ...
    }
    \endcode
    */
GetOpt::GetOpt( int argc, char *argv[] )
{
    init( argc, argv );
}

/**
    Construct a command line parser from the arguments specified in the
    list of arguments \a a. This constructor is convenient in those
    cases where you want to parse a command line assembled on-the-fly
    instead of relying on the \c argc and \c arg parameters passed to
    the \c main() function.
    */
GetOpt::GetOpt( const QStringList &a )
    : args( a )
{
    init( 0, 0 );
}

/**
    \internal
*/
void GetOpt::init( int argc, char *argv[], int offset )
{
    numReqArgs = numOptArgs = 0;
    currArg = 1; // appname is not part of the arguments

    if ( argc )
    {
        // application name
        aname = QFileInfo( QString::fromLocal8Bit( argv[0] ) ).fileName();

        // arguments
        for ( int i = offset; i < argc; ++i )
        {
            args.append( QString::fromLocal8Bit( argv[i] ) );
        }
    }
}

/**
    \fn bool GetOpt::parse()

    Parse the command line arguments specified in the constructor under
    the conditions set by the various \c add*() functions. On success,
    the given variable reference will be initialized with their
    respective values and true will be returned. Returns false
    otherwise.

    In the future there'll be a way to retrieve an error message. In
    the current version the message will be printed to \c stderr.
*/

/**
    \internal
*/
bool GetOpt::parse( bool untilFirstSwitchOnly )
{
    // qDebug( "parse(%s)", args.join( QString( "," ) ).toLocal8Bit().constData() );
    // push all arguments as we got them on a stack
    // more pushes might following when parsing condensed arguments
    // like --key=value.
    QStack<QString> stack;
    {
        QStringList::const_iterator it = args.isEmpty() ? args.end() : --args.end();

        while ( it != args.constEnd() )
        {
            stack.push( *it );

            if ( it == args.begin() )
            {
                it = args.constEnd();
            }
            else
            {
                --it;
            }
        }
    }

    //qWarning() << stack;

    enum { StartState, ExpectingState, OptionalState } state = StartState;
    enum TokenType { LongOpt, ShortOpt, Arg, End } t, currType = End;

    const OptionConstIterator obegin = options.begin();
    const OptionConstIterator oend = options.end();
    Option currOpt;
    bool extraLoop = true; // we'll do an extra round. fake an End argument

    while ( !stack.isEmpty() || extraLoop )
    {
        QString a;
        QString origA;

        // identify argument type
        if ( !stack.isEmpty() )
        {
            a = stack.pop();
            currArg++;
            origA = a;

            // qDebug( "popped %s", a.toLocal8Bit().constData() );
            if ( a.startsWith( QLatin1String( "--" ) ) )
            {
                // recognized long option
                a = a.mid( 2 );

                if ( a.isEmpty() )
                {
                    qWarning( "'--' feature not supported, yet" );
                    //exit( 2 );
                    return false;
                }

                t = LongOpt;
                int equal = a.indexOf( '=' ); // split key=value style arguments

                if ( equal >= 0 )
                {
                    stack.push( a.mid( equal +1 ) );
                    currArg--;
                    a = a.left( equal );
                }
            }
            else if ( a.length() == 1 )
            {
                t = Arg;
            }
            else if ( a[ 0 ] == '-' )
            {
#if 0 // compat mode for -long style options
                if ( a.length() == 2 )
                {
                    t = ShortOpt;
                    a = a[ 1 ];
                }
                else
                {
                    a = a.mid( 1 );
                    t = LongOpt;
                    int equal = a.find( '=' ); // split key=value style arguments

                    if ( equal >= 0 )
                    {
                        stack.push( a.mid( equal +1 ) );
                        currArg--;
                        a = a.left( equal );
                    }
                }
#else
                // short option
                t = ShortOpt;

                // followed by an argument ? push it for later processing.
                if ( a.length() > 2 )
                {
                    stack.push( a.mid( 2 ) );
                    currArg--;
                }

                a = a[ 1 ];
#endif
            }
            else
            {
                t = Arg;
            }
        }
        else
        {
            // faked closing argument
            t = End;
        }

        // look up among known list of options
        Option opt;
        if ( t != End )
        {
            OptionConstIterator oit = obegin;

            while ( oit != oend )
            {
                const Option &o = *oit;

                if ( ( t == LongOpt && a == o.lname ) || ( t == ShortOpt && a[ 0 ].unicode() == o.sname ) )
                {
                    opt = o;
                    break;
                }

                ++oit;
            }

            if ( t == LongOpt && opt.type == OUnknown )
            {
                if ( currOpt.type != OVarLen )
                {
                    qWarning( "Unknown option --%s", a.toLocal8Bit().constData() );
                    return false;
                }
                else
                {
                    // VarLength options support arguments starting with '-'
                    t = Arg;
                }
            }
            else if ( t == ShortOpt && opt.type == OUnknown )
            {
                if ( currOpt.type != OVarLen )
                {
                    qWarning( "Unknown option -%c", a[ 0 ].unicode() );
                    return false;
                }
                else
                {
                    // VarLength options support arguments starting with '-'
                    t = Arg;
                }
            }

        }
        else
        {
            opt = Option( OEnd );
        }

        // interpret result
        switch ( state )
        {
        case StartState:
            if ( opt.type == OSwitch )
            {
                setSwitch( opt );
                setOptions.insert( opt.lname, 1 );
                setOptions.insert( QString( QChar( opt.sname ) ), 1 );
            }
            else if ( opt.type == OArg1 || opt.type == ORepeat )
            {
                state = ExpectingState;
                currOpt = opt;
                currType = t;
                setOptions.insert( opt.lname, 1 );
                setOptions.insert( QString( QChar( opt.sname ) ), 1 );
            }
            else if ( opt.type == OOpt || opt.type == OVarLen )
            {
                state = OptionalState;
                currOpt = opt;
                currType = t;
                setOptions.insert( opt.lname, 1 );
                setOptions.insert( QString( QChar( opt.sname ) ), 1 );
            }
            else if ( opt.type == OEnd )
            {
                // we're done
            }
            else if ( opt.type == OUnknown && t == Arg )
            {
                if ( numReqArgs > 0 )
                {
                    if ( reqArg.stringValue->isNull() )
                    {
                        *reqArg.stringValue = a;
                    }
                    else
                    {
                        qWarning( "Too many arguments" );
                        return false;
                    }
                }
                else if ( numOptArgs > 0 )
                {
                    if ( optArg.stringValue->isNull() )
                    {
                        *optArg.stringValue = a;
                    }
                    else
                    {
                        qWarning( "Too many arguments" );
                        return false;
                    }
                }
            }
            else
            {
                qFatal( "unhandled StartState case %d",  opt.type );
            }
            break;
        case ExpectingState:
            if ( t == Arg )
            {
                if ( currOpt.type == OArg1 )
                {
                    *currOpt.stringValue = a;
                    state = StartState;
                }
                else if ( currOpt.type == ORepeat )
                {
                    currOpt.listValue->append( a );
                    state = StartState;
                }
                else
                {
                    abort();
                }
            }
            else
            {
                QString n = currType == LongOpt ? currOpt.lname : QString( QChar( currOpt.sname ) );
                qWarning( "Expected an argument after '%s' option", n.toLocal8Bit().constData() );
                return false;
            }
            break;
        case OptionalState:
            if ( t == Arg )
            {
                if ( currOpt.type == OOpt )
                {
                    *currOpt.stringValue = a;
                    state = StartState;
                }
                else if ( currOpt.type == OVarLen )
                {
                    currOpt.listValue->append( origA );
                    // remain in this state
                }
                else
                {
                    abort();
                }
            }
            else
            {
                // optional argument not specified
                if ( currOpt.type == OOpt )
                {
                    *currOpt.stringValue = currOpt.def;
                }

                if ( t != End )
                {
                    // re-evaluate current argument
                    stack.push( origA );
                    currArg--;
                }

                state = StartState;
            }
            break;
        }

        if ( untilFirstSwitchOnly && opt.type == OSwitch )
        {
            return true;
        }

        // are we in the extra loop ? if so, flag the final end
        if ( t == End )
        {
            extraLoop = false;
        }
    }

    if ( numReqArgs > 0 && reqArg.stringValue->isNull() )
    {
        qWarning( "Lacking required argument" );
        return false;
    }

    return true;
}

/**
    \internal
*/
void GetOpt::addOption( Option o )
{
    // ### check for conflicts
    options.append( o );
}

/**
    Adds a switch with the long name \a lname. If the switch is found
    during parsing the bool \a *b will bet set to true. Otherwise the
    bool will be initialized to false.

    Example:

    \code
    GetOpt opt;
    bool verbose;
    opt.addSwitch("verbose", &verbose);
    \endcode

    The boolean flag \c verbose will be set to true if \c --verbose has
    been specified in the command line; false otherwise.
*/
void GetOpt::addSwitch( const QString &lname, bool *b )
{
    Option opt( OSwitch, 0, lname );
    opt.boolValue = b;
    addOption( opt );
    // ### could do all inits at the beginning of parse()
    *b = false;
}

/**
    \internal
*/
void GetOpt::setSwitch( const Option &o )
{
    Q_ASSERT( o.type == OSwitch );
    *o.boolValue = true;
}

/**
    Registers an option with the short name \a s and long name \a l to
    the parser. If this option is found during parsing the value will
    be stored in the string pointed to by \a v. By default \a *v will
    be initialized to \c QString::null.
*/
void GetOpt::addOption( char s, const QString &l, QString *v )
{
    Option opt( OArg1, s, l );
    opt.stringValue = v;
    addOption( opt );
    *v = QString::null;
}

/**
    Registers a long option \a l that can have a variable number of
    corresponding value parameters. As there currently is no way to
    tell the end of the value list the only sensible use of this option
    is at the end of the command line.

    Example:

    \code
    QStringList args;
    opt.addVarLengthOption("exec", &args);
    \endcode

    Above code will lead to "-f" and "test.txt" being stored in \a args
    upon

    \code
    myapp --exec otherapp -f test.txt
    \endcode
    */
void GetOpt::addVarLengthOption( const QString &l, QStringList *v )
{
    Option opt( OVarLen, 0, l );
    opt.listValue = v;
    addOption( opt );
    *v = QStringList();
}

/**
    Registers an option with the short name \a s that can be specified
    repeatedly in the command line. The option values will be stored in
    the list pointed to by \a v. If no \a s option is found \a *v will
    remain at its default value of an empty QStringList instance.

    Example:

    To parse the \c -I options in a command line like
    \code
    myapp -I/usr/include -I/usr/local/include
    \endcode

    you can use code like this:

    \code
    GetOpt opt;
    QStringList includes;
    opt.addRepeatableOption('I', &includes);
    opt.parse();
    \endcode
    */
void GetOpt::addRepeatableOption( char s, QStringList *v )
{
    Option opt( ORepeat, s, QString::null );
    opt.listValue = v;
    addOption( opt );
    *v = QStringList();
}

/**
    Registers an option with the long name \a l that can be specified
    repeatedly in the command line.

    \sa addRepeatableOption( char, QStringList* )
    */
void GetOpt::addRepeatableOption( const QString &l, QStringList *v )
{
    Option opt( ORepeat, 0, l );
    opt.listValue = v;
    addOption( opt );
    *v = QStringList();
}

/**
    Adds a long option \a l that has an optional value parameter. If
    the value is not specified by the user it will be set to \a def.

    Example:

    \code
    GetOpt opt;
    QString file;
    opt.addOptionalOption("dump", &file, "<stdout>");
    \endcode

    \sa addOption
    */
void GetOpt::addOptionalOption( const QString &l, QString *v, const QString &def )
{
    addOptionalOption( 0, l, v, def );
}

/**
    Adds a short option \a s that has an optional value parameter. If
    the value is not specified by the user it will be set to \a def.
    */
void GetOpt::addOptionalOption( char s, const QString &l, QString *v, const QString &def )
{
    Option opt( OOpt, s, l );
    opt.stringValue = v;
    opt.def = def;
    addOption( opt );
    *v = QString::null;
}

/**
    Registers a required command line argument \a name. If the argument
    is missing parse() will return false to indicate an error and \a *v
    will remain with its default QString::null value. Otherwise \a *v
    will be set to the value of the argument.

    Example:

    To accept simple arguments like

    \code
    myeditor letter.txt
    \endcode

    use a call like:

    \code
    QString &file;
    opt.addArgument("file", &file);
    \endcode

    Note: the \a name parameter has a rather descriptive meaning for
    now. It might be used for generating a usage or error message in
    the future. Right now, the only current use is in relation with the
    isSet() function.
    */
void GetOpt::addArgument( const QString &name, QString *v )
{
    Option opt( OUnknown, 0, name );
    opt.stringValue = v;
    reqArg = opt;
    ++numReqArgs;
    *v = QString::null;
}

/**
    Registers an optional command line argument \a name. For a more
    detailed description see the addArgument() documentation.

    */
void GetOpt::addOptionalArgument( const QString &name, QString *v )
{
    Option opt( OUnknown, 0, name );
    opt.stringValue = v;
    optArg = opt;
    ++numOptArgs;
    *v = QString::null;
}

/**
    Returns true if the (long) option or switch \a name has been found
    in the command line; returns false otherwise. Leading hyphens are
    not part of the name.

    As the set/not set decision can also be made depending on the value
    of the variable reference used in the respective \c add*() call
    there's generally little use for this function.
*/

bool GetOpt::isSet( const QString &name ) const
{
    return setOptions.find( name ) != setOptions.end();
}

/**
    \fn int GetOpt::currentArgument() const
    \internal
*/