-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathParser.cs
558 lines (483 loc) · 22.1 KB
/
Parser.cs
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
#region License
// <copyright file="Parser.cs" company="Giacomo Stelluti Scala">
// Copyright 2015-2013 Giacomo Stelluti Scala
// </copyright>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
#region Using Directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using CommandLine.Infrastructure;
using CommandLine.Parsing;
using CommandLine.Text;
#endregion
namespace CommandLine
{
/// <summary>
/// Provides methods to parse command line arguments.
/// </summary>
public sealed class Parser : IDisposable
{
/// <summary>
/// Default exit code (1) used by <see cref="Parser.ParseArgumentsStrict(string[],object,Action)"/>
/// and <see cref="Parser.ParseArgumentsStrict(string[],object,Action<string,object>,Action)"/> overloads.
/// </summary>
public const int DefaultExitCodeFail = 1;
private static readonly Parser DefaultParser = new Parser(true);
private readonly ParserSettings _settings;
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Parser"/> class.
/// </summary>
public Parser()
{
_settings = new ParserSettings { Consumed = true };
}
/// <summary>
/// Initializes a new instance of the <see cref="Parser"/> class,
/// configurable with a <see cref="ParserSettings"/> object.
/// </summary>
/// <param name="settings">The <see cref="ParserSettings"/> object is used to configure
/// aspects and behaviors of the parser.</param>
[Obsolete("Use constructor that accepts Action<ParserSettings>.")]
public Parser(ParserSettings settings)
{
Assumes.NotNull(settings, "settings", SR.ArgumentNullException_ParserSettingsInstanceCannotBeNull);
if (settings.Consumed)
{
throw new InvalidOperationException(SR.InvalidOperationException_ParserSettingsInstanceCanBeUsedOnce);
}
_settings = settings;
_settings.Consumed = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="Parser"/> class,
/// configurable with <see cref="ParserSettings"/> using a delegate.
/// </summary>
/// <param name="configuration">The <see cref="Action<ParserSettings>"/> delegate used to configure
/// aspects and behaviors of the parser.</param>
public Parser(Action<ParserSettings> configuration)
{
Assumes.NotNull(configuration, "configuration", SR.ArgumentNullException_ParserSettingsDelegateCannotBeNull);
_settings = new ParserSettings();
configuration.Invoke(Settings);
_settings.Consumed = true;
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "singleton", Justification = "The constructor that accepts a boolean is designed to support default singleton, the parameter is ignored")]
private Parser(bool singleton)
: this(with =>
{
with.CaseSensitive = false;
with.MutuallyExclusive = false;
with.HelpWriter = Console.Error;
with.ParsingCulture = CultureInfo.InvariantCulture;
})
{
}
/// <summary>
/// Finalizes an instance of the <see cref="CommandLine.Parser"/> class.
/// </summary>
~Parser()
{
Dispose(false);
}
/// <summary>
/// Gets the singleton instance created with basic defaults.
/// </summary>
public static Parser Default
{
get { return DefaultParser; }
}
/// <summary>
/// Gets the instance that implements <see cref="CommandLine.ParserSettings"/> in use.
/// </summary>
public ParserSettings Settings
{
get { return _settings; }
}
/// <summary>
/// Parses a <see cref="System.String"/> array of command line arguments, setting values in <paramref name="options"/>
/// parameter instance's public fields decorated with appropriate attributes.
/// </summary>
/// <param name="args">A <see cref="System.String"/> array of command line arguments.</param>
/// <param name="options">An instance used to receive values.
/// Parsing rules are defined using <see cref="CommandLine.BaseOptionAttribute"/> derived types.</param>
/// <returns>True if parsing process succeed.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="args"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="options"/> is null.</exception>
public bool ParseArguments(string[] args, object options)
{
Assumes.NotNull(args, "args", SR.ArgumentNullException_ArgsStringArrayCannotBeNull);
Assumes.NotNull(options, "options", SR.ArgumentNullException_OptionsInstanceCannotBeNull);
return DoParseArguments(args, options);
}
/// <summary>
/// Parses a <see cref="System.String"/> array of command line arguments with verb commands, setting values in <paramref name="options"/>
/// parameter instance's public fields decorated with appropriate attributes.
/// This overload supports verb commands.
/// </summary>
/// <param name="args">A <see cref="System.String"/> array of command line arguments.</param>
/// <param name="options">An instance used to receive values.
/// Parsing rules are defined using <see cref="CommandLine.BaseOptionAttribute"/> derived types.</param>
/// <param name="onVerbCommand">Delegate executed to capture verb command name and instance.</param>
/// <returns>True if parsing process succeed.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="args"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="options"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="onVerbCommand"/> is null.</exception>
public bool ParseArguments(string[] args, object options, Action<string, object> onVerbCommand)
{
Assumes.NotNull(args, "args", SR.ArgumentNullException_ArgsStringArrayCannotBeNull);
Assumes.NotNull(options, "options", SR.ArgumentNullException_OptionsInstanceCannotBeNull);
Assumes.NotNull(options, "onVerbCommand", SR.ArgumentNullException_OnVerbDelegateCannotBeNull);
object verbInstance = null;
var result = DoParseArgumentsVerbs(args, options, ref verbInstance);
onVerbCommand(args.FirstOrDefault() ?? string.Empty, result ? verbInstance : null);
return result;
}
/// <summary>
/// Parses a <see cref="System.String"/> array of command line arguments, setting values in <paramref name="options"/>
/// parameter instance's public fields decorated with appropriate attributes. If parsing fails, the method invokes
/// the <paramref name="onFail"/> delegate, if null exits with <see cref="Parser.DefaultExitCodeFail"/>.
/// </summary>
/// <param name="args">A <see cref="System.String"/> array of command line arguments.</param>
/// <param name="options">An object's instance used to receive values.
/// Parsing rules are defined using <see cref="CommandLine.BaseOptionAttribute"/> derived types.</param>
/// <param name="onFail">The <see cref="Action"/> delegate executed when parsing fails.</param>
/// <returns>True if parsing process succeed.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="args"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="options"/> is null.</exception>
public bool ParseArgumentsStrict(string[] args, object options, Action onFail = null)
{
Assumes.NotNull(args, "args", SR.ArgumentNullException_ArgsStringArrayCannotBeNull);
Assumes.NotNull(options, "options", SR.ArgumentNullException_OptionsInstanceCannotBeNull);
if (!DoParseArguments(args, options))
{
InvokeAutoBuildIfNeeded(options);
if (onFail == null)
{
Environment.Exit(DefaultExitCodeFail);
}
else
{
onFail();
}
return false;
}
return true;
}
/// <summary>
/// Parses a <see cref="System.String"/> array of command line arguments with verb commands, setting values in <paramref name="options"/>
/// parameter instance's public fields decorated with appropriate attributes. If parsing fails, the method invokes
/// the <paramref name="onFail"/> delegate, if null exits with <see cref="Parser.DefaultExitCodeFail"/>.
/// This overload supports verb commands.
/// </summary>
/// <param name="args">A <see cref="System.String"/> array of command line arguments.</param>
/// <param name="options">An instance used to receive values.
/// Parsing rules are defined using <see cref="CommandLine.BaseOptionAttribute"/> derived types.</param>
/// <param name="onVerbCommand">Delegate executed to capture verb command name and instance.</param>
/// <param name="onFail">The <see cref="Action"/> delegate executed when parsing fails.</param>
/// <returns>True if parsing process succeed.</returns>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="args"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="options"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown if <paramref name="onVerbCommand"/> is null.</exception>
public bool ParseArgumentsStrict(string[] args, object options, Action<string, object> onVerbCommand, Action onFail = null)
{
Assumes.NotNull(args, "args", SR.ArgumentNullException_ArgsStringArrayCannotBeNull);
Assumes.NotNull(options, "options", SR.ArgumentNullException_OptionsInstanceCannotBeNull);
Assumes.NotNull(options, "onVerbCommand", SR.ArgumentNullException_OnVerbDelegateCannotBeNull);
object verbInstance = null;
if (!DoParseArgumentsVerbs(args, options, ref verbInstance))
{
onVerbCommand(args.FirstOrDefault() ?? string.Empty, null);
InvokeAutoBuildIfNeeded(options);
if (onFail == null)
{
Environment.Exit(DefaultExitCodeFail);
}
else
{
onFail();
}
return false;
}
onVerbCommand(args.FirstOrDefault() ?? string.Empty, verbInstance);
return true;
}
/// <summary>
/// Frees resources owned by the instance.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "By design")]
internal static object InternalGetVerbOptionsInstanceByName(string verb, object target, out bool found)
{
found = false;
if (string.IsNullOrEmpty(verb))
{
return target;
}
var pair = ReflectionHelper.RetrieveOptionProperty<VerbOptionAttribute>(target, verb);
found = pair != null;
return found ? pair.Left.GetValue(target, null) : target;
}
private static void SetParserStateIfNeeded(object options, IEnumerable<ParsingError> errors)
{
if (!options.CanReceiveParserState())
{
return;
}
var property = ReflectionHelper.RetrievePropertyList<ParserStateAttribute>(options)[0].Left;
var parserState = property.GetValue(options, null);
if (parserState != null)
{
if (!(parserState is IParserState))
{
throw new InvalidOperationException(SR.InvalidOperationException_ParserStateInstanceBadApplied);
}
if (!(parserState is ParserState))
{
throw new InvalidOperationException(SR.InvalidOperationException_ParserStateInstanceCannotBeNotNull);
}
}
else
{
try
{
property.SetValue(options, new ParserState(), null);
}
catch (Exception ex)
{
throw new InvalidOperationException(SR.InvalidOperationException_ParserStateInstanceBadApplied, ex);
}
}
var state = (IParserState)property.GetValue(options, null);
foreach (var error in errors)
{
state.Errors.Add(error);
}
}
private static StringComparison GetStringComparison(ParserSettings settings)
{
return settings.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
}
private bool DoParseArguments(string[] args, object options)
{
var pair = ReflectionHelper.RetrieveMethod<HelpOptionAttribute>(options);
var helpWriter = _settings.HelpWriter;
if (pair != null && helpWriter != null)
{
// If help can be handled is displayed if is requested or if parsing fails
if (ParseHelp(args, pair.Right) || !DoParseArgumentsCore(args, options))
{
string helpText;
HelpOptionAttribute.InvokeMethod(options, pair, out helpText);
helpWriter.Write(helpText);
return false;
}
return true;
}
return DoParseArgumentsCore(args, options);
}
private bool DoParseArgumentsCore(string[] args, object options)
{
var hadError = false;
var optionMap = OptionMap.Create(options, _settings);
optionMap.SetDefaults();
var valueMapper = new ValueMapper(options, _settings.ParsingCulture);
var arguments = new StringArrayEnumerator(args);
while (arguments.MoveNext())
{
var argument = arguments.Current;
if (string.IsNullOrEmpty(argument))
{
continue;
}
var parser = ArgumentParser.Create(argument, _settings.IgnoreUnknownArguments);
if (parser != null)
{
var result = parser.Parse(arguments, optionMap, options);
if ((result & PresentParserState.Failure) == PresentParserState.Failure)
{
SetParserStateIfNeeded(options, parser.PostParsingState);
hadError = true;
continue;
}
if ((result & PresentParserState.MoveOnNextElement) == PresentParserState.MoveOnNextElement)
{
arguments.MoveNext();
}
}
else if (valueMapper.CanReceiveValues)
{
if (!valueMapper.MapValueItem(argument))
{
hadError = true;
}
}
}
hadError |= !optionMap.EnforceRules();
return !hadError;
}
private bool DoParseArgumentsVerbs(string[] args, object options, ref object verbInstance)
{
var verbs = ReflectionHelper.RetrievePropertyList<VerbOptionAttribute>(options);
var helpInfo = ReflectionHelper.RetrieveMethod<HelpVerbOptionAttribute>(options);
if (args.Length == 0)
{
if (helpInfo != null || _settings.HelpWriter != null)
{
DisplayHelpVerbText(options, helpInfo, null);
}
return false;
}
var optionMap = OptionMap.Create(options, verbs, _settings);
if (TryParseHelpVerb(args, options, helpInfo, optionMap))
{
return false;
}
var verbOption = optionMap[args.First()];
// User invoked a bad verb name
if (verbOption == null)
{
if (helpInfo != null)
{
DisplayHelpVerbText(options, helpInfo, null);
}
return false;
}
verbInstance = verbOption.GetValue(options);
if (verbInstance == null)
{
// Developer has not provided a default value and did not assign an instance
verbInstance = verbOption.CreateInstance(options);
}
var verbResult = DoParseArgumentsCore(args.Skip(1).ToArray(), verbInstance);
if (!verbResult && helpInfo != null)
{
// Particular verb parsing failed, we try to print its help
DisplayHelpVerbText(options, helpInfo, args.First());
}
return verbResult;
}
private bool ParseHelp(string[] args, HelpOptionAttribute helpOption)
{
var caseSensitive = _settings.CaseSensitive;
foreach (var arg in args)
{
if (helpOption.ShortName != null)
{
if (ArgumentParser.CompareShort(arg, helpOption.ShortName, caseSensitive))
{
return true;
}
}
if (string.IsNullOrEmpty(helpOption.LongName))
{
continue;
}
if (ArgumentParser.CompareLong(arg, helpOption.LongName, caseSensitive))
{
return true;
}
}
return false;
}
private bool TryParseHelpVerb(string[] args, object options, Pair<MethodInfo, HelpVerbOptionAttribute> helpInfo, OptionMap optionMap)
{
var helpWriter = _settings.HelpWriter;
if (helpInfo != null && helpWriter != null)
{
if (string.Compare(args[0], helpInfo.Right.LongName, GetStringComparison(_settings)) == 0)
{
// User explicitly requested help
var verb = args.ElementAtOrDefault(1);
if (verb != null)
{
var verbOption = optionMap[verb];
if (verbOption != null)
{
if (verbOption.GetValue(options) == null)
{
// We need to create an instance also to render help
verbOption.CreateInstance(options);
}
}
}
DisplayHelpVerbText(options, helpInfo, verb);
return true;
}
}
return false;
}
private void DisplayHelpVerbText(object options, Pair<MethodInfo, HelpVerbOptionAttribute> helpInfo, string verb)
{
string helpText;
if (verb == null)
{
HelpVerbOptionAttribute.InvokeMethod(options, helpInfo, null, out helpText);
}
else
{
HelpVerbOptionAttribute.InvokeMethod(options, helpInfo, verb, out helpText);
}
if (_settings.HelpWriter != null)
{
_settings.HelpWriter.Write(helpText);
}
}
private void InvokeAutoBuildIfNeeded(object options)
{
if (_settings.HelpWriter == null ||
options.HasHelp() ||
options.HasVerbHelp())
{
return;
}
// We print help text for the user
_settings.HelpWriter.Write(
HelpText.AutoBuild(
options,
current => HelpText.DefaultParsingErrorsHandler(options, current),
options.HasVerbs()));
}
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
if (_settings != null)
{
_settings.Dispose();
}
_disposed = true;
}
}
}
}