-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
CmdParser.cs
2352 lines (2092 loc) · 91.3 KB
/
CmdParser.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
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
//////////////////////////////////////////////////////////////////////////////
// Command Line Argument Parser
// ----------------------------
// Usage
// -----
//
// Parsing command line arguments to a console application is a common problem.
// This library handles the common task of reading arguments from a command line
// and filling in the values in a type.
//
// To use this library, define a class whose fields represent the data that your
// application wants to receive from arguments on the command line. Then call
// CommandLine.ParseArguments() to fill the object with the data
// from the command line. Each field in the class defines a command line argument.
// The type of the field is used to validate the data read from the command line.
// The name of the field defines the name of the command line option.
//
// The parser can handle fields of the following types:
//
// - string
// - int
// - uint
// - bool
// - enum
// - array of the above type
//
// For example, suppose you want to read in the argument list for wc (word count).
// wc takes three optional boolean arguments: -l, -w, and -c and a list of files.
//
// You could parse these arguments using the following code:
//
// class WCArguments
// {
// public bool lines;
// public bool words;
// public bool chars;
// public string[] files;
// }
//
// class WC
// {
// static void Main(string[] args)
// {
// if (CommandLine.ParseArgumentsWithUsage(args, parsedArgs))
// {
// // insert application code here
// }
// }
// }
//
// So you could call this aplication with the following command line to count
// lines in the foo and bar files:
//
// wc.exe /lines /files:foo /files:bar
//
// The program will display the following usage message when bad command line
// arguments are used:
//
// wc.exe -x
//
// Unrecognized command line argument '-x'
// /lines[+|-] short form /l
// /words[+|-] short form /w
// /chars[+|-] short form /c
// /files=<string> short form /f
// @<file> Read response file for more options
//
// That was pretty easy. However, you realy want to omit the "/files:" for the
// list of files. The details of field parsing can be controled using custom
// attributes. The attributes which control parsing behaviour are:
//
// ArgumentAttribute
// - controls short name, long name, required, allow duplicates, default value
// and help text
// DefaultArgumentAttribute
// - allows omition of the "/name".
// - This attribute is allowed on only one field in the argument class.
//
// So for the wc.exe program we want this:
//
// using System;
// using Utilities;
//
// class WCArguments
// {
// [Argument(ArgumentType.AtMostOnce, HelpText="Count number of lines in the input text.")]
// public bool lines;
// [Argument(ArgumentType.AtMostOnce, HelpText="Count number of words in the input text.")]
// public bool words;
// [Argument(ArgumentType.AtMostOnce, HelpText="Count number of chars in the input text.")]
// public bool chars;
// [DefaultArgument(ArgumentType.MultipleUnique, HelpText="Input files to count.")]
// public string[] files;
// }
//
// class WC
// {
// static void Main(string[] args)
// {
// WCArguments parsedArgs = new WCArguments();
// if (CommandLine.ParseArgumentsWithUsage(args, parsedArgs))
// {
// // insert application code here
// }
// }
// }
//
//
//
// So now we have the command line we want:
//
// wc.exe /lines foo bar
//
// This will set lines to true and will set files to an array containing the
// strings "foo" and "bar".
//
// The new usage message becomes:
//
// wc.exe -x
//
// Unrecognized command line argument '-x'
// /lines[+|-] Count number of lines in the input text. (short form /l)
// /words[+|-] Count number of words in the input text. (short form /w)
// /chars[+|-] Count number of chars in the input text. (short form /c)
// @<file> Read response file for more options
// <files> Input files to count. (short form /f)
//
// If you want more control over how error messages are reported, how /help is
// dealt with, etc you can instantiate the CommandLine.Parser class.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.ML.Runtime.EntryPoints;
using Microsoft.ML.Runtime.Internal.Utilities;
namespace Microsoft.ML.Runtime.CommandLine
{
/// <summary>
/// Used to control parsing of command line arguments.
/// </summary>
[Flags]
public enum ArgumentType
{
/// <summary>
/// Indicates that this field is required. An error will be displayed
/// if it is not present when parsing arguments.
/// </summary>
Required = 0x01,
/// <summary>
/// Only valid in conjunction with Multiple.
/// Duplicate values will result in an error.
/// </summary>
Unique = 0x02,
/// <summary>
/// Inidicates that the argument may be specified more than once.
/// Only valid if the argument is a collection
/// </summary>
Multiple = 0x04,
/// <summary>
/// The default type for non-collection arguments.
/// The argument is not required, but an error will be reported if it is specified more than once.
/// </summary>
AtMostOnce = 0x00,
/// <summary>
/// For non-collection arguments, when the argument is specified more than
/// once no error is reported and the value of the argument is the last
/// value which occurs in the argument list.
/// </summary>
LastOccurenceWins = Multiple,
/// <summary>
/// The default type for collection arguments.
/// The argument is permitted to occur multiple times, but duplicate
/// values will cause an error to be reported.
/// </summary>
MultipleUnique = Multiple | Unique,
}
/// <summary>
/// Indicates that this argument is the default argument.
/// '/' or '-' prefix only the argument value is specified.
/// The ShortName property should not be set for DefaultArgumentAttribute
/// instances. The LongName property is used for usage text only and
/// does not affect the usage of the argument.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class DefaultArgumentAttribute : ArgumentAttribute
{
/// <summary>
/// Indicates that this argument is the default argument.
/// </summary>
/// <param name="type"> Specifies the error checking to be done on the argument. </param>
public DefaultArgumentAttribute(ArgumentType type)
: base(type)
{
}
}
/// <summary>
/// On an enum value - indicates that the value should not be shown in help or UI.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class HideEnumValueAttribute : Attribute
{
public HideEnumValueAttribute()
{
}
}
/// <summary>
/// On an enum value - specifies the display name.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class EnumValueDisplayAttribute : Attribute
{
public readonly string Name;
public EnumValueDisplayAttribute(string name)
{
Name = name;
}
}
/// <summary>
/// A delegate used in error reporting.
/// </summary>
public delegate void ErrorReporter(string message);
[Flags]
public enum SettingsFlags
{
None = 0x00,
ShortNames = 0x01,
NoSlashes = 0x02,
NoUnparse = 0x04,
Default = ShortNames | NoSlashes
}
/// <summary>
/// Parser for command line arguments.
///
/// The parser specification is infered from the instance fields of the object
/// specified as the destination of the parse.
/// Valid argument types are: int, uint, string, bool, enums
/// Also argument types of Array of the above types are also valid.
///
/// Error checking options can be controlled by adding a ArgumentAttribute
/// to the instance fields of the destination object.
///
/// At most one field may be marked with the DefaultArgumentAttribute
/// indicating that arguments without a '-' or '/' prefix will be parsed as that argument.
///
/// If not specified then the parser will infer default options for parsing each
/// instance field. The default long name of the argument is the field name. The
/// default short name is the first character of the long name. Long names and explicitly
/// specified short names must be unique. Default short names will be used provided that
/// the default short name does not conflict with a long name or an explicitly
/// specified short name.
///
/// Arguments which are array types are collection arguments. Collection
/// arguments can be specified multiple times.
/// </summary>
public sealed class CmdParser
{
private const int SpaceBeforeParam = 2;
private readonly ErrorReporter _reporter;
private readonly IHost _host;
// REVIEW: _catalog should be part of environment and can be get through _host.
private Lazy<ModuleCatalog> _catalog;
/// <summary>
/// Parses a command line. This assumes that the exe name has been stripped off.
/// Errors are output on Console.Error.
/// Use ArgumentAttributes to control parsing behaviour.
/// </summary>
/// <param name="env"> The host environment</param>
/// <param name="settings">The command line</param>
/// <param name="destination">The object to receive the options</param>
/// <returns>true if no errors were detected</returns>
public static bool ParseArguments(IHostEnvironment env, string settings, object destination)
{
return ParseArguments(env, settings, destination, Console.Error.WriteLine);
}
/// <summary>
/// Parses a command line. This assumes that the exe name has been stripped off.
/// Use ArgumentAttributes to control parsing behaviour.
/// </summary>
/// <param name="env"> The host environment</param>
/// <param name="settings">The command line</param>
/// <param name="destination">The object to receive the options</param>
/// <param name="destinationType">The type of 'destination'</param>
/// <param name="reporter"> The destination for parse errors. </param>
/// <returns>true if no errors were detected</returns>
public static bool ParseArguments(IHostEnvironment env, string settings, object destination, Type destinationType, ErrorReporter reporter)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(destination, nameof(destination));
env.CheckValue(destinationType, nameof(destinationType));
env.Check(destinationType.IsInstanceOfType(destination));
env.CheckValue(reporter, nameof(reporter));
string[] strs;
if (!LexString(settings, out strs))
{
reporter("Error: Unbalanced quoting in command line arguments");
return false;
}
var info = GetArgumentInfo(destinationType, null);
CmdParser parser = new CmdParser(env, reporter);
return parser.Parse(info, strs, destination);
}
private static bool ParseArguments(string settings, object destination, CmdParser parser)
{
string[] strs;
var destinationType = destination.GetType();
if (!LexString(settings, out strs))
{
parser.Report("Error: Unbalanced quoting in command line arguments");
return false;
}
var info = GetArgumentInfo(destinationType, null);
return parser.Parse(info, strs, destination);
}
/// <summary>
/// Parses a command line. This assumes that the exe name has been stripped off.
/// Use ArgumentAttributes to control parsing behaviour.
/// </summary>
/// <param name="env"> The host environment</param>
/// <param name="settings">The command line</param>
/// <param name="destination">The object to receive the options</param>
/// <param name="reporter"> The destination for parse errors. </param>
/// <returns>true if no errors were detected</returns>
public static bool ParseArguments(IHostEnvironment env, string settings, object destination, ErrorReporter reporter)
{
Contracts.CheckValue(destination, nameof(destination));
return ParseArguments(env, settings, destination, destination.GetType(), reporter);
}
public static bool ParseArguments(IHostEnvironment env, string settings, object destination, out string helpText)
{
return ParseArguments(env, settings, destination, Console.Error.WriteLine, out helpText);
}
public static bool ParseArguments(IHostEnvironment env, string settings, object destination, ErrorReporter reporter, out string helpText)
{
Contracts.CheckValue(env, nameof(env));
env.CheckValue(reporter, nameof(reporter));
var info = GetArgumentInfo(destination.GetType(), destination);
CmdParser parser = new CmdParser(env, reporter);
string[] strs;
if (!LexString(settings, out strs))
reporter("Error: Unbalanced quoting in command line arguments");
else if (parser.Parse(info, strs, destination))
{
helpText = null;
return true;
}
helpText = parser.GetUsageString(env, info);
return false;
}
public static string CombineSettings(string[] settings)
{
if (settings == null || settings.Length == 0)
return null;
StringBuilder sb = new StringBuilder();
foreach (var s in settings)
{
string inner = CmdLexer.UnquoteValue(s);
inner = inner.Trim();
if (inner.Length > 0)
{
if (sb.Length > 0)
sb.Append(' ');
sb.Append(inner);
}
}
return sb.ToString();
}
// REVIEW: Add a method for cloning arguments, instead of going to text and back.
public static string GetSettings(IExceptionContext ectx, object values, object defaults, SettingsFlags flags = SettingsFlags.Default)
{
Type t1 = values.GetType();
Type t2 = defaults.GetType();
Type t;
if (t1 == t2)
t = t1;
else if (t1.IsAssignableFrom(t2))
t = t1;
else if (t2.IsAssignableFrom(t1))
t = t2;
else
return null;
var info = GetArgumentInfo(t, defaults);
return GetSettingsCore(ectx, info, values, flags);
}
public static IEnumerable<KeyValuePair<string, string>> GetSettingPairs(IHostEnvironment env, object values, object defaults, SettingsFlags flags = SettingsFlags.None)
{
Type t1 = values.GetType();
Type t2 = defaults.GetType();
Type t;
if (t1 == t2)
t = t1;
else if (t1.IsAssignableFrom(t2))
t = t1;
else if (t2.IsAssignableFrom(t1))
t = t2;
else
return null;
var info = GetArgumentInfo(t, defaults);
var parser = new CmdParser(env);
return parser.GetSettingPairsCore(env, info, values, flags);
}
public static IEnumerable<KeyValuePair<string, string>> GetSettingPairs(IHostEnvironment env, object values, SettingsFlags flags = SettingsFlags.None)
{
var info = GetArgumentInfo(values.GetType(), null);
var parser = new CmdParser(env);
return parser.GetSettingPairsCore(env, info, values, flags);
}
/// <summary>
/// Check whether a certain type is numeric.
/// </summary>
public static bool IsNumericType(Type type)
{
return
type == typeof(double) ||
type == typeof(float) ||
type == typeof(int) ||
type == typeof(long) ||
type == typeof(short) ||
type == typeof(uint) ||
type == typeof(ulong) ||
type == typeof(ushort);
}
private void Report(string str)
{
_reporter?.Invoke(str);
}
private void Report(string fmt, params object[] args)
{
_reporter?.Invoke(string.Format(fmt, args));
}
/// <summary>
/// Returns a Usage string for command line argument parsing.
/// Use ArgumentAttributes to control parsing behaviour.
/// </summary>
/// <param name="env"> The host environment. </param>
/// <param name="type"> The type of the arguments to display usage for. </param>
/// <param name="defaults"> The default values. </param>
/// <param name="showRsp"> Whether to show the @file item. </param>
/// <param name="columns"> The number of columns to format the output to. </param>
/// <returns> Printable string containing a user friendly description of command line arguments. </returns>
public static string ArgumentsUsage(IHostEnvironment env, Type type, object defaults, bool showRsp = false, int? columns = null)
{
var info = GetArgumentInfo(type, defaults);
var parser = new CmdParser(env);
return parser.GetUsageString(env, info, showRsp, columns);
}
#if CORECLR
/// <summary>
/// Fix the window width for the Core build to remove the kernel32.dll dependency.
/// </summary>
/// <returns></returns>
public static int GetConsoleWindowWidth()
{
return 120;
}
#else
private const int StdOutputHandle = -11;
private struct Coord
{
internal Int16 X;
internal Int16 Y;
}
private struct SmallRect
{
internal Int16 Left;
internal Int16 Top;
internal Int16 Right;
internal Int16 Bottom;
}
private struct ConsoleScreenBufferInfo
{
internal Coord DwSize;
internal Coord DwCursorPosition;
internal Int16 WAttributes;
internal SmallRect SrWindow;
internal Coord DwMaximumWindowSize;
}
[DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
private static extern int GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", EntryPoint = "GetConsoleScreenBufferInfo", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
private static extern int GetConsoleScreenBufferInfo(int hConsoleOutput, ref ConsoleScreenBufferInfo lpConsoleScreenBufferInfo);
/// <summary>
/// Returns the number of columns in the current console window
/// </summary>
/// <returns>Returns the number of columns in the current console window</returns>
public static int GetConsoleWindowWidth()
{
int screenWidth;
ConsoleScreenBufferInfo csbi = new ConsoleScreenBufferInfo();
// Just to remove the warning messages...
csbi.DwCursorPosition.X = 0;
csbi.DwCursorPosition.Y = 0;
csbi.SrWindow.Bottom = 0;
csbi.SrWindow.Top = 0;
csbi.SrWindow.Left = 0;
csbi.SrWindow.Right = 0;
int rc;
rc = GetConsoleScreenBufferInfo(GetStdHandle(StdOutputHandle), ref csbi);
screenWidth = csbi.DwSize.X;
return screenWidth;
}
#endif
private CmdParser(IHostEnvironment env)
{
_host = env.Register("CmdParser");
_catalog = new Lazy<ModuleCatalog>(() => ModuleCatalog.CreateInstance(_host));
_reporter = Console.Error.WriteLine;
}
private CmdParser(IHostEnvironment env, ErrorReporter reporter)
{
Contracts.AssertValueOrNull(reporter);
_host = env.Register("CmdParser");
_catalog = new Lazy<ModuleCatalog>(() => ModuleCatalog.CreateInstance(_host));
_reporter = reporter;
}
public static ArgInfo GetArgInfo(Type type, object defaults)
{
return ArgInfo.Arg.GetInfo(type, defaults);
}
private static string ArgCase(string name)
{
if (string.IsNullOrEmpty(name))
return name;
if (!char.IsUpper(name[0]))
return name;
if (name.Length == 1)
return name.ToLowerInvariant();
if (!char.IsUpper(name[1]))
return name.Substring(0, 1).ToLowerInvariant() + name.Substring(1);
int firstNonUpper;
for (firstNonUpper = 0; firstNonUpper < name.Length && char.IsUpper(name[firstNonUpper]); ++firstNonUpper)
;
Contracts.Assert(1 < firstNonUpper && firstNonUpper <= name.Length);
if (firstNonUpper == name.Length)
return name.ToLowerInvariant();
--firstNonUpper;
return name.Substring(0, firstNonUpper).ToLowerInvariant() + name.Substring(firstNonUpper);
}
private static ArgumentInfo GetArgumentInfo(Type type, object defaults)
{
Contracts.CheckValue(type, nameof(type));
Contracts.CheckParam(type.IsClass, nameof(type));
var args = new List<Argument>();
var map = new Dictionary<string, Argument>();
Argument def = null;
foreach (FieldInfo field in type.GetFields())
{
ArgumentAttribute attr = GetAttribute(field);
if (attr != null)
{
Contracts.Check(!field.IsStatic && !field.IsInitOnly && !field.IsLiteral);
bool isDefault = attr is DefaultArgumentAttribute;
if (isDefault && def != null)
throw Contracts.Except("Duplicate default argument '{0}' vs '{1}'", def.LongName, field.Name);
string name = ArgCase(field.Name);
string[] nicks;
// Semantics of ShortName:
// The string provided represents an array of names separated by commas and spaces, once empty entries are removed.
// 'null' or a singleton array with containing only the long field name means "use the default short name",
// and is represented by the null 'nicks' array.
// 'String.Empty' or a string containing only spaces and commas means "no short name", and is represented by an empty 'nicks' array.
if (attr.ShortName == null)
nicks = null;
else
{
nicks = attr.ShortName.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (nicks.Length == 0 || nicks.Length == 1 && nicks[0].ToLowerInvariant() == name.ToLowerInvariant())
nicks = null;
}
Contracts.Assert(!isDefault || nicks == null);
if (map.ContainsKey(name.ToLowerInvariant()))
throw Contracts.Except("Duplicate name '{0}' in argument type '{1}'", name, type.Name);
if (nicks != null)
{
foreach (var nick in nicks)
{
if (map.ContainsKey(nick.ToLowerInvariant()))
throw Contracts.Except("Duplicate name '{0}' in argument type '{1}'", nick, type.Name);
}
}
var arg = new Argument(isDefault ? -1 : args.Count, name, nicks, defaults, attr, field);
// Note that we put the default arg in the map to ensure that no other args use the same name.
map.Add(name.ToLowerInvariant(), arg);
if (nicks != null)
{
foreach (var nick in nicks)
map.Add(nick.ToLowerInvariant(), arg);
}
if (isDefault)
def = arg;
else
args.Add(arg);
}
}
// If there is a default argument, remove it from the _map.
if (def != null)
{
Contracts.Assert(def.ShortNames == null);
string name = def.LongName.ToLowerInvariant();
Contracts.Assert(map.ContainsKey(name) && map[name] == def);
map.Remove(name);
}
return new ArgumentInfo(type, def, args.ToArray(), map);
}
private static ArgumentAttribute GetAttribute(FieldInfo field)
{
var attrs = field.GetCustomAttributes(typeof(ArgumentAttribute), false).ToArray();
if (attrs.Length == 1)
{
var argumentAttribute = (ArgumentAttribute)attrs[0];
if (argumentAttribute.Visibility == ArgumentAttribute.VisibilityType.EntryPointsOnly)
return null;
return argumentAttribute;
}
Contracts.Assert(attrs.Length == 0);
return null;
}
private void ReportUnrecognizedArgument(string argument)
{
Report("Unrecognized command line argument '{0}'", argument);
}
/// <summary>
/// Parses an argument list into an object
/// </summary>
/// <param name="info"></param>
/// <param name="strs"></param>
/// <param name="destination"></param>
/// <param name="values"></param>
/// <returns> true if successful </returns>
private bool ParseArgumentList(ArgumentInfo info, string[] strs, object destination, ArgValue[] values)
{
if (strs == null)
return true;
bool hadError = false;
for (int i = 0; i < strs.Length; i++)
{
string str = strs[i];
Contracts.Assert(!string.IsNullOrEmpty(str));
Argument arg;
string option;
string value;
string tag;
switch (str[0])
{
case '@':
string[] nested;
hadError |= !LexFileArguments(str.Substring(1), out nested);
hadError |= !ParseArgumentList(info, nested, destination, values);
continue;
case '-':
case '/':
if (!TryGetOptionValue(info, str.Substring(1), out arg, out option, out tag, out value))
{
ReportUnrecognizedArgument(option);
hadError = true;
if (value == null && i + 2 < strs.Length && strs[i + 1] == "=")
i += 2;
continue;
}
break;
default:
// No switch. See if it looks like a switch or a default value.
if (TryGetOptionValue(info, str, out arg, out option, out tag, out value))
{
if (info.ArgDef == null)
break;
// There is a default argument, so if the arg looks like a filename, assume it is
// a default argument.
if (option.Length > 1 || str.Length <= 1 || str[1] != ':')
break;
}
if (info.ArgDef != null)
{
str = CmdLexer.UnquoteValue(str);
hadError |= !info.ArgDef.SetValue(this, ref values[info.Args.Length], str, "", destination);
}
else
{
ReportUnrecognizedArgument(option);
hadError = true;
if (value == null && i + 2 < strs.Length && strs[i + 1] == "=")
i += 2;
}
continue;
}
Contracts.AssertValue(arg);
Contracts.Assert(arg != info.ArgDef);
Contracts.Assert(0 <= arg.Index & arg.Index < info.Args.Length);
if (tag != null && !arg.IsTaggedCollection)
{
hadError = true;
Report("Error: Tag not allowed for option '{0}'", arg.LongName);
tag = null;
}
tag = tag ?? "";
if (value == null)
{
if (i + 2 < strs.Length && strs[i + 1] == "=")
value = strs[i += 2];
else if (arg.ItemValueType == typeof(bool))
{
// The option is a boolean without embedded value, so its value is true.
value = "+";
}
else if (i + 1 < strs.Length)
value = strs[++i];
else
{
hadError = true;
Report("Error: Need a value for option '{0}'", arg.LongName);
continue;
}
}
if (arg.IsComponentFactory)
{
ModuleCatalog.ComponentInfo component;
if (IsCurlyGroup(value) && value.Length == 2)
arg.Field.SetValue(destination, null);
else if (_catalog.Value.TryFindComponentCaseInsensitive(arg.Field.FieldType, value, out component))
{
var activator = Activator.CreateInstance(component.ArgumentType);
if (!IsCurlyGroup(value) && i + 1 < strs.Length && IsCurlyGroup(strs[i + 1]))
{
hadError |= !ParseArguments(CmdLexer.UnquoteValue(strs[i + 1]), activator, this);
i++;
}
if (!hadError)
arg.Field.SetValue(destination, activator);
}
else
{
Report("Error: Failed to find component with name '{0}' for option '{1}'", value, arg.LongName);
hadError |= true;
}
continue;
}
if (arg.IsSubComponentItemType)
{
hadError |= !arg.SetValue(this, ref values[arg.Index], value, tag, destination);
if (!IsCurlyGroup(value) && i + 1 < strs.Length && IsCurlyGroup(strs[i + 1]))
hadError |= !arg.SetValue(this, ref values[arg.Index], strs[++i], "", destination);
continue;
}
if (arg.IsCustomItemType)
{
hadError |= !arg.SetValue(this, ref values[arg.Index], value, tag, destination);
continue;
}
if (IsCurlyGroup(value))
{
value = CmdLexer.UnquoteValue(value);
hadError |= !arg.SetValue(this, ref values[arg.Index], value, tag, destination);
continue;
}
// Collections of value types (enum or number) can be specified as a colon separated list.
if (!arg.IsCollection || value == null || !arg.ItemValueType.IsSubclassOf(typeof(System.ValueType)) ||
arg.ItemValueType == typeof(char) || !value.Contains(":"))
{
hadError |= !arg.SetValue(this, ref values[arg.Index], value, tag, destination);
continue;
}
foreach (string val in value.Split(':'))
hadError |= !arg.SetValue(this, ref values[arg.Index], val, "", destination);
}
return !hadError;
}
// Decompose str into the option, tag (if present) and value (if an embedded value). Get the Argument from the option,
// or return false if there isn't a corresponding Argument.
private bool TryGetOptionValue(ArgumentInfo info, string str, out Argument arg, out string option, out string tag, out string value)
{
// See if it contains a value.
int ichLim = str.IndexOfAny(new char[] { ':', '+', '-' });
if (ichLim > 0 && str[ichLim] == ':')
{
option = str.Substring(0, ichLim);
value = str.Substring(ichLim + 1);
}
else if (ichLim > 0 && ichLim == str.Length - 1)
{
option = str.Substring(0, ichLim);
value = str.Substring(ichLim);
}
else
{
option = str;
value = null;
}
// See if option contains a tag
tag = null;
var open = option.IndexOf('[');
if (open > 0)
{
var close = option.IndexOf(']');
if (close == option.Length - 1)
{
tag = option.Substring(open, close - open + 1);
option = option.Substring(0, open);
}
}
return info.Map.TryGetValue(option.ToLowerInvariant(), out arg);
}
private static bool IsCurlyGroup(string str)
{
return str != null && str.StartsWith("{") && str.EndsWith("}");
}
/// <summary>
/// Parses an argument list.
/// </summary>
/// <param name="info"></param>
/// <param name="strs"> The arguments to parse. </param>
/// <param name="destination"> The destination of the parsed arguments. </param>
/// <returns> true if no parse errors were encountered. </returns>
private bool Parse(ArgumentInfo info, string[] strs, object destination)
{
var values = new ArgValue[info.Args.Length + 1];
bool hadError = !ParseArgumentList(info, strs, destination, values);
// check for missing required arguments
for (int i = 0; i < info.Args.Length; i++)
{
var arg = info.Args[i];
hadError |= arg.Finish(this, values[arg.Index], destination);
}
if (info.ArgDef != null)
hadError |= info.ArgDef.Finish(this, values[info.Args.Length], destination);
return !hadError;
}
private static string GetSettingsCore(IExceptionContext ectx, ArgumentInfo info, object values, SettingsFlags flags)
{
StringBuilder sb = new StringBuilder();
if (info.ArgDef != null)
{
var val = info.ArgDef.GetValue(values);
info.ArgDef.AppendSetting(ectx, sb, val, flags);
}
foreach (Argument arg in info.Args)
{
var val = arg.GetValue(values);
arg.AppendSetting(ectx, sb, val, flags);
}
return sb.ToString();
}
/// <summary>
/// GetSettingsCore handles the top-level case. This handles the nested custom record case.
/// It deals with custom "unparse" functionality, as well as quoting. It also appends to a StringBuilder
/// instead of returning a string.
/// </summary>
private static void AppendCustomItem(IExceptionContext ectx, ArgumentInfo info, object values, SettingsFlags flags, StringBuilder sb)
{
int ich = sb.Length;
// We always call unparse, even when NoUnparse is specified, since Unparse can "cleanse", which
// we also want done in the full case.
if (info.TryUnparse(values, sb))
{
// Make sure it doesn't need quoted.
if ((flags & SettingsFlags.NoUnparse) != 0 || !CmdQuoter.NeedsQuoting(sb, ich))
return;
}
sb.Length = ich;
if (info.ArgDef != null)
{
var val = info.ArgDef.GetValue(values);
info.ArgDef.AppendSetting(ectx, sb, val, flags);
}
foreach (Argument arg in info.Args)
{
var val = arg.GetValue(values);
arg.AppendSetting(ectx, sb, val, flags);
}
string str = sb.ToString(ich, sb.Length - ich);
sb.Length = ich;
CmdQuoter.QuoteValue(str, sb, force: true);
}
private IEnumerable<KeyValuePair<string, string>> GetSettingPairsCore(IExceptionContext ectx, ArgumentInfo info, object values, SettingsFlags flags)
{
StringBuilder buffer = new StringBuilder();
foreach (Argument arg in info.Args)
{
string key = arg.GetKey(flags);
object value = arg.GetValue(values);
foreach (string val in arg.GetSettingStrings(ectx, value, buffer))
yield return new KeyValuePair<string, string>(key, val);
}
}
private struct ArgumentHelpStrings
{
public readonly string Syntax;
public readonly string Help;
public ArgumentHelpStrings(string syntax, string help)
{
Syntax = syntax;
Help = help;
}
}