-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy pathHelpText.cs
1135 lines (976 loc) · 48 KB
/
HelpText.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
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.
using CommandLine.Core;
using CommandLine.Infrastructure;
using CSharpx;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CommandLine.Text
{
/// <summary>
/// Provides means to format an help screen.
/// You can assign it in place of a <see cref="System.String"/> instance.
/// </summary>
public struct ComparableOption
{
public bool Required;
public bool IsOption;
public bool IsValue;
public string LongName;
public string ShortName;
public int Index;
}
public class HelpText
{
#region ordering
ComparableOption ToComparableOption(Specification spec, int index)
{
OptionSpecification option = spec as OptionSpecification;
ValueSpecification value = spec as ValueSpecification;
bool required = option?.Required ?? false;
return new ComparableOption()
{
Required = required,
IsOption = option != null,
IsValue = value != null,
LongName = option?.LongName ?? value?.MetaName,
ShortName = option?.ShortName,
Index = index
};
}
public Comparison<ComparableOption> OptionComparison { get; set; } = null;
public static Comparison<ComparableOption> RequiredThenAlphaComparison = (ComparableOption attr1, ComparableOption attr2) =>
{
if (attr1.IsOption && attr2.IsOption)
{
if (attr1.Required && !attr2.Required)
{
return -1;
}
else if (!attr1.Required && attr2.Required)
{
return 1;
}
return String.Compare(attr1.LongName, attr2.LongName, StringComparison.Ordinal);
}
else if (attr1.IsOption && attr2.IsValue)
{
return -1;
}
else
{
return 1;
}
};
#endregion
private const int BuilderCapacity = 128;
private const int DefaultMaximumLength = 80; // default console width
/// <summary>
/// The number of spaces between an option and its associated help text
/// </summary>
private const int OptionToHelpTextSeparatorWidth = 4;
/// <summary>
/// The width of the option prefix (either "--" or " "
/// </summary>
private const int OptionPrefixWidth = 2;
/// <summary>
/// The total amount of extra space that needs to accounted for when indenting Option help text
/// </summary>
private const int TotalOptionPadding = OptionToHelpTextSeparatorWidth + OptionPrefixWidth;
private readonly StringBuilder preOptionsHelp;
private readonly StringBuilder postOptionsHelp;
private readonly SentenceBuilder sentenceBuilder;
private int maximumDisplayWidth;
private string heading;
private string copyright;
private bool additionalNewLineAfterOption;
private StringBuilder optionsHelp;
private bool addDashesToOption;
private bool addEnumValuesToHelpText;
private bool autoHelp;
private bool autoVersion;
private bool addNewLineBetweenHelpSections;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class.
/// </summary>
public HelpText()
: this(SentenceBuilder.Create(), string.Empty, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying the sentence builder.
/// </summary>
/// <param name="sentenceBuilder">
/// A <see cref="SentenceBuilder"/> instance.
/// </param>
public HelpText(SentenceBuilder sentenceBuilder)
: this(sentenceBuilder, string.Empty, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading string.
/// </summary>
/// <param name="heading">An heading string or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="heading"/> is null or empty string.</exception>
public HelpText(string heading)
: this(SentenceBuilder.Create(), heading, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying the sentence builder and heading string.
/// </summary>
/// <param name="sentenceBuilder">A <see cref="SentenceBuilder"/> instance.</param>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
public HelpText(SentenceBuilder sentenceBuilder, string heading)
: this(sentenceBuilder, heading, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright strings.
/// </summary>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright or an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <exception cref="System.ArgumentNullException">Thrown when one or more parameters are null or empty strings.</exception>
public HelpText(string heading, string copyright)
: this(SentenceBuilder.Create(), heading, copyright)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright strings.
/// </summary>
/// <param name="sentenceBuilder">A <see cref="SentenceBuilder"/> instance.</param>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright or an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <exception cref="System.ArgumentNullException">Thrown when one or more parameters are null or empty strings.</exception>
public HelpText(SentenceBuilder sentenceBuilder, string heading, string copyright)
{
if (sentenceBuilder == null) throw new ArgumentNullException("sentenceBuilder");
if (heading == null) throw new ArgumentNullException("heading");
if (copyright == null) throw new ArgumentNullException("copyright");
preOptionsHelp = new StringBuilder(BuilderCapacity);
postOptionsHelp = new StringBuilder(BuilderCapacity);
try
{
maximumDisplayWidth = Console.WindowWidth;
if (maximumDisplayWidth < 1)
{
maximumDisplayWidth = DefaultMaximumLength;
}
}
catch (IOException)
{
maximumDisplayWidth = DefaultMaximumLength;
}
this.sentenceBuilder = sentenceBuilder;
this.heading = heading;
this.copyright = copyright;
this.autoHelp = true;
this.autoVersion = true;
}
/// <summary>
/// Gets or sets the heading string.
/// You can directly assign a <see cref="CommandLine.Text.HeadingInfo"/> instance.
/// </summary>
public string Heading
{
get { return heading; }
set
{
if (value == null) throw new ArgumentNullException("value");
heading = value;
}
}
/// <summary>
/// Gets or sets the copyright string.
/// You can directly assign a <see cref="CommandLine.Text.CopyrightInfo"/> instance.
/// </summary>
public string Copyright
{
get { return copyright; }
set
{
if (value == null) throw new ArgumentNullException("value");
copyright = value;
}
}
/// <summary>
/// Gets or sets the maximum width of the display. This determines word wrap when displaying the text.
/// </summary>
/// <value>The maximum width of the display.</value>
public int MaximumDisplayWidth
{
get { return maximumDisplayWidth; }
set { maximumDisplayWidth = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the format of options should contain dashes.
/// It modifies behavior of <see cref="AddOptions{T}(ParserResult{T})"/> method.
/// </summary>
public bool AddDashesToOption
{
get { return addDashesToOption; }
set { addDashesToOption = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to add an additional line after the description of the specification.
/// </summary>
public bool AdditionalNewLineAfterOption
{
get { return additionalNewLineAfterOption; }
set { additionalNewLineAfterOption = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to add newlines between help sections.
/// </summary>
public bool AddNewLineBetweenHelpSections
{
get { return addNewLineBetweenHelpSections; }
set { addNewLineBetweenHelpSections = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to add the values of an enum after the description of the specification.
/// </summary>
public bool AddEnumValuesToHelpText
{
get { return addEnumValuesToHelpText; }
set { addEnumValuesToHelpText = value; }
}
/// <summary>
/// Gets or sets a value indicating whether implicit option or verb 'help' should be supported.
/// </summary>
public bool AutoHelp
{
get { return autoHelp; }
set { autoHelp = value; }
}
/// <summary>
/// Gets or sets a value indicating whether implicit option or verb 'version' should be supported.
/// </summary>
public bool AutoVersion
{
get { return autoVersion; }
set { autoVersion = value; }
}
/// <summary>
/// Gets the <see cref="SentenceBuilder"/> instance specified in constructor.
/// </summary>
public SentenceBuilder SentenceBuilder
{
get { return sentenceBuilder; }
}
/// <summary>
/// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults.
/// </summary>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
/// <param name='onError'>A delegate used to customize the text block of reporting parsing errors text block.</param>
/// <param name='onExample'>A delegate used to customize <see cref="CommandLine.Text.Example"/> model used to render text block of usage examples.</param>
/// <param name="verbsIndex">If true the output style is consistent with verb commands (no dashes), otherwise it outputs options.</param>
/// <param name="maxDisplayWidth">The maximum width of the display.</param>
/// <remarks>The parameter <paramref name="verbsIndex"/> is not ontly a metter of formatting, it controls whether to handle verbs or options.</remarks>
public static HelpText AutoBuild<T>(
ParserResult<T> parserResult,
Func<HelpText, HelpText> onError,
Func<Example, Example> onExample,
bool verbsIndex = false,
int maxDisplayWidth = DefaultMaximumLength)
{
var auto = new HelpText
{
Heading = HeadingInfo.Empty,
Copyright = CopyrightInfo.Empty,
AdditionalNewLineAfterOption = true,
AddDashesToOption = !verbsIndex,
MaximumDisplayWidth = maxDisplayWidth
};
try
{
auto.Heading = HeadingInfo.Default;
auto.Copyright = CopyrightInfo.Default;
}
catch (Exception)
{
auto = onError(auto);
}
var errors = Enumerable.Empty<Error>();
if (onError != null && parserResult.Tag == ParserResultType.NotParsed)
{
errors = ((NotParsed<T>)parserResult).Errors;
if (errors.IsHelp() || errors.OnlyMeaningfulOnes().Any())
auto = onError(auto);
}
ReflectionHelper.GetAttribute<AssemblyLicenseAttribute>()
.Do(license => license.AddToHelpText(auto, true));
var usageAttr = ReflectionHelper.GetAttribute<AssemblyUsageAttribute>();
var usageLines = HelpText.RenderUsageTextAsLines(parserResult, onExample).ToMaybe();
if (usageAttr.IsJust() || usageLines.IsJust())
{
var heading = auto.SentenceBuilder.UsageHeadingText();
if (heading.Length > 0)
{
if (auto.AddNewLineBetweenHelpSections)
heading = Environment.NewLine + heading;
auto.AddPreOptionsLine(heading);
}
}
usageAttr.Do(
usage => usage.AddToHelpText(auto, true));
usageLines.Do(
lines => auto.AddPreOptionsLines(lines));
if ((verbsIndex && parserResult.TypeInfo.Choices.Any())
|| errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
{
auto.AddDashesToOption = false;
auto.AddVerbs(parserResult.TypeInfo.Choices.ToArray());
}
else
auto.AddOptions(parserResult);
return auto;
}
/// <summary>
/// Creates a default instance of the <see cref="CommandLine.Text.HelpText"/> class,
/// automatically handling verbs or options scenario.
/// </summary>
/// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
/// <param name="maxDisplayWidth">The maximum width of the display.</param>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <remarks>This feature is meant to be invoked automatically by the parser, setting the HelpWriter property
/// of <see cref="CommandLine.ParserSettings"/>.</remarks>
public static HelpText AutoBuild<T>(ParserResult<T> parserResult, int maxDisplayWidth = DefaultMaximumLength)
{
return AutoBuild<T>(parserResult, h => h, maxDisplayWidth);
}
/// <summary>
/// Creates a custom instance of the <see cref="CommandLine.Text.HelpText"/> class,
/// automatically handling verbs or options scenario.
/// </summary>
/// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
/// <param name='onError'>A delegate used to customize the text block of reporting parsing errors text block.</param>
/// <param name="maxDisplayWidth">The maximum width of the display.</param>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <remarks>This feature is meant to be invoked automatically by the parser, setting the HelpWriter property
/// of <see cref="CommandLine.ParserSettings"/>.</remarks>
public static HelpText AutoBuild<T>(ParserResult<T> parserResult, Func<HelpText, HelpText> onError, int maxDisplayWidth = DefaultMaximumLength)
{
if (parserResult.Tag != ParserResultType.NotParsed)
throw new ArgumentException("Excepting NotParsed<T> type.", "parserResult");
var errors = ((NotParsed<T>)parserResult).Errors;
if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
return new HelpText($"{HeadingInfo.Default}{Environment.NewLine}") { MaximumDisplayWidth = maxDisplayWidth }.AddPreOptionsLine(Environment.NewLine);
if (!errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
return AutoBuild(parserResult, current =>
{
onError?.Invoke(current);
return DefaultParsingErrorsHandler(parserResult, current);
}, e => e, maxDisplayWidth: maxDisplayWidth);
var err = errors.OfType<HelpVerbRequestedError>().Single();
var pr = new NotParsed<object>(TypeInfo.Create(err.Type), new Error[] { err });
return err.Matched
? AutoBuild(pr, current =>
{
onError?.Invoke(current);
return DefaultParsingErrorsHandler(pr, current);
}, e => e, maxDisplayWidth: maxDisplayWidth)
: AutoBuild(parserResult, current =>
{
onError?.Invoke(current);
return DefaultParsingErrorsHandler(parserResult, current);
}, e => e, true, maxDisplayWidth);
}
/// <summary>
/// Supplies a default parsing error handler implementation.
/// </summary>
/// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
/// <param name="current">The <see cref="CommandLine.Text.HelpText"/> instance.</param>
public static HelpText DefaultParsingErrorsHandler<T>(ParserResult<T> parserResult, HelpText current)
{
if (parserResult == null) throw new ArgumentNullException("parserResult");
if (current == null) throw new ArgumentNullException("current");
if (((NotParsed<T>)parserResult).Errors.OnlyMeaningfulOnes().Empty())
return current;
var errors = RenderParsingErrorsTextAsLines(parserResult,
current.SentenceBuilder.FormatError,
current.SentenceBuilder.FormatMutuallyExclusiveSetErrors,
2); // indent with two spaces
if (errors.Empty())
return current;
return current
.AddPreOptionsLine(
string.Concat(Environment.NewLine, current.SentenceBuilder.ErrorsHeadingText()))
.AddPreOptionsLines(errors);
}
/// <summary>
/// Converts the help instance to a <see cref="System.String"/>.
/// </summary>
/// <param name="info">This <see cref="CommandLine.Text.HelpText"/> instance.</param>
/// <returns>The <see cref="System.String"/> that contains the help screen.</returns>
public static implicit operator string(HelpText info)
{
return info.ToString();
}
/// <summary>
/// Adds a text line after copyright and before options usage strings.
/// </summary>
/// <param name="value">A <see cref="System.String"/> instance.</param>
/// <returns>Updated <see cref="CommandLine.Text.HelpText"/> instance.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception>
public HelpText AddPreOptionsLine(string value)
{
return AddPreOptionsLine(value, MaximumDisplayWidth);
}
/// <summary>
/// Adds a text line at the bottom, after options usage string.
/// </summary>
/// <param name="value">A <see cref="System.String"/> instance.</param>
/// <returns>Updated <see cref="CommandLine.Text.HelpText"/> instance.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception>
public HelpText AddPostOptionsLine(string value)
{
return AddLine(postOptionsHelp, value);
}
/// <summary>
/// Adds text lines after copyright and before options usage strings.
/// </summary>
/// <param name="lines">A <see cref="System.String"/> sequence of line to add.</param>
/// <returns>Updated <see cref="CommandLine.Text.HelpText"/> instance.</returns>
public HelpText AddPreOptionsLines(IEnumerable<string> lines)
{
lines.ForEach(line => AddPreOptionsLine(line));
return this;
}
/// <summary>
/// Adds text lines at the bottom, after options usage string.
/// </summary>
/// <param name="lines">A <see cref="System.String"/> sequence of line to add.</param>
/// <returns>Updated <see cref="CommandLine.Text.HelpText"/> instance.</returns>
public HelpText AddPostOptionsLines(IEnumerable<string> lines)
{
lines.ForEach(line => AddPostOptionsLine(line));
return this;
}
/// <summary>
/// Adds a text block of lines after copyright and before options usage strings.
/// </summary>
/// <param name="text">A <see cref="System.String"/> text block.</param>
/// <returns>Updated <see cref="CommandLine.Text.HelpText"/> instance.</returns>
public HelpText AddPreOptionsText(string text)
{
var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
lines.ForEach(line => AddPreOptionsLine(line));
return this;
}
/// <summary>
/// Adds a text block of lines at the bottom, after options usage string.
/// </summary>
/// <param name="text">A <see cref="System.String"/> text block.</param>
/// <returns>Updated <see cref="CommandLine.Text.HelpText"/> instance.</returns>
public HelpText AddPostOptionsText(string text)
{
var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
lines.ForEach(line => AddPostOptionsLine(line));
return this;
}
/// <summary>
/// Adds a text block with options usage string.
/// </summary>
/// <param name="result">A parsing computation result.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="result"/> is null.</exception>
public HelpText AddOptions<T>(ParserResult<T> result)
{
if (result == null) throw new ArgumentNullException("result");
return AddOptionsImpl(
GetSpecificationsFromType(result.TypeInfo.Current),
SentenceBuilder.RequiredWord(),
SentenceBuilder.OptionGroupWord(),
MaximumDisplayWidth);
}
/// <summary>
/// Adds a text block with verbs usage string.
/// </summary>
/// <param name="types">The array of <see cref="System.Type"/> with verb commands.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="types"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="types"/> array is empty.</exception>
public HelpText AddVerbs(params Type[] types)
{
if (types == null) throw new ArgumentNullException("types");
if (types.Length == 0) throw new ArgumentOutOfRangeException("types");
return AddOptionsImpl(
AdaptVerbsToSpecifications(types),
SentenceBuilder.RequiredWord(),
SentenceBuilder.OptionGroupWord(),
MaximumDisplayWidth);
}
/// <summary>
/// Adds a text block with options usage string.
/// </summary>
/// <param name="maximumLength">The maximum length of the help screen.</param>
/// <param name="result">A parsing computation result.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="result"/> is null.</exception>
public HelpText AddOptions<T>(int maximumLength, ParserResult<T> result)
{
if (result == null) throw new ArgumentNullException("result");
return AddOptionsImpl(
GetSpecificationsFromType(result.TypeInfo.Current),
SentenceBuilder.RequiredWord(),
SentenceBuilder.OptionGroupWord(),
maximumLength);
}
/// <summary>
/// Adds a text block with verbs usage string.
/// </summary>
/// <param name="maximumLength">The maximum length of the help screen.</param>
/// <param name="types">The array of <see cref="System.Type"/> with verb commands.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="types"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="types"/> array is empty.</exception>
public HelpText AddVerbs(int maximumLength, params Type[] types)
{
if (types == null) throw new ArgumentNullException("types");
if (types.Length == 0) throw new ArgumentOutOfRangeException("types");
return AddOptionsImpl(
AdaptVerbsToSpecifications(types),
SentenceBuilder.RequiredWord(),
SentenceBuilder.OptionGroupWord(),
maximumLength);
}
/// <summary>
/// Builds a string that contains a parsing error message.
/// </summary>
/// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
/// <param name="formatError">The error formatting delegate.</param>
/// <param name="formatMutuallyExclusiveSetErrors">The specialized <see cref="CommandLine.MutuallyExclusiveSetError"/> sequence formatting delegate.</param>
/// <param name="indent">Number of spaces used to indent text.</param>
/// <returns>The <see cref="System.String"/> that contains the parsing error message.</returns>
public static string RenderParsingErrorsText<T>(
ParserResult<T> parserResult,
Func<Error, string> formatError,
Func<IEnumerable<MutuallyExclusiveSetError>, string> formatMutuallyExclusiveSetErrors,
int indent)
{
return string.Join(
Environment.NewLine,
RenderParsingErrorsTextAsLines(parserResult, formatError, formatMutuallyExclusiveSetErrors, indent));
}
/// <summary>
/// Builds a sequence of string that contains a parsing error message.
/// </summary>
/// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
/// <param name="formatError">The error formatting delegate.</param>
/// <param name="formatMutuallyExclusiveSetErrors">The specialized <see cref="CommandLine.MutuallyExclusiveSetError"/> sequence formatting delegate.</param>
/// <param name="indent">Number of spaces used to indent text.</param>
/// <returns>A sequence of <see cref="System.String"/> that contains the parsing error message.</returns>
public static IEnumerable<string> RenderParsingErrorsTextAsLines<T>(
ParserResult<T> parserResult,
Func<Error, string> formatError,
Func<IEnumerable<MutuallyExclusiveSetError>, string> formatMutuallyExclusiveSetErrors,
int indent)
{
if (parserResult == null) throw new ArgumentNullException("parserResult");
var meaningfulErrors =
((NotParsed<T>)parserResult).Errors.OnlyMeaningfulOnes();
if (meaningfulErrors.Empty())
yield break;
foreach (var error in meaningfulErrors
.Where(e => e.Tag != ErrorType.MutuallyExclusiveSetError))
{
var line = new StringBuilder(indent.Spaces())
.Append(formatError(error));
yield return line.ToString();
}
var mutuallyErrs =
formatMutuallyExclusiveSetErrors(
meaningfulErrors.OfType<MutuallyExclusiveSetError>());
if (mutuallyErrs.Length > 0)
{
var lines = mutuallyErrs
.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach (var line in lines)
yield return line;
}
}
/// <summary>
/// Builds a string with usage text block created using <see cref="CommandLine.Text.UsageAttribute"/> data and metadata.
/// </summary>
/// <typeparam name="T">Type of parsing computation result.</typeparam>
/// <param name="parserResult">A parsing computation result.</param>
/// <returns>Resulting formatted text.</returns>
public static string RenderUsageText<T>(ParserResult<T> parserResult)
{
return RenderUsageText(parserResult, example => example);
}
/// <summary>
/// Builds a string with usage text block created using <see cref="CommandLine.Text.UsageAttribute"/> data and metadata.
/// </summary>
/// <typeparam name="T">Type of parsing computation result.</typeparam>
/// <param name="parserResult">A parsing computation result.</param>
/// <param name="mapperFunc">A mapping lambda normally used to translate text in other languages.</param>
/// <returns>Resulting formatted text.</returns>
public static string RenderUsageText<T>(ParserResult<T> parserResult, Func<Example, Example> mapperFunc)
{
return string.Join(Environment.NewLine, RenderUsageTextAsLines(parserResult, mapperFunc));
}
/// <summary>
/// Builds a string sequence with usage text block created using <see cref="CommandLine.Text.UsageAttribute"/> data and metadata.
/// </summary>
/// <typeparam name="T">Type of parsing computation result.</typeparam>
/// <param name="parserResult">A parsing computation result.</param>
/// <param name="mapperFunc">A mapping lambda normally used to translate text in other languages.</param>
/// <returns>Resulting formatted text.</returns>
public static IEnumerable<string> RenderUsageTextAsLines<T>(ParserResult<T> parserResult, Func<Example, Example> mapperFunc)
{
if (parserResult == null) throw new ArgumentNullException("parserResult");
var usage = GetUsageFromType(parserResult.TypeInfo.Current);
if (usage.MatchNothing())
yield break;
var usageTuple = usage.FromJustOrFail();
var examples = usageTuple.Item2;
var appAlias = usageTuple.Item1.ApplicationAlias ?? ReflectionHelper.GetAssemblyName();
foreach (var e in examples)
{
var example = mapperFunc(e);
var exampleText = new StringBuilder(example.HelpText)
.Append(':');
yield return exampleText.ToString();
var styles = example.GetFormatStylesOrDefault();
foreach (var s in styles)
{
var commandLine = new StringBuilder(OptionPrefixWidth.Spaces())
.Append(appAlias)
.Append(' ')
.Append(Parser.Default.FormatCommandLine(example.Sample,
config =>
{
config.PreferShortName = s.PreferShortName;
config.GroupSwitches = s.GroupSwitches;
config.UseEqualToken = s.UseEqualToken;
config.SkipDefault = s.SkipDefault;
}));
yield return commandLine.ToString();
}
}
}
/// <summary>
/// Returns the help screen as a <see cref="System.String"/>.
/// </summary>
/// <returns>The <see cref="System.String"/> that contains the help screen.</returns>
public override string ToString()
{
const int ExtraLength = 10;
var sbLength = heading.SafeLength() + copyright.SafeLength() + preOptionsHelp.SafeLength()
+ optionsHelp.SafeLength() + postOptionsHelp.SafeLength() + ExtraLength;
var result = new StringBuilder(sbLength);
result.Append(heading)
.AppendWhen(!string.IsNullOrEmpty(copyright),
Environment.NewLine,
copyright)
.AppendWhen(preOptionsHelp.SafeLength() > 0,
NewLineIfNeededBefore(preOptionsHelp),
Environment.NewLine,
preOptionsHelp.ToString())
.AppendWhen(optionsHelp.SafeLength() > 0,
Environment.NewLine,
Environment.NewLine,
optionsHelp.SafeToString())
.AppendWhen(postOptionsHelp.SafeLength() > 0,
NewLineIfNeededBefore(postOptionsHelp),
Environment.NewLine,
postOptionsHelp.ToString());
string NewLineIfNeededBefore(StringBuilder sb)
{
if (AddNewLineBetweenHelpSections
&& result.Length > 0
&& !result.SafeEndsWith(Environment.NewLine)
&& !sb.SafeStartsWith(Environment.NewLine))
return Environment.NewLine;
else
return null;
}
return result.ToString();
}
internal static void AddLine(StringBuilder builder, string value, int maximumLength)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (maximumLength < 1)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
value = value.TrimEnd();
builder.AppendWhen(builder.Length > 0, Environment.NewLine);
builder.Append(TextWrapper.WrapAndIndentText(value, 0, maximumLength));
}
private IEnumerable<Specification> GetSpecificationsFromType(Type type)
{
var specs = type.GetSpecifications(Specification.FromProperty);
var optionSpecs = specs
.OfType<OptionSpecification>();
if (autoHelp)
optionSpecs = optionSpecs.Concat(new[] { MakeHelpEntry() });
if (autoVersion)
optionSpecs = optionSpecs.Concat(new[] { MakeVersionEntry() });
var valueSpecs = specs
.OfType<ValueSpecification>()
.OrderBy(v => v.Index);
return Enumerable.Empty<Specification>()
.Concat(optionSpecs)
.Concat(valueSpecs);
}
private static Maybe<Tuple<UsageAttribute, IEnumerable<Example>>> GetUsageFromType(Type type)
{
return type.GetUsageData().Map(
tuple =>
{
var prop = tuple.Item1;
var attr = tuple.Item2;
var examples = (IEnumerable<Example>)prop
.GetValue(null, BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty, null, null, null);
return Tuple.Create(attr, examples);
});
}
private IEnumerable<Specification> AdaptVerbsToSpecifications(IEnumerable<Type> types)
{
var optionSpecs = from verbTuple in Verb.SelectFromTypes(types)
select
OptionSpecification.NewSwitch(
string.Empty,
verbTuple.Item1.Name.Concat(verbTuple.Item1.Aliases).ToDelimitedString(", "),
false,
verbTuple.Item1.IsDefault ? "(Default Verb) " + verbTuple.Item1.HelpText : verbTuple.Item1.HelpText, //Default verb
string.Empty,
verbTuple.Item1.Hidden);
if (autoHelp)
optionSpecs = optionSpecs.Concat(new[] { MakeHelpEntry() });
if (autoVersion)
optionSpecs = optionSpecs.Concat(new[] { MakeVersionEntry() });
return optionSpecs;
}
private HelpText AddOptionsImpl(
IEnumerable<Specification> specifications,
string requiredWord,
string optionGroupWord,
int maximumLength)
{
var maxLength = GetMaxLength(specifications);
optionsHelp = new StringBuilder(BuilderCapacity);
var remainingSpace = maximumLength - (maxLength + TotalOptionPadding);
if (OptionComparison != null)
{
int i = -1;
var comparables = specifications.ToList().Select(s =>
{
i++;
return ToComparableOption(s, i);
}).ToList();
comparables.Sort(OptionComparison);
foreach (var comparable in comparables)
{
Specification spec = specifications.ElementAt(comparable.Index);
AddOption(requiredWord, optionGroupWord, maxLength, spec, remainingSpace);
}
}
else
{
specifications.ForEach(
option =>
AddOption(requiredWord, optionGroupWord, maxLength, option, remainingSpace));
}
return this;
}
private OptionSpecification MakeHelpEntry()
{
return OptionSpecification.NewSwitch(
string.Empty,
"help",
false,
sentenceBuilder.HelpCommandText(AddDashesToOption),
string.Empty,
false);
}
private OptionSpecification MakeVersionEntry()
{
return OptionSpecification.NewSwitch(
string.Empty,
"version",
false,
sentenceBuilder.VersionCommandText(AddDashesToOption),
string.Empty,
false);
}
private HelpText AddPreOptionsLine(string value, int maximumLength)
{
AddLine(preOptionsHelp, value, maximumLength);
return this;
}
private HelpText AddOption(string requiredWord, string optionGroupWord, int maxLength, Specification specification, int widthOfHelpText)
{
OptionSpecification GetOptionGroupSpecification()
{
if (specification.Tag == SpecificationType.Option &&
specification is OptionSpecification optionSpecification &&
optionSpecification.Group.Length > 0
)
{
return optionSpecification;
}
return null;
}
if (specification.Hidden)
return this;
optionsHelp.Append(" ");
var name = new StringBuilder(maxLength)
.BimapIf(
specification.Tag == SpecificationType.Option,
it => it.Append(AddOptionName(maxLength, (OptionSpecification)specification)),
it => it.Append(AddValueName(maxLength, (ValueSpecification)specification)));
optionsHelp
.Append(name.Length < maxLength ? name.ToString().PadRight(maxLength) : name.ToString())
.Append(OptionToHelpTextSeparatorWidth.Spaces());
var optionHelpText = specification.HelpText;
if (addEnumValuesToHelpText && specification.EnumValues.Any())
optionHelpText += " Valid values: " + string.Join(", ", specification.EnumValues);
specification.DefaultValue.Do(
defaultValue => optionHelpText = "(Default: {0}) ".FormatInvariant(FormatDefaultValue(defaultValue)) + optionHelpText);
var optionGroupSpecification = GetOptionGroupSpecification();
if (specification.Required && optionGroupSpecification == null)
optionHelpText = "{0} ".FormatInvariant(requiredWord) + optionHelpText;
if (optionGroupSpecification != null)
{
optionHelpText = "({0}: {1}) ".FormatInvariant(optionGroupWord, optionGroupSpecification.Group) + optionHelpText;
}
//note that we need to indent trim the start of the string because it's going to be
//appended to an existing line that is as long as the indent-level
var indented = TextWrapper.WrapAndIndentText(optionHelpText, maxLength + TotalOptionPadding, widthOfHelpText).TrimStart();
optionsHelp
.Append(indented)
.Append(Environment.NewLine)
.AppendWhen(additionalNewLineAfterOption, Environment.NewLine);
return this;
}
private string AddOptionName(int maxLength, OptionSpecification specification)
{