This repository has been archived by the owner on Jan 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathCommandLine.cs
1844 lines (1712 loc) · 84.7 KB
/
CommandLine.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Microsoft.Fx.CommandLine
{
// See code:#Overview to get started.
/// <summary>
/// #Overview
///
/// The code:CommandLineParser is a utility for parsing command lines. Command lines consist of three basic
/// entities. A command can have any (or none) of the following (separated by whitespace of any size).
///
/// * PARAMETERS - this are non-space strings. They are positional (logicaly they are numbered). Strings
/// with space can be specified by enclosing in double quotes.
///
/// * QUALIFIERS - Qualifiers are name-value pairs. The following syntax is supported.
/// * -QUALIFIER
/// * -QUALIFIER:VALUE
/// * -QUALIFIER=VALUE
/// * -QUALIFIER VALUE
///
/// The end of a value is delimited by space. Again values with spaces can be encoded by enclosing them
/// the value (or the whole qualifer-value string), in double quotes. The first form (where a value is
/// not specified is only available for boolean qualifiers, and boolean values can not use the form where
/// the qualifer and value are separated by space. The '/' character can also be used instead of the '-'
/// to begin a qualifier.
///
/// Unlike parameters, qualifiers are NOT ordered. They may occur in any order with respect to the
/// parameters or other qualifiers and THAT ORDER IS NOT COMMUNICATED THROUGH THE PARSER. Thus it is not
/// possible to have qualifiers that only apply to specific parameters.
///
/// * PARAMETER SET SPECIFIER - A parameter set is optional argument that looks like a boolean qualifier
/// (however if NoDashOnParameterSets is set the dash is not need, so it is looks like a parameter),
/// that is special in that it decides what qualifiers and positional parameters are allowed. See
/// code:#ParameterSets for more
///
/// #ParameterSets
///
/// Parameter sets are an OPTIONAL facility of code:CommandLineParser that allow more complex command lines
/// to be specified accurately. It not uncommon for a EXE to have several 'commands' that are logically
/// independent of one another. For example a for example For example a program might have 'checkin'
/// 'checkout' 'list' commands, and each of these commands has a different set of parameters that are needed
/// and qualifiers that are allowed. (for example checkout will take a list of file names, list needs nothing,
/// and checkin needs a comment). Additionally some qualifiers (like say -dataBaseName can apply to any of hte
/// commands). Thus You would like to say that the following command lines are legal
///
/// * EXE -checkout MyFile1 MyFile -dataBaseName:MyDatabase
/// * EXE -dataBaseName:MyDatabase -list
/// * EXE -comment "Specifying the comment first" -checkin
/// * EXE -checkin -comment "Specifying the comment afterward"
///
/// But the following are not
///
/// * EXE -checkout
/// * EXE -checkout -comment "hello"
/// * EXE -list MyFile
///
/// You do this by specifying 'checkout', 'list' and 'checkin' as parameters sets. On the command line they
/// look like boolean qualifiers, however they have additional sematantics. They must come before any
/// positional parameters (because they affect whether the parameters are allowed and what they are named),
/// and they are mutually exclusive. Each parameter set gets its own set of parameter definitions, and
/// qualifiers can either be associated with a particular parameter set (like -comment) or global to all
/// parameter sets (like -dataBaseName) .
///
/// By default parameter set specifiers look like a boolean specifier (begin with a '-' or '/'), however
/// because it is common practice to NOT have a dash for commands, there there is a Property
/// code:CommandLineParser.NoDashOnParameterSets that indicates that the dash is not used. If this was
/// specified then the following command would be legal.
///
/// * EXE checkout MyFile1 MyFile -dataBaseName:MyDatabase
///
/// #DefaultParameterSet
///
/// One parameters set (which has the empty string name), is special in that it is used when no other
/// parameter set is matched. This is the default parameter set. For example, if -checkout was defined to be
/// the default parameter set, then the following would be legal.
///
/// * EXE Myfile1 Myfile
///
/// And would implicitly mean 'checkout' Myfile1, Myfile2
///
/// If no parameter sets are defined, then all qualifiers and parameters are in the default parameter set.
///
/// -------------------------------------------------------------------------
/// #Syntatic ambiguities
///
/// Because whitespace can separate a qualifier from its value AND Qualifier from each other, and because
/// parameter values might start with a dash (and thus look like qualifiers), the syntax is ambiguous. It is
/// disambigutated with the following rules.
/// * The command line is parsed into 'arguments' that are spearated by whitespace. Any string enclosed
/// in "" will be a single argument even if it has embedded whitespace. Double quote characters can
/// be specified by \" (and a \" literal can be specified by \\" etc).
/// * Arguments are parsed into qualifiers. This parsing stops if a '--' argument is found. Thus all
/// qualifiers must come before any '--' argument but parameters that begin with - can be specified by
/// placing them after the '--' argument,
/// * Qualifiers are parsed. Because spaces can be used to separate a qualifier from its value, the type of
/// the qualifier must be known to parse it. Boolean values never consume an additional parameter, and
/// non-boolean qualifiers ALWAYS consume the next argument (if there is no : or =). If the empty
/// string is to be specified, it must use the ':' or '=' form. Moreover it is illegal for the values
/// that begin with '-' to use space as a separator. They must instead use the ':' or '=' form. This
/// is because it is too confusing for humans to parse (values look like qualifiers).
/// * Parameters are parsed. Whatever arguments that were not used by qualifiers are parameters.
///
/// --------------------------------------------------------------------------------------------
/// #DefiningParametersAndQualifiers
///
/// The following example shows the steps for defining the parameters and qualifiers for the example. Note
/// that the order is important. Qualifiers that apply to all commands must be specified first, then each
/// parameter set then finally the default parameter set. Most steps are optional.
#if EXAMPLE1
class CommandLineParserExample1
{
enum Command { checkout, checkin, list };
static void Main()
{
string dataBaseName = "myDefaultDataBase";
string comment = String.Empty;
Command command = checkout;
string[] fileNames = null;
// Step 1 define the parser.
CommandLineParser commandLineParser = new CommandLineParser(); // by default uses Environment.CommandLine
// Step 2 (optional) define qualifiers that apply to all parameter sets.
commandLineParser.DefineOptionalParameter("dataBaseName", ref dataBaseName, "Help for database.");
// Step 3A define the checkin command this includes all parameters and qualifiers specific to this command
commandLineParser.DefineParameterSet("checkin", ref command, Command.checkin, "Help for checkin.");
commandLineParser.DefineOptionalQualifiers("comment", ref comment, "Help for -comment.");
// Step 3B define the list command this includes all parameters and qualifiers specific to this command
commandLineParser.DefineParameterSet("list", ref command, Command.list, "Help for list.");
// Step 4 (optional) define the default parameter set (in this case checkout).
commandLineParser.DefineDefaultParameterSet("checkout", ref command, Command.checkout, "Help for checkout.");
commandLineParser.DefineParamter("fileNames", ref fileNames, "Help for fileNames.");
// Step 5, do final validation (look for undefined qualifiers, extra parameters ...
commandLineParser.CompleteValidation();
// Step 6 use the parsed values
Console.WriteLine("Got {0} {1} {2} {3} {4}", dataBaseName, command, comment, string.Join(',', fileNames));
}
}
#endif
/// #RequiredAndOptional
///
/// Parameters and qualifiers can be specified as required (the default), or optional. Makeing the default
/// required was choses to make any mistakes 'obvious' since the parser will fail if a required parameter is
/// not present (if the default was optional, it would be easy to make what should have been a required
/// qualifier optional, leading to business logic failiure).
///
/// #ParsedValues
///
/// The class was designed maximize programmer convinience. For each parameter, only one call is needed to
/// both define the parameter, its help message, and retrive its (strong typed) value. For example
///
/// * int count = 5;
/// * parser.DefineOptionalQualifier("count", ref count, "help for optional debugs qualifier");
///
/// Defines a qualifier 'count' and will place its value in the local variable 'count' as a integer. Default
/// values are supported by doing nothing, so in the example above the default value will be 5.
///
/// Types supported: The parser will support any type that has a static method called 'Parse' taking one
/// string argument and returning that type. This is true for all primtive types, DateTime, Enumerations, and
/// any user defined type that follows this convention.
///
/// Array types: The parser has special knowedge of arrays. If the type of a qualifier is an array, then the
/// string value is assumed to be a ',' separated list of strings which will be parsed as the element type of
/// the array. In addition to the ',' syntax, it is also legal to specify the qualifier more than once. For
/// example given the defintion
///
/// * int[] counts;
/// * parser.DefineOptionalQualifier("counts", ref counts, "help for optional counts qualifier");
///
/// The command line
///
/// * EXE -counts 5 SomeArg -counts 6 -counts:7
///
/// Is the same as
///
/// * EXE -counts:5,6,7 SomeArg
///
/// If a qualifier or parameter is an array type and is required, then the array must have at least one
/// element. If it is optional, then the array can be empty (but in all cases, the array is created, thus
/// null is never returned by the command line parser).
///
/// By default is it is illegal for a non-array qualifier to be specified more than once. It is however
/// possible to override this behavior by setting the LastQualifierWins property before defining the qualifier.
///
/// -------------------------------------------------------------------------
/// #Misc
///
/// Qualifier can have more than one string form (typically a long and a short form). These are specified
/// with the code:CommandLineParser.DefineAliases method.
///
/// After defining all the qualifiers and parameters, it is necessary to call the parser to check for the user
/// specifying a qualifier (or parameter) that does not exist. This is the purpose of the
/// code:CommandLineParser.CompleteValidation method.
///
/// When an error is detected at runtime an instance of code:CommandLineParserException is thrown. The error
/// message in this exception was designed to be suitable to print to the user directly.
///
/// #CommandLineHelp
///
/// The parser also can generate help that is correct for the qualifier and parameter definitions. This can be
/// accessed from the code:CommandLineParser.GetHelp method. It is also possible to get the help for just a
/// particular Parameter set with code:CommandLineParser.GetHelpForParameterSet. This help includes command
/// line syntax, whether the qualifier or parameter is optional or a list, the types of the qualifiers and
/// parameters, the help text, and default values. The help text comes from the 'Define' Methods, and is
/// properly word-wrapped. Newlines in the help text indicate new paragraphs.
///
/// #AutomaticExceptionProcessingAndHelp
///
/// In the CommandLineParserExample1, while the command line parser did alot of the work there is still work
/// needed to make the application user friendly that pretty much all applications need. These include
///
/// * Call the code:CommandLineParser constructor and code:CommandLineParser.CompleteValidation
/// * Catch any code:CommandLineParserException and print a friendly message
/// * Define a -? qualifier and wire it up to print the help.
///
/// Since this is stuff that all applications will likely need the
/// code:CommandLineParser.ParseForConsoleApplication was created to do all of this for you, thus making it
/// super-easy to make a production quality parser (and concentrate on getting your application logic instead
/// of command line parsing. Here is an example which defines a 'Ping' command. If you will notice there are
/// very few lines of code that are not expressing something very specific to this applications. This is how
/// it should be!
#if EXAMPLE2
class CommandLineParserExample2
{
static void Main()
{
// Step 1: Initialize to the defaults
string Host = null;
int Timeout = 1000;
bool Forever = false;
// Step 2: Define the parameters, in this case there is only the default parameter set.
CommandLineParser.ParseForConsoleApplication(args, delegate(CommandLineParser parser)
{
parser.DefineOptionalQualifier("Timeout", ref Timeout, "Timeout in milliseconds to wait for each reply.");
parser.DefineOptionalQualifier("Forever", ref Forever, "Ping forever.");
parser.DefineDefaultParameterSet("Ping sends a network request to a host to reply to the message (to check for liveness).");
parser.DefineParameter("Host", ref Host, "The Host to send a ping message to.");
});
// Step 3, use the parameters
Console.WriteLine("Got {0} {1} {2} {3}", Host, Timeout, Forever);
}
}
#endif
/// Using local variables for the parsed arguments if fine when the program is not complex and the values
/// don't need to be passed around to many routines. In general, however it is often a better idea to
/// create a class whose sole purpose is to act as a repository for the parsed arguments. This also nicely
/// separates all command line processing into a single class. This is how the ping example would look in
/// that style. Notice that the main program no longer holds any command line processing logic. and that
/// 'commandLine' can be passed to other routines in bulk easily.
#if EXAMPLE3
class CommandLineParserExample3
{
static void Main()
{
CommandLine commandLine = new CommandLine();
Console.WriteLine("Got {0} {1} {2} {3}", commandLine.Host, commandLine.Timeout, commandLine.Forever);
}
}
class CommandLine
{
public CommandLine()
{
CommandLineParser.ParseForConsoleApplication(args, delegate(CommandLineParser parser)
{
parser.DefineOptionalQualifier("Timeout", ref Timeout, "Timeout in milliseconds to wait for each reply.");
parser.DefineOptionalQualifier("Forever", ref Forever, "Ping forever.");
parser.DefineDefaultParameterSet("Ping sends a network request to a host to reply to the message (to check for liveness).");
parser.DefineParameter("Host", ref Host, "The Host to send a ping message to.");
});
}
public string Host = null;
public int Timeout = 1000;
public bool Forever = false;
};
#endif
/// <summary>
/// see code:#Overview for more
/// </summary>
public class CommandLineParser
{
/// <summary>
/// If you are building a console Application, there is a common structure to parsing arguments. You want
/// the text formated and output for console windows, and you want /? to be wired up to do this. All
/// errors should be caught and displayed in a nice way. This routine does this 'boiler plate'.
/// </summary>
/// <param name="parseBody">parseBody is the body of the parsing that this outer shell does not provide.
/// in this delegate, you should be defining all the command line parameters using calls to Define* methods.
/// </param>
public static bool ParseForConsoleApplication(Action<CommandLineParser> parseBody, string[] args)
{
return Parse(parseBody, parser =>
{
var parameterSetTofocusOn = parser.HelpRequested;
if (parameterSetTofocusOn.Length == 0)
{
parameterSetTofocusOn = null;
}
string helpString = parser.GetHelp(GetConsoleWidth() - 1, parameterSetTofocusOn, true);
DisplayStringToConsole(helpString);
}, (parser, ex) =>
{
Console.WriteLine("Error: " + ex.Message);
Console.WriteLine("Use -? for help.");
},
args);
}
public static bool Parse(Action<CommandLineParser> parseBody, Action<CommandLineParser> helpHandler, Action<CommandLineParser, Exception> errorHandler, string[] args)
{
var help = false;
CommandLineParser parser = new CommandLineParser(args);
parser.DefineOptionalQualifier("?", ref help, "Print this help guide.");
try
{
// RawPrint the help.
if (parser.HelpRequested != null)
{
parser._skipParameterSets = true;
parser._skipDefinitions = true;
}
parseBody(parser);
if (parser.HelpRequested != null)
{
helpHandler(parser);
return false;
}
parser.CompleteValidation();
return true;
}
catch (CommandLineParserException e)
{
errorHandler(parser, e);
return false;
}
}
/// <summary>
/// Qualifiers are command line parameters of the form -NAME:VALUE where NAME is an alphanumeric name and
/// VALUE is a string. The parser also accepts -NAME: VALUE and -NAME VALUE but not -NAME : VALUE For
/// boolan parameters, the VALUE can be dropped (which means true), and a empty string VALUE means false.
/// Thus -NAME means the same as -NAME:true and -NAME: means the same as -NAME:false (and boolean
/// qualifiers DONT allow -NAME true or -NAME false).
///
/// The types that are supported are any type that has a static 'Parse' function that takes a string
/// (this includes all primitive types as well as DateTime, and Enumerations, as well as arrays of
/// parsable types (values are comma separated without space).
///
/// Qualifiers that are defined BEFORE any parameter sets apply to ALL parameter sets. qualifiers that
/// are defined AFTER a parameter set will apply only the the parameter set that preceeds them.
///
/// See code:#DefiningParametersAndQualifiers
/// See code:#Overview
/// <param name="name">The name of the qualifier.</param>
/// <param name="retVal">The place to put the parsed value</param>
/// <param name="helpText">Text to print for this qualifier. It will be word-wrapped. Newlines indicate
/// new paragraphs.</param>
/// </summary>
public void DefineOptionalQualifier<T>(string name, ref T retVal, string helpText)
{
object obj = DefineQualifier(name, typeof(T), retVal, helpText, false);
if (obj != null)
retVal = (T)obj;
}
/// <summary>
/// Like code:DeclareOptionalQualifier except it is an error if this parameter is not on the command line.
/// <param name="name">The name of the qualifer.</param>
/// <param name="retVal">The place to put the parsed value</param>
/// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate
/// new paragraphs.</param>
/// </summary>
public void DefineQualifier<T>(string name, ref T retVal, string helpText)
{
object obj = DefineQualifier(name, typeof(T), retVal, helpText, true);
if (obj != null)
retVal = (T)obj;
}
/// <summary>
/// Specify additional aliases for an qualifier. This call must come BEFORE the call to
/// Define*Qualifier, since the definition needs to know about its aliases to do its job.
/// </summary>
public void DefineAliases(string officalName, params string[] alaises)
{
// TODO assert that aliases are defined before the Definition.
// TODO confirm no ambiguities (same alias used again).
if (_aliasDefinitions != null && _aliasDefinitions.ContainsKey(officalName))
throw new CommandLineParserDesignerException("Named parameter " + officalName + " already has been given aliases.");
if (_aliasDefinitions == null)
_aliasDefinitions = new Dictionary<string, string[]>();
_aliasDefinitions.Add(officalName, alaises);
}
/// <summary>
/// DefineParameter declares an unnamed mandatory parameter (basically any parameter that is not a
/// qualifier). These are given ordinal numbers (starting at 0). You should declare the parameter in the
/// desired order.
///
///
/// See code:#DefiningParametersAndQualifiers
/// See code:#Overview
/// <param name="name">The name of the parameter.</param>
/// <param name="retVal">The place to put the parsed value</param>
/// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate
/// new paragraphs.</param>
/// </summary>
public void DefineParameter<T>(string name, ref T retVal, string helpText)
{
object obj = DefineParameter(name, typeof(T), retVal, helpText, true);
if (obj != null)
retVal = (T)obj;
}
/// <summary>
/// Like code:DeclareParameter except the parameter is optional.
/// These must come after non-optional (required) parameters.
/// </summary>
/// <param name="name">The name of the parameter</param>
/// <param name="retVal">The location to place the parsed value.</param>
/// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate
/// new paragraphs.</param>
public void DefineOptionalParameter<T>(string name, ref T retVal, string helpText)
{
object obj = DefineParameter(name, typeof(T), retVal, helpText, false);
if (obj != null)
retVal = (T)obj;
}
/// <summary>
/// A parameter set defines on of a set of 'commands' that decides how to parse the rest of the command
/// line. If this 'command' is present on the command line then 'val' is assigned to 'retVal'.
/// Typically 'retVal' is a variable of a enumerated type (one for each command), and 'val' is one
/// specific value of that enumeration.
///
/// * See code:#ParameterSets
/// * See code:#DefiningParametersAndQualifiers
/// * See code:#Overview
/// <param name="name">The name of the parameter set.</param>
/// <param name="retVal">The place to put the parsed value</param>
/// <param name="val">The value to place into 'retVal' if this parameter set is indicated</param>
/// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate
/// new paragraphs.</param>
/// </summary>
public void DefineParameterSet<T>(string name, ref T retVal, T val, string helpText)
{
if (DefineParameterSet(name, helpText))
retVal = val;
}
/// <summary>
/// There is one special parameter set called the default parameter set (whose names is empty) which is
/// used when a command line does not have one of defined parameter sets. It is always present, even if
/// this method is not called, so calling this method is optional, however, by calling this method you can
/// add help text for this case. If present this call must be AFTER all other parameter set
/// definitions.
///
/// * See code:#DefaultParameterSet
/// * See code:#DefiningParametersAndQualifiers
/// * See code:#Overview
/// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate
/// new paragraphs.</param>
/// </summary>
public void DefineDefaultParameterSet(string helpText)
{
DefineParameterSet(String.Empty, helpText);
}
/// <summary>
/// This variation of DefineDefaultParameterSet has a 'retVal' and 'val' parameters. If the command
/// line does not match any of the other parameter set defintions, then 'val' is asigned to 'retVal'.
/// Typically 'retVal' is a variable of a enumerated type and 'val' is a value of that type.
///
/// * See code:DefineDefaultParameterSet for more.
/// <param name="retVal">The place to put the parsed value</param>
/// <param name="val">The value to place into 'retVal' if this parameter set is indicated</param>
/// <param name="helpText">Text to print for this qualifer. It will be word-wrapped. Newlines indicate
/// new paragraphs.</param>
/// </summary>
public void DefineDefaultParameterSet<T>(ref T retVal, T val, string helpText)
{
if (DefineParameterSet(String.Empty, helpText))
retVal = val;
}
// You can influence details of command line parsing by setting the following properties.
// These should be set before the first call to Define* routines and should not change
// thereafter.
/// <summary>
/// By default parameter set specifiers must look like a qualifier (begin with a -), however setting
/// code:NoDashOnParameterSets will define a parameter set marker not to have any special prefix (just
/// the name itself.
/// </summary>
public bool NoDashOnParameterSets
{
get { return _noDashOnParameterSets; }
set
{
if (_noDashOnParameterSets != value)
ThrowIfNotFirst("NoDashOnParameterSets");
_noDashOnParameterSets = value;
}
}
/// <summary>
/// By default, the syntax (-Qualifier:Value) and (-Qualifer Value) are both allowed. However
/// this makes it impossible to use -Qualifier to specify that a qualifier is present but uses
/// a default value (you have to use (-Qualifier: )) Specifying code:NoSpaceOnQualifierValues
/// indicates that the syntax (-Qualifer ObjectEnumerator) is not allowed, which allows this.
/// </summary>
/// TODO decide if we should keep this...
public bool NoSpaceOnQualifierValues
{
get { return _noSpaceOnQualifierValues; }
set
{
if (_noSpaceOnQualifierValues != value)
ThrowIfNotFirst("NoSpaceOnQualifierValues");
_noSpaceOnQualifierValues = value;
}
}
/// <summary>
/// If the positional parameters might look like named parameters (typically happens when the tail of the
/// command line is literal text), it is useful to stop the search for named parameters at the first
/// positional parameter.
///
/// Because some parameters sets might want this behavior and some might not, you specify the list of
/// parameter sets that you want to opt in.
///
/// The expectation is you do something like
/// * commandLine.ParameterSetsWhereQualifiersMustBeFirst = new string[] { "parameterSet1" };
///
/// The empty string is a wildcard that indicats all parameter sets have the qualifiersMustBeFirst
/// attribute. This is the only way to get this attribute on the default parameter set.
/// </summary>
public string[] ParameterSetsWhereQualifiersMustBeFirst
{
get { return _parameterSetsWhereQualifiersMustBeFirst; }
set
{
ThrowIfNotFirst("ParameterSetsWhereQualifiersMustBeFirst");
NoSpaceOnQualifierValues = true;
_parameterSetsWhereQualifiersMustBeFirst = value;
}
}
/// <summary>
/// By default qualifiers may being with a - or a / character. Setting code:QualifiersUseOnlyDash will
/// make / invalid qualifier marker (only - can be used)
/// </summary>
public bool QualifiersUseOnlyDash
{
get { return _qualifiersUseOnlyDash; }
set
{
if (_qualifiersUseOnlyDash != value)
ThrowIfNotFirst("OnlyDashForQualifiers");
_qualifiersUseOnlyDash = value;
}
}
// TODO remove? Not clear it is useful. Can be useful for CMD.EXE alias (which provide a default) but later user may override.
/// <summary>
/// By default, a non-list qualifier can not be specified more than once (since one or the other will
/// have to be ignored). Normally an error is thrown. Setting code:LastQualifierWins makes it legal, and
/// the last qualifier is the one that is used.
/// </summary>
public bool LastQualifierWins
{
get { return _lastQualifierWins; }
set { _lastQualifierWins = value; }
}
// These routines are typically are not needed because ParseArgsForConsoleApp does the work.
#if !COREFX
public CommandLineParser() : this(Environment.CommandLine) { }
#endif
public CommandLineParser(string commandLine)
{
_args = new List<string>();
ParseWords(commandLine);
}
public CommandLineParser(string[] args)
{
_args = new List<string>();
_seenExeArg = true;
for (int i = 0; i < args.Length; i++)
{
if (args[i][0] == '@')
{
// Parse response files
ParseWords(args[i]);
}
else
{
_args.Add(args[i]);
}
}
}
/// <summary>
/// Check for any parameters that the user specified but that were not defined by a Define*Parameter call
/// and throw an exception if any are found.
///
/// Returns true if validation was completed. It can return false (rather than throwing), If the user
/// requested help (/?). Thus if this routine returns false, the 'GetHelp' should be called.
/// </summary>
public bool CompleteValidation()
{
// Check if there are any undefined parameters or ones specified twice.
foreach (int encodedPos in _dashedParameterEncodedPositions.Values)
{
throw new CommandLineParserException("Unexpected qualifier: " + _args[GetPosition(encodedPos)] + ".");
}
// Find any 'unused' parameters;
while (_curPosition < _args.Count && _args[_curPosition] == null)
_curPosition++;
if (_curPosition < _args.Count)
throw new CommandLineParserException("Extra positional parameter: " + _args[_curPosition] + ".");
// TODO we should null out data structures we no longer need, to save space.
// Not critical because in the common case, the parser as a whole becomes dead.
if (_helpRequestedFor != null)
return false;
if (!_defaultParamSetEncountered)
{
if (_paramSetEncountered && _parameterSetName == null)
{
if (_noDashOnParameterSets && _curPosition < _args.Count)
throw new CommandLineParserException("Unrecognised command: " + _args[_curPosition]);
else
throw new CommandLineParserException("No command given.");
}
}
return true;
}
/// <summary>
/// Return the string representing the help for a single paramter set. If displayGlobalQualifiers is
/// true than qualifiers that apply to all parameter sets is also included, otherwise it is just the
/// parameters and qualifiers that are specific to that parameters set.
///
/// If the parameterSetName null, then the help for the entire program (all parameter
/// sets) is returned. If parameterSetName is not null (empty string is default parameter set),
/// then it generates help for the parameter set specified on the command line.
///
/// Since most of the time you don't need help, helpInformatin is NOT collected during the Define* calls
/// unless HelpRequested is true. If /? is seen on the command line first, then this works. You can
/// also force this by setting HelpRequested to True before calling all the Define* APIs.
///
/// </summary>
public string GetHelp(int maxLineWidth, string parameterSetName = null, bool displayGlobalQualifiers = true)
{
Debug.Assert(_mustParseHelpStrings);
if (!_mustParseHelpStrings) // Backup for retail code.
return null;
if (parameterSetName == null)
return GetFullHelp(maxLineWidth);
// Find the beginning of the parameter set parameters, as well as the end of the global parameters
// (Which come before any parameters set).
int parameterSetBody = 0; // Points at body of the parameter set (parameters after the parameter set)
CommandLineParameter parameterSetParameter = null;
for (int i = 0; i < _parameterDescriptions.Count; i++)
{
CommandLineParameter parameter = _parameterDescriptions[i];
if (parameter.IsParameterSet)
{
parameterSetParameter = parameter;
if (string.Compare(parameterSetParameter.Name, parameterSetName, StringComparison.OrdinalIgnoreCase) == 0)
{
parameterSetBody = i + 1;
break;
}
}
}
if (parameterSetBody == 0 && parameterSetName != String.Empty)
return String.Empty;
// At this point parameterSetBody and globalParametersEnd are properly set. Start generating strings
StringBuilder sb = new StringBuilder();
// Create the 'Usage' line;
string appName = GetEntryAssemblyName();
sb.Append("Usage: ").Append(appName);
if (parameterSetName.Length > 0)
{
sb.Append(' ');
sb.Append(parameterSetParameter.Syntax(false, false));
}
bool hasQualifiers = false;
bool hasParameters = false;
for (int i = parameterSetBody; i < _parameterDescriptions.Count; i++)
{
CommandLineParameter parameter = _parameterDescriptions[i];
if (parameter.IsParameterSet)
break;
if (parameter.IsPositional)
{
hasParameters = true;
sb.Append(' ').Append(parameter.Syntax(false, false));
}
else
hasQualifiers = true;
}
sb.AppendLine();
// Print the help for the command itself.
if (parameterSetParameter != null && !string.IsNullOrEmpty(parameterSetParameter.HelpText))
{
sb.AppendLine();
if (parameterSetParameter != null && parameterSetParameter.HelpText != null)
Wrap(sb.Append(" "), parameterSetParameter.HelpText, 2, " ", maxLineWidth);
}
if (hasParameters)
{
sb.AppendLine().Append(" Parameters:").AppendLine();
for (int i = parameterSetBody; i < _parameterDescriptions.Count; i++)
{
CommandLineParameter parameter = _parameterDescriptions[i];
if (parameter.IsParameterSet)
break;
if (parameter.IsPositional)
ParameterHelp(parameter, sb, QualifierSyntaxWidth, maxLineWidth);
}
}
string globalQualifiers = null;
if (displayGlobalQualifiers)
globalQualifiers = GetHelpGlobalQualifiers(maxLineWidth);
if (hasQualifiers || !string.IsNullOrEmpty(globalQualifiers))
{
sb.AppendLine().Append(" Qualifiers:").AppendLine();
for (int i = parameterSetBody; i < _parameterDescriptions.Count; i++)
{
CommandLineParameter parameter = _parameterDescriptions[i];
if (parameter.IsParameterSet)
break;
if (parameter.IsNamed)
ParameterHelp(parameter, sb, QualifierSyntaxWidth, maxLineWidth);
}
if (globalQualifiers != null)
sb.Append(globalQualifiers);
}
return sb.ToString();
}
/// <summary>
/// Returns non-null if the user specified /? on the command line. returns the word after /? (which may be the empty string)
/// </summary>
public string HelpRequested
{
get { return _helpRequestedFor; }
set { _helpRequestedFor = value; _mustParseHelpStrings = true; }
}
#region private
/// <summary>
/// CommandLineParameter contains the 'full' information for a parameter or qualifier used for generating help.
/// Most of the time we don't actualy generate instances of this class. (see mustParseHelpStrings)
/// </summary>
private class CommandLineParameter
{
public string Name { get { return _name; } }
public Type Type { get { return _type; } }
public object DefaultValue { get { return _defaultValue; } }
public bool IsRequired { get { return _isRequired; } }
public bool IsPositional { get { return _isPositional; } }
public bool IsNamed { get { return !_isPositional; } }
public bool IsParameterSet { get { return _isParameterSet; } }
public string HelpText { get { return _helpText; } }
public override string ToString()
{
return "<CommandLineParameter " +
"Name=\"" + _name + "\" " +
"Type=\"" + _type + "\" " +
"IsRequired=\"" + IsRequired + "\" " +
"IsPositional=\"" + IsPositional + "\" " +
"HelpText=\"" + HelpText + "\"/>";
}
public string Syntax(bool printType, bool printDefaultValue)
{
string ret = _name;
if (IsNamed)
ret = "-" + ret;
if (printType)
{
// We print out arrays with the ... notiation, so we don't want the [] when we display the type
Type displayType = Type;
if (displayType.IsArray)
displayType = displayType.GetElementType();
if (displayType.GetTypeInfo().IsGenericType && displayType.GetGenericTypeDefinition() == typeof(Nullable<>))
displayType = displayType.GetGenericArguments()[0];
bool shouldPrint = true;
// Bool type implied on named parameters
if (IsNamed && _type == typeof(bool))
{
shouldPrint = false;
if (_defaultValue != null && (bool)_defaultValue)
shouldPrint = false;
}
// string type is implied on positional parameters
if (IsPositional && displayType == typeof(string) && string.IsNullOrEmpty(_defaultValue as string))
shouldPrint = false;
if (shouldPrint)
{
ret = ret + (IsNamed ? ":" : ".") + displayType.Name.ToUpper();
if (printDefaultValue && _defaultValue != null)
{
string defValue = _defaultValue.ToString();
if (defValue.Length < 40) // TODO is this reasonable?
ret += "(" + defValue + ")";
}
}
}
if (Type.IsArray)
ret = ret + (IsNamed ? "," : " ") + "...";
if (!IsRequired)
ret = "[" + ret + "]";
return ret;
}
#region private
internal CommandLineParameter(string Name, object defaultValue, string helpText, Type type,
bool isRequired, bool isPositional, bool isParameterSet)
{
_name = Name;
_defaultValue = defaultValue;
_type = type;
_helpText = helpText;
_isRequired = isRequired;
_isPositional = isPositional;
_isParameterSet = isParameterSet;
}
private string _name;
private object _defaultValue;
private string _helpText;
private Type _type;
private bool _isRequired;
private bool _isPositional;
private bool _isParameterSet;
#endregion
}
private void ThrowIfNotFirst(string propertyName)
{
if (_qualiferEncountered || _positionalArgEncountered || _paramSetEncountered)
throw new CommandLineParserDesignerException("The property " + propertyName + " can only be set before any calls to Define* Methods.");
}
private static bool IsDash(char c)
{
// can be any of ASCII dash (0x002d), endash (0x2013), emdash (0x2014) or hori-zontal bar (0x2015).
return c == '-' || ('\x2013' <= c && c <= '\x2015');
}
/// <summary>
/// Returns true if 'arg' is a qualifier begins with / or -
/// </summary>
private bool IsQualifier(string arg)
{
if (arg.Length < 1)
return false;
if (IsDash(arg[0]))
return true;
if (!_qualifiersUseOnlyDash && arg[0] == '/')
return true;
return false;
}
/// <summary>
/// Qualifiers have the syntax -/NAME=Value. This returns the NAME
/// </summary>
private string ParseParameterName(string arg)
{
string ret = null;
if (arg != null && IsQualifier(arg))
{
int endName = arg.IndexOfAny(s_separators);
if (endName < 0)
endName = arg.Length;
ret = arg.Substring(1, endName - 1);
}
return ret;
}
/// <summary>
/// Parses 'commandLine' into words (space separated items). Handles quoting (using double quotes)
/// and handles escapes of double quotes and backslashes with the \" and \\ syntax.
/// In theory this mimics the behavior of the parsing done before Main to parse the command line into
/// the string[].
/// </summary>
/// <param name="commandLine"></param>
private void ParseWords(string commandLine)
{
int wordStartIndex = -1;
bool hasExcapedQuotes = false;
bool isResponseFile = false;
int numQuotes = 0;
// Loop to <=length to reuse the same logic for AddWord on spaces and the end of the string
for (int i = 0; i <= commandLine.Length; i++)
{
char c = (i < commandLine.Length ? commandLine[i] : '\0');
if (c == '"')
{
numQuotes++;
if (wordStartIndex < 0)
wordStartIndex = i;
i++;
for (;;)
{
if (i >= commandLine.Length)
throw new CommandLineParserException("Unmatched quote at position " + i + ".");
c = commandLine[i];
if (c == '"')
{
if (i > 0 && commandLine[i - 1] == '\\')
hasExcapedQuotes = true;
else
break;
}
i++;
}
}
else if (c == ' ' || c == '\t' || c == '\0')
{
if (wordStartIndex >= 0)
{
AddWord(ref commandLine, wordStartIndex, i, numQuotes, hasExcapedQuotes, isResponseFile);
wordStartIndex = -1;
hasExcapedQuotes = false;
numQuotes = 0;
isResponseFile = false;
}
}
else if (c == '@')
{
isResponseFile = true;
}
else
{
if (wordStartIndex < 0)
wordStartIndex = i;
}
}
}
private void AddWord(ref string commandLine, int wordStartIndex, int wordEndIndex, int numQuotes, bool hasExcapedQuotes, bool isResponseFile)
{
if (!_seenExeArg)
{
_seenExeArg = true;
return;
}
string word;
if (numQuotes > 0)
{
// Common case, the whole word is quoted, and no escaping happened.
if (!hasExcapedQuotes && numQuotes == 1 && commandLine[wordStartIndex] == '"' && commandLine[wordEndIndex - 1] == '"')
word = commandLine.Substring(wordStartIndex + 1, wordEndIndex - wordStartIndex - 2);
else
{
// Remove "" (except for quoted quotes!)
StringBuilder sb = new StringBuilder();
for (int i = wordStartIndex; i < wordEndIndex;)
{
char c = commandLine[i++];
if (c != '"')