-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathArguments.cs
1096 lines (954 loc) · 38.3 KB
/
Arguments.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sttz.InstallUnity
{
/// <summary>
/// Exception representing an input error when parsing arguments.
/// </summary>
public class ArgumentsException : Exception
{
/// <summary>
/// Position of the argument related to the error.
/// </summary>
public int ArgumentIndex { get; protected set; }
public ArgumentsException(string message, int index = -1) : base(message)
{
ArgumentIndex = index;
}
}
/// <summary>
/// Simple arguments parser, modeled to be permissive and following GNU option syntax.
/// </summary>
/// <remarks>
/// Exhaustive list of features:
/// - Options and positional arguments
/// - Short (-x), long options (--xxx) and windows-style options (/x, /xxx)
/// - Short options can be combined (-xyz is equivalent to -x -y -z)
/// - Options can have an argument (-x arg, --xxx arg, --xxx=arg, --xxx:arg, -zyx arg)
/// - Options can have multiple arguments (either comma-separated or space-separated)
/// - Options can optionally be repeatable (-vv, -p one -p two)
/// - Options can optionally be required, arguments can optionally be optional
/// - Actions with own options and positional arguments
/// (action must be first positional argument, global options are allowed before action)
/// - Free ordering of options and arguments
/// - Usage of -- to terminate option parsing (everything that follows is treated as positional arguments)
/// - Currently only bool, string, enums and IList<string> are supported
/// - Generate help
/// - Generate error with faulty argument highlighted
///
/// Not supported:
/// - Short option argument without a space (-xARG)
/// - Long options with single dash (-xxx)
///
/// NOTE: Space-separated lists can eat the positional argument, use of -- required
/// NOTE: Optional arguments can eat positinal arguments, use of -- or = required
/// </remarks>
public class Arguments<T>
{
// -------- API --------
/// <summary>
/// Define a new action. All following Options will become child options of this action.
/// </summary>
/// <param name="name">Name of the action (null = global / no action)</param>
/// <param name="callback">Callback executed when the action has been selected</param>
public Arguments<T> Action(string name, Action<T, string> callback = null)
{
if (name == null) {
name = "";
}
if (actions.ContainsKey(name)) {
throw new ArgumentException($"Action '{name}' already defined.");
}
definedAction = new ActionDef() {
name = name,
callback = callback
};
actions[definedAction.name] = definedAction;
definedOption = null;
return this;
}
/// <summary>
/// Make the current action the default action (used when no action is explicitly set).
/// </summary>
/// <param name="usingDefaultAction">Called if no action is specified and the default is used</param>
public Arguments<T> DefaultAction(Action<T> usingDefaultAction = null)
{
if (definedAction == null) {
throw new InvalidOperationException($"No current action set to make default");
}
if (usingDefaultAction != null) {
this.usingDefaultAction = usingDefaultAction;
}
defaultAction = definedAction.name;
return this;
}
/// <summary>
/// Define a boolean option (flag).
/// By default the option is optional and not repeatable.
/// Boolean opotions do not take an argument.
/// </summary>
/// <param name="setter">Callback called when the option is set</param>
/// <param name="names">Names of the option</param>
public Arguments<T> Option(Action<T, bool> setter, params string[] names)
{
AddOption(typeof(bool), new OptionDef<bool>() {
action = definedAction?.name,
names = names,
position = -1,
setter = setter
});
return this;
}
/// <summary>
/// Define an option with a string argument.
/// By default the option is optional and not repeatable, the argument required.
/// </summary>
/// <param name="setter">Callback called when the option is set</param>
/// <param name="names">Names of the option</param>
public Arguments<T> Option(Action<T, string> setter, params string[] names)
{
AddOption(typeof(string), new OptionDef<string>() {
action = definedAction?.name,
names = names,
position = -1,
requiresArgument = true,
setter = setter
});
return this;
}
/// <summary>
/// Define an option with a Enum argument.
/// By default the option is optional and not repeatable, the argument required.
/// </summary>
/// <param name="setter">Callback called when the option is set</param>
/// <param name="names">Names of the option</param>
public Arguments<T> Option<TEnum>(Action<T, TEnum> setter, params string[] names) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException($"Type {typeof(TEnum)} is not an Enum", nameof(TEnum));
AddOption(typeof(string), new OptionDef<string>() {
action = definedAction?.name,
names = names,
position = -1,
requiresArgument = true,
argumentName = string.Join("|", Enum.GetNames(typeof(TEnum)).Select(n => n.ToLower())),
setter = (target, input) => {
if (string.IsNullOrEmpty(input)) {
setter(target, default);
return;
}
TEnum value;
if (!Enum.TryParse<TEnum>(input, true, out value)) {
var values = Enum.GetNames(typeof(TEnum)).Select(v => "'" + v.ToLower() + "'");
var name = names.FirstOrDefault(n => n.Length > 1);
if (name == null) name = names[0];
throw new ArgumentsException($"Invalid value for {name}: '{input}' (must be {string.Join(", ", values)})");
}
setter(target, value);
}
});
return this;
}
/// <summary>
/// Define a list option.
/// By default the option is optional and not repeatable, the argument required.
/// </summary>
/// <param name="setter">Callback called when the option is set</param>
/// <param name="names">Names of the option</param>
public Arguments<T> Option(Action<T, IList<string>> setter, params string[] names)
{
AddOption(typeof(IList<string>), new OptionDef<IList<string>>() {
action = definedAction?.name,
names = names,
position = -1,
requiresArgument = true,
setter = setter
});
return this;
}
/// <summary>
/// Define a positional option (argument).
/// By default the option is optional.
/// </summary>
/// <param name="setter">Callback called when the option is set</param>
/// <param name="position">Position of the argument</param>
public Arguments<T> Option(Action<T, string> setter, int position)
{
if (position > 0) {
var option = FindOption(definedAction?.name, position - 1);
if (option == null) throw new ArgumentException($"Invalid position {position}: No Option at position {position-1} defined");
if (option.repeatable) throw new InvalidOperationException("Cannot add another positional argument after a repeatable positional argument");
}
AddOption(typeof(string), new OptionDef<string>() {
action = definedAction?.name,
names = null,
position = position,
setter = setter
});
return this;
}
/// <summary>
/// Make the last defined option repeatable.
/// The callback will be called multiple times for each instance the option appears in the arguments.
/// </summary>
public Arguments<T> Repeatable(bool repeatable = true)
{
if (definedOption == null) throw new InvalidOperationException("Repeatable: No current option to operate on");
definedOption.repeatable = repeatable;
return this;
}
/// <summary>
/// Make the last defined option required.
/// </summary>
public Arguments<T> Required(bool required = true)
{
if (definedOption == null) throw new InvalidOperationException("Required: No current option to operate on");
if (definedOption is OptionDef<bool>) throw new InvalidOperationException("Required: Boolean options cannot be required");
definedOption.required = required;
return this;
}
/// <summary>
/// Make the last defined option's argument required (default) or optional (pass false).
/// </summary>
public Arguments<T> OptionalArgument(bool optional = true)
{
if (definedOption == null) throw new InvalidOperationException("OptionalArgument: No current option to operate on");
if (definedOption.position >= 0) throw new InvalidOperationException("OptionalArgument: Positional option doesn't have argument");
if (definedOption is OptionDef<bool>) throw new InvalidOperationException("OptionalArgument: Boolean options cannot require argument");
definedOption.requiresArgument = !optional;
return this;
}
/// <summary>
/// Set an argument name to use in the help.
/// This method can be used for options that take arguments and for positional arguments.
/// The default name is <arg>, the <> should be included in the name.
/// </summary>
public Arguments<T> ArgumentName(string name)
{
if (definedOption == null) throw new InvalidOperationException("ArgumentName: No current option to operate on");
if (!TakesArgument(definedOption)) throw new InvalidOperationException("ArgumentName: Option does not take argument(s)");
definedOption.argumentName = name;
return this;
}
/// <summary>
/// Provide a description to be shown in the help.
/// Can be used for actions, options and positional arguments.
/// </summary>
public Arguments<T> Description(string desc)
{
if (definedAction == null && definedOption == null)
throw new InvalidOperationException("Description: No action or option to operate on");
if (definedOption != null) {
definedOption.description = desc;
} else {
definedAction.description = desc;
}
return this;
}
/// <summary>
/// Parse the given arguments and return the selected action.
/// </summary>
/// <param name="target">The target object</param>
/// <param name="args">Input arguments to parse.</param>
public void Parse(T target, string[] args)
{
var hasActions = actions.Count > 0;
var explicitAction = false;
var argPos = -1;
var processOptions = true;
parsedAction = defaultAction;
for (int i = 0; i < args.Length; i++) {
var arg = args[i];
// -- terminates parsing of options and forces the
// rest to be interpreted as positional arguments
if (arg == "--") {
processOptions = false;
continue;
}
var isOption = false;
// - can be used to represent stdin
if (processOptions && arg != "-") {
// Long unix-style options: --xxx
if (arg.StartsWith("--")) {
var name = GetName(arg.Substring(2));
var opt = FindOption(parsedAction, name, false);
if (opt != null) {
i += CallOption(opt, name, true, target, args, i);
isOption = true;
} else {
throw new ArgumentsException($"Unknown option: {name}", i);
}
// Short and long windows-style options: /x /xxx
} else if (arg.StartsWith("/")) {
var name = GetName(arg.Substring(1));
var opt = FindOption(parsedAction, name, null);
if (opt != null) {
i += CallOption(opt, name, true, target, args, i);
isOption = true;
} else {
// Don't treat this as an error, as it could be a path
}
// Short unix-style options: -x -xyz
} else if (arg.StartsWith("-")) {
for (int j = 1; j < arg.Length; j++) {
var name = arg[j].ToString();
var opt = FindOption(parsedAction, name, true);
if (opt != null) {
i += CallOption(opt, name, j == arg.Length - 1, target, args, i);
isOption = true;
} else {
throw new ArgumentsException($"Unknown short option: {name}", i);
}
}
}
}
// Parse as positional argument
if (!isOption) {
argPos++;
// First positional argument is parsed as action
if (hasActions && argPos == 0 && actions.ContainsKey(arg)) {
explicitAction = true;
parsedAction = arg;
} else {
var pos = argPos - (explicitAction ? 1 : 0);
var opt = FindOption(parsedAction, pos);
if (opt != null) {
CallOption(opt, target, arg);
} else {
throw new ArgumentsException($"Unexpected argument at position #{pos}: {arg}", i);
}
}
}
}
// Check for missing required options
foreach (var option in options) {
if (string.IsNullOrEmpty(option.action) || string.Equals(option.action, parsedAction, ActionComp)) {
if (option.required && !option.wasSet) {
if (option.position >= 0) {
throw new ArgumentsException($"Required argument #{option.position} not set.");
} else {
throw new ArgumentsException($"Required option not set: {GetFirstLongName(option)}");
}
}
}
// Reset wasSet in case Parse is called again
option.wasSet = false;
}
if (!explicitAction && usingDefaultAction != null) {
usingDefaultAction.Invoke(target);
}
// Action callback
ActionDef action;
if (actions.TryGetValue(parsedAction ?? "", out action) && action.callback != null) {
action.callback(target, action.name);
}
}
/// <summary>
/// Write an exception to the console, recursively handling aggregate and inner exceptions.
/// </summary>
/// <param name="e">Exception to print</param>
/// <param name="stackTrace">Print stack trace (never for outer exceptions)</param>
/// <param name="enableColors">Colorize output</param>
public static void WriteException(Exception e, string[] args, bool stackTrace, bool enableColors)
{
var arg = e as ArgumentsException;
if (arg != null) {
WriteArgumentsWithError(args, arg);
return;
}
var agg = e as AggregateException;
if (agg != null) {
if (!stackTrace) {
WriteSingleException(agg.GetBaseException(), stackTrace, enableColors);
} else {
WriteSingleException(e, false, enableColors);
foreach (var inner in agg.InnerExceptions) {
WriteException(inner, args, stackTrace, enableColors);
}
}
return;
}
if (e.InnerException != null) {
WriteSingleException(e, false, enableColors);
WriteException(e.InnerException, args, stackTrace, enableColors);
return;
}
WriteSingleException(e, stackTrace, enableColors);
}
static void WriteSingleException(Exception e, bool stackTrace, bool enableColors)
{
if (enableColors) Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
if (stackTrace) {
if (enableColors) Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(e.StackTrace);
}
Console.ResetColor();
}
// -------- Output --------
/// <summary>
/// Generate help.
/// </summary>
public string Help(string command, string header, string footer, int width = 80)
{
var sb = new StringBuilder();
if (header != null) {
sb.AppendLine(header);
sb.AppendLine();
}
// -- Main Usage
sb.Append("USAGE: ");
sb.Append(command);
sb.Append(" ");
// Global options
var prefix = new string(' ', 8 + command.Length);
var pos = prefix.Length;
pos = OptionUsage(sb, prefix, pos, width, (option) => string.IsNullOrEmpty(option.action));
// Action
if (actions.Count > 0) {
pos = WrappedAppend(sb, prefix, pos, width, "<action> ");
}
// Gloabl positional arguments
pos = ArgumentUsage(sb, prefix, pos, width, (option) => string.IsNullOrEmpty(option.action));
sb.AppendLine();
sb.AppendLine();
// -- Global Options
if (options.Count(o => string.IsNullOrEmpty(o.action)) > 0) {
if (actions.Count > 0) sb.Append("GLOBAL ");
sb.AppendLine("OPTIONS:");
ListOptions(sb, width, (option) => string.IsNullOrEmpty(option.action));
sb.AppendLine();
sb.AppendLine();
}
// -- Actions
if (actions.Count > 0) {
sb.AppendLine($"ACTIONS:\n");
if (defaultAction != null && actions.TryGetValue(defaultAction, out var defaultActionDef)) {
ActionUsage(sb, defaultActionDef, command, width);
}
foreach (var actionDef in actions.Values) {
if (actionDef.name == "" || actionDef.name == defaultAction) continue;
ActionUsage(sb, actionDef, command, width);
}
}
if (footer != null) {
sb.AppendLine();
sb.AppendLine(footer);
}
return sb.ToString();
}
void ActionUsage(StringBuilder sb, ActionDef action, string command, int width)
{
sb.AppendLine($"---- {action.name.ToUpper()}{(defaultAction == action.name ? " (default)" : "")}:");
string prefix;
if (action.description != null) {
prefix = " ";
sb.Append(prefix);
WordWrappedAppend(sb, prefix, prefix.Length, width, action.description);
sb.AppendLine();
}
sb.AppendLine();
// Action Usage
var pos = 0;
pos = Append(sb, pos, "USAGE: ");
pos = Append(sb, pos, command);
pos = Append(sb, pos, " [options] ");
pos = Append(sb, pos, action.name == defaultAction ? $"[{action.name}]" : action.name);
pos = Append(sb, pos, " ");
prefix = new string(' ', 8 + command.Length);
pos = OptionUsage(sb, prefix, pos, width, (option) => string.Equals(option.action, action.name, ActionComp));
pos = ArgumentUsage(sb, prefix, pos, width, (option) => string.Equals(option.action, action.name, ActionComp));
sb.AppendLine();
sb.AppendLine();
// Action options
if (options.Count(option => string.Equals(option.action, action.name, ActionComp)) > 0) {
sb.AppendLine("OPTIONS:");
ListOptions(sb, width, (option) => string.Equals(option.action, action.name, ActionComp));
sb.AppendLine();
}
sb.AppendLine();
}
/// <summary>
/// Helper function that prints options for usage.
/// </summary>
int OptionUsage(StringBuilder sb, string prefix, int pos, int width, Func<OptionDef, bool> filter)
{
foreach (var option in options) {
if (option.position >= 0 || !filter(option)) continue;
var name = GetFirstLongName(option);
name = (name.Length == 1 ? "-" : "--") + name;
if (TakesArgument(option)) name += " " + ArgumentName(option);
if (option.repeatable) name += "...";
if (!option.required) name = "[" + name + "]";
pos = WrappedAppend(sb, prefix, pos, width, name + " ");
}
return pos;
}
/// <summary>
/// Helper function that prints positional arguments for usage.
/// </summary>
int ArgumentUsage(StringBuilder sb, string prefix, int pos, int width, Func<OptionDef, bool> filter)
{
foreach (var option in options) {
if (option.position < 0 || !filter(option)) continue;
var name = ArgumentName(option);
if (option.repeatable) name += "...";
if (!option.required) name = "[" + name + "]";
pos = WrappedAppend(sb, prefix, pos, width, name + " ");
}
return pos;
}
/// <summary>
/// Helper function that prints option list.
/// </summary>
void ListOptions(StringBuilder sb, int width, Func<OptionDef, bool> filter)
{
var descIndent = 18;
var pos = 0;
var wrapPrefix = new string(' ', descIndent);
foreach (var option in options) {
if (!filter(option)) continue;
if (option.position < 0) {
var longName = GetFirstLongName(option, shortFallback: false);
if (option.names.Length > 0 && option.names[0].Length == 1) {
pos = Append(sb, pos, " -");
pos = Append(sb, pos, option.names[0]);
if (longName != null) {
pos = Append(sb, pos, ", ");
} else {
pos = Append(sb, pos, " ");
}
} else {
pos = Append(sb, pos, " ");
}
if (longName != null && longName.Length > 1) {
pos = Append(sb, pos, "--");
pos = Append(sb, pos, longName);
pos = Append(sb, pos, " ");
}
if (TakesArgument(option)) {
pos = Append(sb, pos, ArgumentName(option));
pos = Append(sb, pos, " ");
}
} else {
pos = Append(sb, pos, " ");
pos = Append(sb, pos, ArgumentName(option));
}
pos = Append(sb, pos, " ");
if (option.description != null) {
pos = Append(sb, pos, new string(' ', Math.Max(descIndent - pos, 0)));
pos = WordWrappedAppend(sb, wrapPrefix, pos, width, option.description);
sb.AppendLine();
pos = 0;
}
}
}
/// <summary>
/// Append to a string builder while tracking position.
/// </summary>
int Append(StringBuilder sb, int pos, string append)
{
sb.Append(append);
return pos + append.Length;
}
/// <summary>
/// Try to fit string into width or wrap it on a new line.
/// </summary>
int WrappedAppend(StringBuilder sb, string prefix, int pos, int width, string append)
{
pos += append.Length;
if (pos > width) {
sb.AppendLine();
sb.Append(prefix);
pos = prefix.Length + append.Length;
}
sb.Append(append);
return pos;
}
/// <summary>
/// Like WrappedAppend, but does it for each word individually.
/// </summary>
int WordWrappedAppend(StringBuilder sb, string prefix, int pos, int width, string append)
{
var words = append.Split(' ');
foreach (var word in words) {
pos = WrappedAppend(sb, prefix, pos, width, word + " ");
}
return pos;
}
/// <summary>
/// Write a parse error to the console together with the used arguments, indicating where
/// the error happened (if applicable).
/// </summary>
/// <param name="args">Arguments that were parsed</param>
/// <param name="ex">Exception thrown during parsing</param>
public static void WriteArgumentsWithError(string[] args, ArgumentsException ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Gray;
var cmdName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
Console.Write("$ ");
Console.Write(cmdName);
Console.Write(" ");
var offset = cmdName.Length + 3;
var originalFgColor = Console.ForegroundColor;
for (int i = 0; i < args.Length; i++) {
if (i > 0) Console.Write(" ");
if (ex.ArgumentIndex == i) {
Console.ForegroundColor = ConsoleColor.Red;
}
Console.Write(EscapeArgument(args[i]));
if (ex.ArgumentIndex == i) {
Console.ForegroundColor = originalFgColor;
}
if (ex.ArgumentIndex > i) {
offset += args[i].Length + 1;
}
}
Console.ResetColor();
Console.WriteLine();
if (ex.ArgumentIndex > 0) {
Console.Write(new string(' ', offset));
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(new string('^', args[ex.ArgumentIndex].Length));
Console.ResetColor();
}
}
static char[] NeedQuotesChars = new [] { ' ', '\t', '\n' };
/// <summary>
/// Escape a command line argument.
/// </summary>
/// <remarks>
/// Based on work from Nate McMaster, Licensed under the Apache License, Version 2.0.
/// In turn based on this MSDN blog post:
/// https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
/// </remarks>
public static string EscapeArgument(string arg)
{
var sb = new StringBuilder();
var needsQuotes = arg.IndexOfAny(NeedQuotesChars) >= 0;
var isQuoted = needsQuotes || (arg.Length > 1 && arg[0] == '"' && arg[arg.Length - 1] == '"');
if (needsQuotes) {
sb.Append('"');
}
for (int i = 0; i < arg.Length; ++i) {
var backslashes = 0;
// Consume all backslashes
while (i < arg.Length && arg[i] == '\\') {
backslashes++;
i++;
}
if (i == arg.Length && isQuoted) {
// Escape any backslashes at the end of the arg when the argument is also quoted.
// This ensures the outside quote is interpreted as an argument delimiter
sb.Append('\\', 2 * backslashes);
} else if (i == arg.Length) {
// At then end of the arg, which isn't quoted,
// just add the backslashes, no need to escape
sb.Append('\\', backslashes);
} else if (arg[i] == '"') {
// Escape any preceding backslashes and the quote
sb.Append('\\', (2 * backslashes) + 1);
sb.Append('"');
} else {
// Output any consumed backslashes and the character
sb.Append('\\', backslashes);
sb.Append(arg[i]);
}
}
if (needsQuotes) {
sb.Append('"');
}
return sb.ToString();
}
// -------- Internals --------
/// <summary>
/// Base option definition.
/// </summary>
class OptionDef
{
/// <summary>
/// The action the option belongs to.
/// </summary>
public string action;
/// <summary>
/// The names (aliases) of the option (without prefix).
/// </summary>
public string[] names;
/// <summary>
/// The position of positional options or -1.
/// </summary>
public int position;
/// <summary>
/// Wether the option is repeatable.
/// </summary>
public bool repeatable;
/// <summary>
/// Wether the option is required.
/// </summary>
public bool required;
/// <summary>
/// Wether the option's argument is required.
/// </summary>
public bool requiresArgument;
/// <summary>
/// Name of argument(s), used in help.
/// </summary>
public string argumentName;
/// <summary>
/// Description shown in help.
/// </summary>
public string description;
/// <summary>
/// Used to track missing required arguments.
/// </summary>
public bool wasSet;
}
/// <summary>
/// Generic option definition subclass that contains the typed callback.
/// </summary>
class OptionDef<TArg> : OptionDef
{
public Action<T, TArg> setter;
}
/// <summary>
/// Action definition.
/// </summary>
class ActionDef
{
/// <summary>
/// Name of the action.
/// </summary>
public string name;
/// <summary>
/// Description shown in help.
/// </summary>
public string description;
/// <summary>
/// Called when action has been selected.
/// </summary>
public Action<T, string> callback;
}
static StringComparison ActionComp = StringComparison.OrdinalIgnoreCase;
ActionDef definedAction;
OptionDef definedOption;
Dictionary<string, ActionDef> actions = new Dictionary<string, ActionDef>(StringComparer.OrdinalIgnoreCase);
string defaultAction;
Action<T> usingDefaultAction;
List<OptionDef> options = new List<OptionDef>();
string parsedAction;
/// <summary>
/// Add an option definition
/// </summary>
void AddOption(Type t, OptionDef option)
{
if (option.position >= 0) {
if (FindOption(definedAction?.name, option.position) != null) {
throw new Exception($"Argument #{option.position} already defined.");
}
} else {
foreach (var name in option.names) {
if (FindOption(definedAction?.name, name, null) != null) {
throw new Exception($"Argument named '{name}' already defined.");
}
}
}
options.Add(option);
definedOption = option;
}
/// <summary>
/// Check wether an argument starts with an option prefix.
/// </summary>
bool IsOption(string arg)
{
if (arg.StartsWith("/")) {
return FindOption(parsedAction, GetName(arg.Substring(1)), null) != null;
}
return arg.StartsWith("-");
}
/// <summary>
/// Return an option's first long name or the first short name if it has no long names.
/// </summary>
string GetFirstLongName(OptionDef option, bool shortFallback = true)
{
if (option.names == null || option.names.Length == 0) return null;
foreach (var name in option.names) {
if (name.Length > 1) return name;
}
return shortFallback ? option.names[0] : null;
}
/// <summary>
/// Return wether an option takes an argument.
/// </summary>
bool TakesArgument(OptionDef option)
{
return (option is OptionDef<string> || option is OptionDef<IList<string>>);
}
/// <summary>
/// Return name to use for argument.
/// </summary>
string ArgumentName(OptionDef option)
{
return option.argumentName ?? "<arg>";
}
/// <summary>
/// Parse the name out of an option with a combined argument, e.g. opt=value or opt:value.
/// </summary>
string GetName(string arg)
{
var index = arg.IndexOf('=');
if (index > 0) {
return arg.Substring(0, index);
}
index = arg.IndexOf(':');
if (index > 0) {
return arg.Substring(0, index);
}
return arg;
}
/// <summary>
/// Parse the argument out of an option with a combined argument, e.g. opt=value or opt:value.
/// </summary>
string GetValue(string arg)
{
var index = arg.IndexOf('=');
if (index > 0) {
return arg.Substring(index + 1);
}
index = arg.IndexOf(':');
if (index > 0) {
return arg.Substring(index + 1);
}
return null;
}
/// <summary>
/// Search for an option by name.
/// </summary>
/// <param name="action">Limit seach to this action (global options are always returned)</param>
/// <param name="name">Name to search for</param>
/// <param name="shortOption">Wether to search for short or long options or for both</param>
OptionDef FindOption(string action, string name, bool? shortOption)
{
foreach (var option in options) {
if (option.names == null || (!string.IsNullOrEmpty(option.action) && !string.Equals(option.action, action, ActionComp))) continue;
foreach (var candidate in option.names) {
if (shortOption == (candidate.Length != 1)) continue;
if (string.Equals(name, candidate, ActionComp)) {
return option;
}
}
}
return null;
}
/// <summary>
/// Search for a positional argument.
/// </summary>
/// <param name="action">Limit seach to this action (global arguments are always returned)</param>
/// <param name="position">The position to search for</param>
OptionDef FindOption(string action, int position)
{
if (position < 0) throw new ArgumentException($"Argument cannot be < 0", nameof(position));
foreach (var option in options) {
if (option.position < 0) continue;
if (!string.IsNullOrEmpty(option.action) && !string.Equals(option.action, action, ActionComp)) continue;
if (option.position == position || (option.repeatable && position >= option.position)) {
return option;
}
}
return null;
}