aboutsummaryrefslogtreecommitdiffstats
path: root/src/qtprojectlib/CommandLineParser.cs
blob: 7c74e9a207f37a590141f9edb417578f859b2f0e (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
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
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt VS Tools.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace QtProjectLib.CommandLine
{
    public class Parser
    {

        List<Option> commandLineOptionList = new List<Option>();
        Dictionary<string, int> nameHash = new Dictionary<string, int>();
        Dictionary<int, List<string>> optionValuesHash = new Dictionary<int, List<string>>();
        List<string> optionNames = new List<string>();
        List<string> positionalArgumentList = new List<string>();
        List<string> unknownOptionNames = new List<string>();
        bool needsParsing = true;

        public enum SingleDashWordOptionMode
        {
            ParseAsCompactedShortOptions = 0,
            ParseAsLongOptions = 1
        }
        SingleDashWordOptionMode singleDashWordOptionMode = 0;

        public enum OptionsAfterPositionalArgumentsMode
        {
            ParseAsOptions = 0,
            ParseAsPositionalArguments = 1
        }
        OptionsAfterPositionalArgumentsMode optionsAfterPositionalArgumentsMode = 0;

        public Parser()
        {
        }

        public string ApplicationDescription
        {
            get;
            set;
        }

        public string ErrorText
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public string HelpText
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public IEnumerable<string> PositionalArguments
        {
            get
            {
                CheckParsed("PositionalArguments");
                return positionalArgumentList;
            }
        }

        public IEnumerable<string> OptionNames
        {
            get
            {
                CheckParsed("OptionNames");
                return optionNames;
            }
        }

        public IEnumerable<string> UnknownOptionNames
        {
            get
            {
                CheckParsed("UnknownOptionNames");
                return unknownOptionNames;
            }
        }

        IEnumerable<string> Aliases(string optionName)
        {
            int optionIndex;
            if (!nameHash.TryGetValue(optionName, out optionIndex)) {
                return new List<string>();
            }
            return commandLineOptionList[optionIndex].Names;
        }

        public void SetSingleDashWordOptionMode(SingleDashWordOptionMode singleDashWordOptionMode)
        {
            this.singleDashWordOptionMode = singleDashWordOptionMode;
        }

        public void SetOptionsAfterPositionalArgumentsMode(
            OptionsAfterPositionalArgumentsMode parsingMode)
        {
            this.optionsAfterPositionalArgumentsMode = parsingMode;
        }

        public bool AddOption(Option option)
        {
            if (option.Names.Any()) {
                foreach (var name in option.Names) {
                    if (nameHash.ContainsKey(name))
                        return false;
                }

                commandLineOptionList.Add(option);

                int offset = commandLineOptionList.Count() - 1;
                foreach (var name in option.Names)
                    nameHash.Add(name, offset);

                return true;
            }

            return false;
        }

        public bool AddOptions(IEnumerable<Option> options)
        {
            bool result = true;
            foreach (var option in options)
                result &= AddOption(option);

            return result;
        }

        public Option AddVersionOption()
        {
            Option opt = new Option(new[] { "v", "version" });
            AddOption(opt);
            return opt;
        }

        public Option AddHelpOption()
        {
            Option opt = new Option(new[] { "?", "h", "help" });
            AddOption(opt);
            return opt;
        }

        public void AddPositionalArgument(string name, string description, string syntax)
        {
            throw new NotImplementedException();
        }

        public void ClearPositionalArguments()
        {
            throw new NotImplementedException();
        }

        bool RegisterFoundOption(string optionName)
        {
            if (nameHash.ContainsKey(optionName)) {
                optionNames.Add(optionName);
                return true;
            } else {
                unknownOptionNames.Add(optionName);
                return false;
            }
        }

        bool ParseOptionValue(string optionName, string argument,
             IEnumerator<string> argumentEnumerator, ref bool atEnd)
        {
            const char assignChar = '=';
            int optionOffset;
            if (nameHash.TryGetValue(optionName, out optionOffset)) {
                int assignPos = argument.IndexOf(assignChar);
                bool withValue = !string.IsNullOrEmpty(
                    commandLineOptionList[optionOffset].ValueName);
                if (withValue) {
                    if (assignPos == -1) {
                        if (atEnd = (!argumentEnumerator.MoveNext())) {
                            return false;
                        }
                        if (!optionValuesHash.ContainsKey(optionOffset))
                            optionValuesHash.Add(optionOffset, new List<string>());
                        optionValuesHash[optionOffset].Add(argumentEnumerator.Current);
                    } else {
                        if (!optionValuesHash.ContainsKey(optionOffset))
                            optionValuesHash.Add(optionOffset, new List<string>());
                        optionValuesHash[optionOffset].Add(argument.Substring(assignPos + 1));
                    }
                } else {
                    if (assignPos != -1) {
                        return false;
                    }
                }
            }
            return true;
        }

        void CheckParsed(string method)
        {
            if (needsParsing)
                Trace.TraceWarning("CommandLineParser: Parse() before {0}", method);
        }

        public bool Parse(string commandLine, string execName)
        {
            List<string> arguments = new List<string>();
            StringBuilder arg = new StringBuilder();
            bool foundExec = false;
            foreach (Match token in Lexer.Tokenize(commandLine)) {
                if (!foundExec) {
                    if (!token.TokenText()
                        .EndsWith(execName,
                        StringComparison.InvariantCultureIgnoreCase)) {
                        continue;
                    }

                    foundExec = true;
                }

                var tokenType = token.TokenType();
                if (tokenType == Token.Newline) {
                    break;
                } else if (tokenType == Token.Whitespace) {
                    if (arg.Length > 0) {
                        arguments.Add(arg.ToString());
                        arg.Clear();
                    }
                } else {
                    arg.Append(token.TokenText());
                }
            }
            if (arg.Length > 0)
                arguments.Add(arg.ToString());
            return Parse(arguments);
        }

        public bool Parse(IEnumerable<string> args)
        {
            needsParsing = false;

            bool error = false;

            const string doubleDashString = "--";
            const char dashChar = '-';
            const char assignChar = '=';

            bool forcePositional = false;
            positionalArgumentList.Clear();
            optionNames.Clear();
            unknownOptionNames.Clear();
            optionValuesHash.Clear();

            if (!args.Any()) {
                return false;
            }

            var argumentIterator = args.GetEnumerator();
            bool atEnd = false;

            while (!atEnd && argumentIterator.MoveNext()) {
                var argument = argumentIterator.Current;
                if (forcePositional) {
                    positionalArgumentList.Add(argument);
                } else if (argument.StartsWith(doubleDashString)) {
                    if (argument.Length > 2) {
                        var optionName = argument.Substring(2).Split(new char[] { assignChar })[0];
                        if (RegisterFoundOption(optionName)) {
                            if (!ParseOptionValue(
                                optionName,
                                argument,
                                argumentIterator,
                                ref atEnd)) {
                                error = true;
                            }

                        } else {
                            error = true;
                        }
                    } else {
                        forcePositional = true;
                    }
                } else if (argument.StartsWith(dashChar.ToString())) {
                    if (argument.Length == 1) { // single dash ("stdin")
                        positionalArgumentList.Add(argument);
                        continue;
                    }
                    string optionName = "";
                    switch (singleDashWordOptionMode) {
                        case SingleDashWordOptionMode.ParseAsCompactedShortOptions:
                            bool valueFound = false;
                            for (int pos = 1; pos < argument.Length; ++pos) {
                                optionName = argument.Substring(pos, 1);
                                if (!RegisterFoundOption(optionName)) {
                                    error = true;
                                } else {
                                    int optionOffset;
                                    Trace.Assert(nameHash.TryGetValue(
                                        optionName,
                                        out optionOffset));
                                    bool withValue = !string.IsNullOrEmpty(
                                        commandLineOptionList[optionOffset].ValueName);
                                    if (withValue) {
                                        if (pos + 1 < argument.Length) {
                                            if (argument[pos + 1] == assignChar)
                                                ++pos;
                                            if (!optionValuesHash.ContainsKey(optionOffset)) {
                                                optionValuesHash.Add(
                                                    optionOffset,
                                                    new List<string>());
                                            }
                                            optionValuesHash[optionOffset].Add(
                                                argument.Substring(pos + 1));
                                            valueFound = true;
                                        }
                                        break;
                                    }
                                    if (pos + 1 < argument.Length
                                        && argument[pos + 1] == assignChar) {
                                        break;
                                    }
                                }
                            }
                            if (!valueFound
                                && !ParseOptionValue(
                                    optionName,
                                    argument,
                                    argumentIterator,
                                    ref atEnd)) {
                                error = true;
                            }

                            break;
                        case SingleDashWordOptionMode.ParseAsLongOptions:
                            if (argument.Length > 2) {
                                string possibleShortOptionStyleName = argument.Substring(1, 1);

                                int shortOptionIdx;
                                if (nameHash.TryGetValue(
                                    possibleShortOptionStyleName,
                                    out shortOptionIdx)) {
                                    var arg = commandLineOptionList[shortOptionIdx];
                                    if ((arg.Flags & Option.Flag.ShortOptionStyle) != 0) {
                                        RegisterFoundOption(possibleShortOptionStyleName);
                                        if (!optionValuesHash.ContainsKey(shortOptionIdx)) {
                                            optionValuesHash.Add(
                                                shortOptionIdx,
                                                new List<string>());
                                        }
                                        optionValuesHash[shortOptionIdx].Add(
                                            argument.Substring(2));
                                        break;
                                    }
                                }
                            }
                            optionName = argument.Substring(1).Split(new char[] { assignChar })[0];
                            if (RegisterFoundOption(optionName)) {
                                if (!ParseOptionValue(
                                    optionName,
                                    argument,
                                    argumentIterator,
                                    ref atEnd)) {
                                    error = true;
                                }

                            } else {
                                error = true;
                            }
                            break;
                    }
                } else {
                    positionalArgumentList.Add(argument);
                    if (optionsAfterPositionalArgumentsMode
                        == OptionsAfterPositionalArgumentsMode.ParseAsPositionalArguments) {
                        forcePositional = true;
                    }
                }
            }
            return !error;
        }

        public bool IsSet(string name)
        {
            CheckParsed("IsSet");
            if (optionNames.Contains(name))
                return true;
            var aliases = Aliases(name);
            foreach (var optionName in optionNames) {
                if (aliases.Contains(optionName))
                    return true;
            }
            return false;
        }

        public string Value(string optionName)
        {
            CheckParsed("Value");
            var valueList = Values(optionName);
            if (valueList.Any())
                return valueList.Last();
            return "";
        }

        public IEnumerable<string> Values(string optionName)
        {
            CheckParsed("Values");
            int optionOffset;
            if (nameHash.TryGetValue(optionName, out optionOffset)) {
                var values = optionValuesHash[optionOffset];
                return values;
            }

            Trace.TraceWarning("QCommandLineParser: option not defined: \"{0}\"", optionName);
            return new List<string>();
        }

        public bool IsSet(Option option)
        {
            return option.Names.Any() && IsSet(option.Names.First());
        }

        public string Value(Option option)
        {
            return Value(option.Names.FirstOrDefault());
        }

        public IEnumerable<string> Values(Option option)
        {
            return Values(option.Names.FirstOrDefault());
        }
    }

    public class Option
    {
        [Flags]
        public enum Flag
        {
            HiddenFromHelp = 0x1,
            ShortOptionStyle = 0x2
        }

        public Option(string name, string valueName = "")
        {
            Names = new[] { name };
            ValueName = valueName;
            Flags = 0;
        }

        public Option(IEnumerable<string> names, string valueName = "")
        {
            Names = names;
            ValueName = valueName;
            Flags = 0;
        }

        public Option(Option other)
        {
            Names = other.Names;
            ValueName = other.ValueName;
            Flags = other.Flags;
        }

        public IEnumerable<string> Names
        {
            get;
            private set;
        }

        public string ValueName
        {
            get;
            set;
        }

        public Flag Flags
        {
            get;
            set;
        }

        public override string ToString()
        {
            return Names.Last();
        }

    }

    enum Token
    {
        Unknown = 0,
        Newline = 1,
        Unquoted = 2,
        Quoted = 3,
        Whitespace = 4
    };

    static class Lexer
    {
        static Regex lexer = new Regex(@"(\n)|([^\s\""]+)|(?:\""([^\""]+)\"")|(\s+)");

        public static Token TokenType(this Match token)
        {
            for (int i = 1; i < token.Groups.Count; i++) {
                if (!string.IsNullOrEmpty(token.Groups[i].Value))
                    return (Token)i;
            }
            return Token.Unknown;
        }

        public static string TokenText(this Match token)
        {
            Token t = TokenType(token);
            if (t != Token.Unknown)
                return token.Groups[(int)t].Value;
            return "";
        }

        public static MatchCollection Tokenize(string commandLine)
        {
            return lexer.Matches(commandLine);
        }
    }
}