aboutsummaryrefslogtreecommitdiffstats
path: root/src/CommandLineParser.cpp
blob: 39f40d601d50eba66b5fd768248778a8a2a92940 (plain)
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
/*
 * This file is part of the vng project
 * Copyright (C) 2008 Thomas Zander <tzander@trolltech.com>
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */

#include "CommandLineParser.h"

#include <QDebug>
#include <QTextStream>
#include <QStringList>
#include <QList>
#include <QHash>

CommandLineParser *CommandLineParser::self = 0;

class CommandLineParser::Private
{
public:
    Private(int argc, char **argv);

    // functions
    void addDefinitions(const CommandLineOption * options);
    void setArgumentDefinition(const char *definition);
    void parse();

    // variables;
    const int argumentCount;
    char ** const argumentStrings;
    bool dirty;
    int requiredArguments;
    QString argumentDefinition;

    struct OptionDefinition {
        OptionDefinition() : optionalParameters(0), requiredParameters(0) { }
        QString name;
        QString comment;
        QChar shortName;
        int optionalParameters;
        int requiredParameters;
    };

    // result of what the user typed
    struct ParsedOption {
        QString option;
        QList<QString> parameters;
    };

    QList<OptionDefinition> definitions;
    QHash<QString, ParsedOption> options;
    QList<QString> arguments;
    QList<QString> undefinedOptions;
    QList<QString> errors;
};


CommandLineParser::Private::Private(int argc, char **argv)
    : argumentCount(argc), argumentStrings(argv), dirty(true),
    requiredArguments(0)
{
}

void CommandLineParser::Private::addDefinitions(const CommandLineOption * options)
{
    for (int i=0; options[i].specification != 0; i++) {
        OptionDefinition definition;
        QString option = QString::fromLatin1(options[i].specification);
        // options with optional params are written as "--option required[, optional]
        if (option.indexOf(QLatin1Char(',')) >= 0 && ( option.indexOf(QLatin1Char('[')) < 0 || option.indexOf(QLatin1Char(']')) < 0) ) {
            QStringList optionParts = option.split(QLatin1Char(','), QString::SkipEmptyParts);
            if (optionParts.count() != 2) {
                qWarning() << "option definition '" << option << "' is faulty; only one ',' allowed";
                continue;
            }
            foreach (QString s, optionParts) {
                s = s.trimmed();
                if (s.startsWith(QLatin1String("--")) && s.length() > 2)
                    definition.name = s.mid(2);
                else if (s.startsWith(QLatin1String("-")) && s.length() > 1)
                    definition.shortName = s.at(1);
                else {
                    qWarning() << "option definition '" << option << "' is faulty; the option should start with a -";
                    break;
                }
            }
        }
        else if (option.startsWith(QLatin1String("--")) && option.length() > 2)
            definition.name = option.mid(2);
        else
            qWarning() << "option definition '" << option << "' has unrecognized format. See the api docs for CommandLineParser for a howto";

        if(definition.name.isEmpty())
            continue;
        if (option.indexOf(QLatin1Char(' ')) > 0) {
            QStringList optionParts = definition.name.split(QLatin1Char(' '), QString::SkipEmptyParts);
            definition.name = optionParts[0];
            bool first = true;
            foreach (QString s, optionParts) {
                if (first) {
                    first = false;
                    continue;
                }
                s = s.trimmed();
                if (s[0].unicode() == '[' && s.endsWith(QLatin1Char(']')))
                    definition.optionalParameters++;
                else
                    definition.requiredParameters++;
            }
        }

        definition.comment = QString::fromLatin1(options[i].description);
        definitions << definition;
    }
/*
    foreach (OptionDefinition def, definitions) {
        qDebug() << "definition:" << (def.shortName != 0 ? def.shortName : QChar(32)) << "|" << def.name << "|" << def.comment
            << "|" << def.requiredParameters << "+" << def.optionalParameters;
    }
*/

    dirty = true;
}

void CommandLineParser::Private::setArgumentDefinition(const char *defs)
{
    requiredArguments = 0;
    argumentDefinition = QString::fromLatin1(defs);
    QStringList optionParts = argumentDefinition.split(QLatin1Char(' '), QString::SkipEmptyParts);
    bool inArg = false;
    foreach (QString s, optionParts) {
        s = s.trimmed();
        if (s[0].unicode() == '<') {
            inArg = true;
            requiredArguments++;
        }
        else if (s[0].unicode() == '[')
            inArg = true;
        if (s.endsWith(QLatin1Char('>')))
            inArg = false;
        else if (!inArg)
            requiredArguments++;
    }
}

void CommandLineParser::Private::parse()
{
    if (dirty == false)
        return;
    errors.clear();
    options.clear();
    arguments.clear();
    undefinedOptions.clear();
    dirty = false;

    class OptionProcessor {
      public:
        OptionProcessor(Private *d) : clp(d) { }

        void next(Private::ParsedOption &option) {
            if (! option.option.isEmpty()) {
                // find the definition to match.
                OptionDefinition def;
                foreach (Private::OptionDefinition definition, clp->definitions) {
                    if (definition.name == option.option) {
                        def = definition;
                        break;
                    }
                }
                if (! def.name.isEmpty() && def.requiredParameters >= option.parameters.count() &&
                        def.requiredParameters + def.optionalParameters <= option.parameters.count())
                    clp->options.insert(option.option, option);
                else if (!clp->undefinedOptions.contains(option.option))
                    clp->undefinedOptions << option.option;
                else
                    clp->errors.append(QLatin1String("Not enough arguments passed for option `")
                            + option.option +QLatin1Char('\''));
            }
            option.option.clear();
            option.parameters.clear();
        }

      private:
        CommandLineParser::Private *clp;
    };
    OptionProcessor processor(this);

    bool optionsAllowed = true;
    ParsedOption option;
    OptionDefinition currentDefinition;
    for (int i = 1; i < argumentCount; i++) {
        QString arg = QString::fromLocal8Bit(argumentStrings[i]);
        if (optionsAllowed) {
            if (arg == QLatin1String("--")) {
                optionsAllowed = false;
                continue;
            }
            if (arg.startsWith(QLatin1String("--"))) {
                processor.next(option);
                int end = arg.indexOf(QLatin1Char('='));
                option.option = arg.mid(2, end - 2);
                if (end > 0)
                    option.parameters << arg.mid(end+1);
                continue;
            }
            if (arg[0].unicode() == '-' && arg.length() > 1) {
                for (int x = 1; x < arg.length(); x++) {
                    bool resolved = false;
                    foreach (OptionDefinition definition, definitions) {
                        if (definition.shortName == arg[x]) {
                            resolved = true;
                            processor.next(option);
                            currentDefinition = definition;
                            option.option = definition.name;

                            if (definition.requiredParameters == 1 && arg.length() >= x+2) {
                                option.parameters << arg.mid(x+1, arg.length());
                                x = arg.length();
                            }
                            break;
                        }
                    }
                    if (!resolved) { // nothing found; copy char so it ends up in unrecognized
                        option.option = arg[x];
                        processor.next(option);
                    }
                }
                continue;
            }
        }
        if (! option.option.isEmpty()) {
            if (currentDefinition.name != option.option) {
                // find the definition to match.
                foreach (OptionDefinition definition, definitions) {
                    if (definition.name == option.option) {
                        currentDefinition = definition;
                        break;
                    }
                }
            }
            if (currentDefinition.requiredParameters + currentDefinition.optionalParameters <= option.parameters.count())
                processor.next(option);
        }
        if (option.option.isEmpty())
            arguments << arg;
        else
            option.parameters << arg;
    }
    processor.next(option);

    if (requiredArguments > arguments.count())
        errors.append(QLatin1String("Not enough arguments, usage: ") + QString::fromLocal8Bit(argumentStrings[0])
                + QLatin1Char(' ') + argumentDefinition);

/*
    foreach (QString key, options.keys()) {
        ParsedOption p = options[key];
        qDebug() << "-> " << p.option;
        foreach (QString v, p.parameters)
            qDebug() << "   +" << v;
    }
    qDebug() << "---";
    foreach (QString arg, arguments) {
        qDebug() << arg;
    }
*/
}

// -----------------------------------


// static
void CommandLineParser::init(int argc, char **argv)
{
    if (self)
        delete self;
    self = new CommandLineParser(argc, argv);
}

// static
void CommandLineParser::addOptionDefinitions(const CommandLineOption * optionList)
{
    if (!self) {
        qWarning() << "CommandLineParser:: Use init before addOptionDefinitions!";
        return;
    }
    self->d->addDefinitions(optionList);
}

// static
CommandLineParser *CommandLineParser::instance()
{
    return self;
}

// static
void CommandLineParser::setArgumentDefinition(const char *definition)
{
    if (!self) {
        qWarning() << "CommandLineParser:: Use init before addOptionDefinitions!";
        return;
    }
    self->d->setArgumentDefinition(definition);
}


CommandLineParser::CommandLineParser(int argc, char **argv)
    : d(new Private(argc, argv))
{
}

CommandLineParser::~CommandLineParser()
{
    delete d;
}

void CommandLineParser::usage(const QString &name, const QString &argumentDescription)
{
    QTextStream cout(stdout, QIODevice::WriteOnly);
    cout << "Usage: " << d->argumentStrings[0];
    if (! name.isEmpty())
        cout << " " << name;
    if (d->definitions.count())
        cout << " [OPTION]";
    if (! argumentDescription.isEmpty())
        cout << " " << argumentDescription;
    cout << endl << endl;

    if (d->definitions.count() > 0)
        cout << "Options:" << endl;
    int commandLength = 0;
    foreach (Private::OptionDefinition definition, d->definitions)
        commandLength = qMax(definition.name.length(), commandLength);

    foreach (Private::OptionDefinition definition, d->definitions) {
        cout << "    ";
        if (definition.shortName == 0)
            cout << "   --";
        else
            cout << "-" << definition.shortName << " --";
        cout << definition.name;
        for (int i = definition.name.length(); i <= commandLength; i++)
            cout << ' ';
         cout << definition.comment <<endl;
    }
}

QStringList CommandLineParser::options() const
{
    d->parse();
    return d->options.keys();
}

bool CommandLineParser::contains(const QString & key) const
{
    d->parse();
    return d->options.contains(key);
}

QStringList CommandLineParser::arguments() const
{
    d->parse();
    return d->arguments;
}

QStringList CommandLineParser::undefinedOptions() const
{
    d->parse();
    return d->undefinedOptions;
}

QString CommandLineParser::optionArgument(const QString &optionName, const QString &defaultValue) const
{
    QStringList answer = optionArguments(optionName);
    if (answer.isEmpty())
        return defaultValue;
    return answer.first();
}

QStringList CommandLineParser::optionArguments(const QString &optionName) const
{
    if (! contains(optionName))
        return QStringList();
    Private::ParsedOption po = d->options[optionName];
    return po.parameters;
}

QStringList CommandLineParser::parseErrors() const
{
    d->parse();
    return d->errors;
}