4using System.Collections;
5using System.Collections.Generic;
8using System.Reflection;
72 : this(sentenceBuilder, string.Empty, string.Empty) { }
90 : this(sentenceBuilder,
heading, string.Empty) { }
112 if (sentenceBuilder ==
null)
114 throw new ArgumentNullException(
"sentenceBuilder");
119 throw new ArgumentNullException(
"heading");
124 throw new ArgumentNullException(
"copyright");
162 throw new ArgumentNullException(
"value");
180 throw new ArgumentNullException(
"value");
254 Func<HelpText, HelpText> onError,
255 Func<Example, Example> onExample,
256 bool verbsIndex =
false,
275 auto = onError(
auto);
278 IEnumerable<Error> errors = Enumerable.Empty<
Error>();
284 if (errors.IsHelp() ||
285 errors.OnlyMeaningfulOnes()
288 auto = onError(
auto);
293 .Do(license => license.AddToHelpText(
auto,
true));
300 if (usageAttr.IsJust() || usageLines.IsJust())
302 string heading =
auto.SentenceBuilder.UsageHeadingText();
311 auto.AddPreOptionsLine(
heading);
315 usageAttr.Do(usage => usage.AddToHelpText(
auto,
true));
320 errors.Any(e => e.Tag ==
ErrorType.NoVerbSelectedError))
322 auto.AddDashesToOption =
false;
327 auto.AddOptions(parserResult);
351 return AutoBuild(parserResult, h => h, maxDisplayWidth);
372 Func<HelpText, HelpText> onError,
377 throw new ArgumentException(
"Excepting NotParsed<T> type.",
"parserResult");
380 IEnumerable<Error> errors = ((
NotParsed<T>)parserResult).Errors;
382 if (errors.Any(e => e.Tag ==
ErrorType.VersionRequestedError))
384 return new HelpText($
"{HeadingInfo.Default}{Environment.NewLine}")
387 }.AddPreOptionsLine(Environment.NewLine);
390 if (!errors.Any(e => e.Tag ==
ErrorType.HelpVerbRequestedError))
392 return AutoBuild(parserResult,
395 onError?.Invoke(current);
397 return DefaultParsingErrorsHandler(parserResult, current);
400 maxDisplayWidth: maxDisplayWidth
415 onError?.Invoke(current);
417 return DefaultParsingErrorsHandler(pr, current);
420 maxDisplayWidth: maxDisplayWidth
422 : AutoBuild(parserResult,
425 onError?.Invoke(current);
427 return DefaultParsingErrorsHandler(parserResult, current);
445 if (parserResult ==
null)
447 throw new ArgumentNullException(
"parserResult");
452 throw new ArgumentNullException(
"current");
455 if (((
NotParsed<T>)parserResult).Errors.OnlyMeaningfulOnes()
461 IEnumerable<string> errors = RenderParsingErrorsTextAsLines(parserResult,
483 public static implicit
operator string(
HelpText info)
541 string[] lines = text.Split(
new[] { Environment.NewLine },
542 StringSplitOptions.None
556 string[] lines = text.Split(
new[] { Environment.NewLine },
557 StringSplitOptions.None
573 throw new ArgumentNullException(
"result");
593 throw new ArgumentNullException(
"types");
596 if (types.Length == 0)
598 throw new ArgumentOutOfRangeException(
"types");
618 throw new ArgumentNullException(
"result");
639 throw new ArgumentNullException(
"types");
642 if (types.Length == 0)
644 throw new ArgumentOutOfRangeException(
"types");
669 Func<Error, string> formatError,
670 Func<IEnumerable<MutuallyExclusiveSetError>,
string>
671 formatMutuallyExclusiveSetErrors,
674 return string.Join(Environment.NewLine,
675 RenderParsingErrorsTextAsLines(parserResult,
677 formatMutuallyExclusiveSetErrors,
698 Func<Error, string> formatError,
699 Func<IEnumerable<MutuallyExclusiveSetError>,
701 formatMutuallyExclusiveSetErrors,
704 if (parserResult ==
null)
706 throw new ArgumentNullException(
"parserResult");
709 IEnumerable<Error> meaningfulErrors =
710 ((
NotParsed<T>)parserResult).Errors.OnlyMeaningfulOnes();
712 if (meaningfulErrors.Empty())
717 foreach (
Error error
in meaningfulErrors
718 .Where(e => e.Tag !=
ErrorType.MutuallyExclusiveSetError))
720 StringBuilder line =
new StringBuilder(indent.Spaces())
721 .Append(formatError(error));
723 yield
return line.ToString();
726 string mutuallyErrs =
729 if (mutuallyErrs.Length > 0)
731 string[] lines = mutuallyErrs
732 .Split(
new[] { Environment.NewLine },
733 StringSplitOptions.None
736 foreach (
string line
in lines)
752 return RenderUsageText(parserResult, example => example);
765 return string.Join(Environment.NewLine, RenderUsageTextAsLines(parserResult, mapperFunc));
777 Func<Example, Example> mapperFunc)
779 if (parserResult ==
null)
781 throw new ArgumentNullException(
"parserResult");
791 Tuple<UsageAttribute, IEnumerable<Example>> usageTuple = usage.FromJustOrFail();
792 IEnumerable<Example> examples = usageTuple.Item2;
795 foreach (
Example e
in examples)
797 Example example = mapperFunc(e);
799 StringBuilder exampleText =
new StringBuilder(example.
HelpText)
802 yield
return exampleText.ToString();
803 IEnumerable<UnParserSettings> styles = example.GetFormatStylesOrDefault();
813 config.PreferShortName = s.PreferShortName;
814 config.GroupSwitches = s.GroupSwitches;
815 config.UseEqualToken = s.UseEqualToken;
816 config.SkipDefault = s.SkipDefault;
821 yield
return commandLine.ToString();
832 const int ExtraLength = 10;
834 int sbLength =
heading.SafeLength() +
840 StringBuilder result =
new StringBuilder(sbLength);
843 .AppendWhen(!
string.IsNullOrEmpty(
copyright),
863 string NewLineIfNeededBefore(StringBuilder sb)
867 !result.SafeEndsWith(Environment.NewLine) &&
868 !sb.SafeStartsWith(Environment.NewLine))
870 return Environment.NewLine;
876 return result.ToString();
879 internal static void AddLine(StringBuilder builder,
string value,
int maximumLength)
883 throw new ArgumentNullException(nameof(builder));
888 throw new ArgumentNullException(nameof(value));
891 if (maximumLength < 1)
893 throw new ArgumentOutOfRangeException(nameof(value));
896 value = value.TrimEnd();
898 builder.AppendWhen(builder.Length > 0, Environment.NewLine);
906 IEnumerable<OptionSpecification> optionSpecs = specs
919 IOrderedEnumerable<ValueSpecification> valueSpecs = specs
921 .OrderBy(v => v.Index);
930 return type.GetUsageData()
933 PropertyInfo prop = tuple.Item1;
936 IEnumerable<Example> examples = (IEnumerable<Example>)prop
938 BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty,
944 return Tuple.Create(attr, examples);
951 IEnumerable<OptionSpecification> optionSpecs = from verbTuple in
Verb.
SelectFromTypes(types)
954 verbTuple.Item1.Name.Concat(verbTuple.Item1.Aliases)
955 .ToDelimitedString(
", "),
957 verbTuple.Item1.IsDefault
958 ?
"(Default Verb) " + verbTuple.Item1.HelpText
959 : verbTuple.Item1.HelpText,
961 verbTuple.Item1.Hidden
979 string optionGroupWord,
992 List<ComparableOption> comparables = specifications.ToList()
1006 AddOption(requiredWord, optionGroupWord, maxLength, spec, remainingSpace);
1011 specifications.ForEach(option =>
1012 AddOption(requiredWord, optionGroupWord, maxLength, option, remainingSpace)
1047 string optionGroupWord,
1050 int widthOfHelpText)
1056 optionSpecification.
Group.Length > 0
1060 return optionSpecification;
1066 if (specification.
Hidden)
1073 StringBuilder name =
new StringBuilder(maxLength)
1080 .Append(name.Length < maxLength
1082 .PadRight(maxLength)
1087 string optionHelpText = specification.
HelpText;
1091 optionHelpText +=
" Valid values: " +
string.Join(
", ", specification.
EnumValues);
1096 "(Default: {0}) ".FormatInvariant(FormatDefaultValue(defaultValue)) +
1102 if (specification.
Required && optionGroupSpecification ==
null)
1104 optionHelpText =
"{0} ".FormatInvariant(requiredWord) + optionHelpText;
1107 if (optionGroupSpecification !=
null)
1109 optionHelpText =
"({0}: {1}) ".FormatInvariant(optionGroupWord, optionGroupSpecification.
Group) +
1121 .Append(Environment.NewLine)
1130 new StringBuilder(maxLength)
1131 .MapIf(specification.
ShortName.Length > 0,
1134 .AppendFormat(
"{0}", specification.
ShortName)
1135 .AppendFormatWhen(specification.
MetaValue.Length > 0,
" {0}", specification.
MetaValue)
1136 .AppendWhen(specification.
LongName.Length > 0,
", ")
1138 .MapIf(specification.
LongName.Length > 0,
1141 .AppendFormat(
"{0}", specification.
LongName)
1142 .AppendFormatWhen(specification.
MetaValue.Length > 0,
"={0}", specification.
MetaValue)
1149 return new StringBuilder(maxLength)
1150 .BimapIf(specification.
MetaName.Length > 0,
1151 it => it.AppendFormat(
"{0} (pos. {1})", specification.
MetaName, specification.
Index),
1152 it => it.AppendFormat(
"value pos. {0}", specification.
Index)
1154 .AppendFormatWhen(specification.
MetaValue.Length > 0,
1170 return specifications.Aggregate(0,
1182 return Math.Max(length, specLength);
1192 bool hasShort = spec.ShortName.Length > 0;
1193 bool hasLong = spec.LongName.Length > 0;
1199 metaLength = spec.MetaValue.Length + 1;
1211 specLength += metaLength;
1216 specLength += spec.
LongName.Length;
1223 specLength += metaLength;
1226 if (hasShort && hasLong)
1238 bool hasMeta = spec.MetaName.Length > 0;
1244 metaLength = spec.MetaValue.Length + 1;
1249 specLength += spec.MetaName.Length +
1250 spec.
Index.ToStringInvariant()
1256 specLength += spec.
Index.ToStringInvariant()
1261 specLength += metaLength;
1270 return value.ToStringLocal()
1271 .ToLowerInvariant();
1274 if (value is
string)
1276 return value.ToStringLocal();
1279 IEnumerable asEnumerable = value as IEnumerable;
1281 if (asEnumerable ==
null)
1283 return value.ToStringLocal();
1286 StringBuilder builder =
new StringBuilder();
1288 foreach (
object item
in asEnumerable)
1291 .Append(item.ToStringLocal())
1295 return builder.Length > 0
1296 ? builder.ToString(0, builder.Length - 1)
1306 bool required = option?.
Required ??
false;
1310 Required = required,
1311 IsOption = option !=
null,
1312 IsValue = value !=
null,
1324 if (attr1.IsOption && attr2.IsOption)
1326 if (attr1.Required && !attr2.Required)
1331 if (!attr1.Required && attr2.Required)
1336 return string.Compare(attr1.LongName, attr2.LongName, StringComparison.Ordinal);
1339 if (attr1.IsOption && attr2.IsValue)
The Maybe type models an optional value. A value of type Maybe a either contains a value of type a (r...
bool MatchNothing()
Matches an empty value returning true.
static OptionSpecification NewSwitch(string shortName, string longName, bool required, string helpText, string metaValue, bool hidden=false)
static Specification FromProperty(PropertyInfo property)
Maybe< object > DefaultValue
IEnumerable< string > EnumValues
static IEnumerable< Tuple< Verb, Type > > SelectFromTypes(IEnumerable< Type > types)
Models an error generated when a user explicitly requests help in verb commands scenario.
Type Type
System.Type of verb command.
static string GetAssemblyName()
Models an error generated when a an option from another set is defined.
It contains a sequence of CommandLine.Error.
Provides methods to parse command line arguments.
static Parser Default
Gets the singleton instance created with basic defaults.
Models a parser result. When inherited by CommandLine.Parsed<T>, it contains an instance of type T w...
ParserResultType Tag
Parser result type discriminator, defined as CommandLine.ParserResultType enumeration.
Models a multiline assembly license text.
Models a multiline assembly usage text.
Models the copyright part of an help text. You can assign it where you assign any System....
static CopyrightInfo Empty
An empty object used for initialization.
static CopyrightInfo Default
Gets the default copyright information. Retrieved from AssemblyCopyrightAttribute,...
Models a command line usage example.
string HelpText
Example description.
Models the heading part of an help text. You can assign it where you assign any System....
static HeadingInfo Default
Gets the default heading instance. The title is retrieved from AssemblyTitleAttribute,...
static HeadingInfo Empty
An empty object used for initialization.
HelpText AddPostOptionsText(string text)
Adds a text block of lines at the bottom, after options usage string.
OptionSpecification MakeVersionEntry()
HelpText(SentenceBuilder sentenceBuilder, string heading, string copyright)
Initializes a new instance of the CommandLine.Text.HelpText class specifying heading and copyright st...
HelpText AddPreOptionsLine(string value)
Adds a text line after copyright and before options usage strings.
readonly StringBuilder preOptionsHelp
HelpText AddPostOptionsLine(string value)
Adds a text line at the bottom, after options usage string.
const int TotalOptionPadding
The total amount of extra space that needs to accounted for when indenting Option help text.
Comparison< ComparableOption > OptionComparison
int GetMaxOptionLength(OptionSpecification spec)
HelpText AddPreOptionsText(string text)
Adds a text block of lines after copyright and before options usage strings.
HelpText AddPreOptionsLine(string value, int maximumLength)
int GetMaxValueLength(ValueSpecification spec)
HelpText AddLine(StringBuilder builder, string value)
HelpText AddOptionsImpl(IEnumerable< Specification > specifications, string requiredWord, string optionGroupWord, int maximumLength)
HelpText AddOption(string requiredWord, string optionGroupWord, int maxLength, Specification specification, int widthOfHelpText)
HelpText AddVerbs(params Type[] types)
Adds a text block with verbs usage string.
SentenceBuilder SentenceBuilder
Gets the SentenceBuilder instance specified in constructor.
bool AddEnumValuesToHelpText
Gets or sets a value indicating whether to add the values of an enum after the description of the spe...
HelpText(SentenceBuilder sentenceBuilder, string heading)
Initializes a new instance of the CommandLine.Text.HelpText class specifying the sentence builder and...
HelpText AddPostOptionsLines(IEnumerable< string > lines)
Adds text lines at the bottom, after options usage string.
readonly StringBuilder postOptionsHelp
HelpText AddOptions< T >(ParserResult< T > result)
Adds a text block with options usage string.
static void AddLine(StringBuilder builder, string value, int maximumLength)
HelpText(string heading)
Initializes a new instance of the CommandLine.Text.HelpText class specifying heading string.
static HelpText DefaultParsingErrorsHandler< T >(ParserResult< T > parserResult, HelpText current)
Supplies a default parsing error handler implementation.
HelpText AddPreOptionsLines(IEnumerable< string > lines)
Adds text lines after copyright and before options usage strings.
int GetMaxLength(IEnumerable< Specification > specifications)
static Comparison< ComparableOption > RequiredThenAlphaComparison
const int BuilderCapacity
string Copyright
Gets or sets the copyright string. You can directly assign a CommandLine.Text.CopyrightInfo instance.
IEnumerable< Specification > AdaptVerbsToSpecifications(IEnumerable< Type > types)
const int DefaultMaximumLength
ComparableOption ToComparableOption(Specification spec, int index)
bool AutoVersion
Gets or sets a value indicating whether implicit option or verb 'version' should be supported.
int MaximumDisplayWidth
Gets or sets the maximum width of the display. This determines word wrap when displaying the text.
string AddValueName(int maxLength, ValueSpecification specification)
bool AddNewLineBetweenHelpSections
Gets or sets a value indicating whether to add newlines between help sections.
static HelpText AutoBuild< T >(ParserResult< T > parserResult, Func< HelpText, HelpText > onError, Func< Example, Example > onExample, bool verbsIndex=false, int maxDisplayWidth=DefaultMaximumLength)
Creates a new instance of the CommandLine.Text.HelpText class using common defaults.
bool AutoHelp
Gets or sets a value indicating whether implicit option or verb 'help' should be supported.
static string RenderParsingErrorsText< T >(ParserResult< T > parserResult, Func< Error, string > formatError, Func< IEnumerable< MutuallyExclusiveSetError >, string > formatMutuallyExclusiveSetErrors, int indent)
Builds a string that contains a parsing error message.
string Heading
Gets or sets the heading string. You can directly assign a CommandLine.Text.HeadingInfo instance.
HelpText AddVerbs(int maximumLength, params Type[] types)
Adds a text block with verbs usage string.
string AddOptionName(int maxLength, OptionSpecification specification)
IEnumerable< Specification > GetSpecificationsFromType(Type type)
OptionSpecification MakeHelpEntry()
const int OptionToHelpTextSeparatorWidth
The number of spaces between an option and its associated help text.
bool AdditionalNewLineAfterOption
Gets or sets a value indicating whether to add an additional line after the description of the specif...
bool AddDashesToOption
Gets or sets a value indicating whether the format of options should contain dashes....
static Maybe< Tuple< UsageAttribute, IEnumerable< Example > > > GetUsageFromType(Type type)
HelpText(SentenceBuilder sentenceBuilder)
Initializes a new instance of the CommandLine.Text.HelpText class specifying the sentence builder.
override string ToString()
Returns the help screen as a System.String.
StringBuilder optionsHelp
const int OptionPrefixWidth
The width of the option prefix (either "--" or " ".
static IEnumerable< string > RenderUsageTextAsLines< T >(ParserResult< T > parserResult, Func< Example, Example > mapperFunc)
Builds a string sequence with usage text block created using CommandLine.Text.UsageAttribute data and...
static string RenderUsageText< T >(ParserResult< T > parserResult)
Builds a string with usage text block created using CommandLine.Text.UsageAttribute data and metadata...
HelpText()
Initializes a new instance of the CommandLine.Text.HelpText class.
static IEnumerable< string > RenderParsingErrorsTextAsLines< T >(ParserResult< T > parserResult, Func< Error, string > formatError, Func< IEnumerable< MutuallyExclusiveSetError >, string > formatMutuallyExclusiveSetErrors, int indent)
Builds a sequence of string that contains a parsing error message.
HelpText(string heading, string copyright)
Initializes a new instance of the CommandLine.Text.HelpText class specifying heading and copyright st...
static string FormatDefaultValue< T >(T value)
Exposes standard delegates to provide a mean to customize part of help screen generation....
Func< string > RequiredWord
Gets a delegate that returns the word 'required'.
Func< IEnumerable< MutuallyExclusiveSetError >, string > FormatMutuallyExclusiveSetErrors
Gets a delegate that handles mutually exclusive set errors formatting. The delegates must accept a se...
Func< string > ErrorsHeadingText
Gets a delegate that returns that errors block heading text.
Func< string > OptionGroupWord
Gets a delegate that returns the word 'group'.
Func< bool, string > HelpCommandText
Get a delegate that returns the help text of help command. The delegates must accept a boolean that i...
Func< Error, string > FormatError
Gets a delegate that handles singular error formatting. The delegates must accept an Error and return...
Func< bool, string > VersionCommandText
Get a delegate that returns the help text of vesion command. The delegates must accept a boolean that...
A utility class to word-wrap and indent blocks of text.
static string WrapAndIndentText(string input, int indentLevel, int columnWidth)
Convenience method to wraps and indent a string in a single operation.
Applied to a static property that yields a sequence of CommandLine.Text.Example, provides data to ren...
IEnumerable< Type > Choices
static TypeInfo Create(Type current)
Provides settings for when formatting command line from an options instance../>.
ParserResultType
Discriminator enumeration of CommandLine.ParserResultType derivates.
ErrorType
Discriminator enumeration of CommandLine.Error derivates.
Provides means to format an help screen. You can assign it in place of a System.String instance.