Skip to content

Commit dbc6cc0

Browse files
committed
Defaults to current consoles width if available otherwise uses default. Made easier to override by bring it up to the ParserSettings class.
Added ParserSettings.MaximumDisplayWidth property that will be passed to HelpText Added maxDisplayWidth params to several methods with a default of DefaultMaximumLength if not provided Added an attempt to set the MaximumDisplayWidth in ParserSettings and HelpText to Console.WindowWidth and if it isn't possible use MaximumDisplayWidth instead.
1 parent 919bfda commit dbc6cc0

File tree

4 files changed

+97
-15
lines changed

4 files changed

+97
-15
lines changed

‎src/CommandLine/Parser.cs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,15 +187,16 @@ private static ParserResult<T> MakeParserResult<T>(ParserResult<T> parserResult,
187187
{
188188
returnDisplayHelp(
189189
parserResult,
190-
settings.HelpWriter);
190+
settings.HelpWriter,
191+
settings.MaximumDisplayWidth);
191192
}
192193

193-
privatestaticParserResult<T>DisplayHelp<T>(ParserResult<T>parserResult,TextWriterhelpWriter)
194+
privatestaticParserResult<T>DisplayHelp<T>(ParserResult<T>parserResult,TextWriterhelpWriter,intmaxDisplayWidth)
194195
{
195196
parserResult.WithNotParsed(
196197
errors =>
197198
Maybe.Merge(errors.ToMaybe(),helpWriter.ToMaybe())
198-
.Do((_,writer)=>writer.Write(HelpText.AutoBuild(parserResult)))
199+
.Do((_,writer)=>writer.Write(HelpText.AutoBuild(parserResult,maxDisplayWidth)))
199200
);
200201

201202
returnparserResult;

‎src/CommandLine/ParserSettings.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,16 @@ namespace CommandLine
1313
/// </summary>
1414
publicclassParserSettings:IDisposable
1515
{
16+
privateconstintDefaultMaximumLength=80;// default console width
17+
1618
privatebooldisposed;
1719
privateboolcaseSensitive;
1820
privateboolcaseInsensitiveEnumValues;
1921
privateTextWriterhelpWriter;
2022
privateboolignoreUnknownArguments;
2123
privateCultureInfoparsingCulture;
2224
privateboolenableDashDash;
25+
privateintmaximumDisplayWidth;
2326

2427
/// <summary>
2528
/// Initializes a new instance of the <see cref="ParserSettings"/> class.
@@ -29,6 +32,14 @@ public ParserSettings()
2932
caseSensitive=true;
3033
caseInsensitiveEnumValues=false;
3134
parsingCulture=CultureInfo.InvariantCulture;
35+
try
36+
{
37+
maximumDisplayWidth=Console.WindowWidth;
38+
}
39+
catch(IOException)
40+
{
41+
maximumDisplayWidth=DefaultMaximumLength;
42+
}
3243
}
3344

3445
/// <summary>
@@ -114,6 +125,15 @@ public bool EnableDashDash
114125
set{PopsicleSetter.Set(Consumed,refenableDashDash,value);}
115126
}
116127

128+
/// <summary>
129+
/// Gets or sets the maximum width of the display. This determines word wrap when displaying the text.
130+
/// </summary>
131+
publicintMaximumDisplayWidth
132+
{
133+
get{returnmaximumDisplayWidth;}
134+
set{maximumDisplayWidth=value;}
135+
}
136+
117137
internalStringComparerNameComparer
118138
{
119139
get

‎src/CommandLine/Text/HelpText.cs‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
usingSystem;
44
usingSystem.Collections;
55
usingSystem.Collections.Generic;
6+
usingSystem.IO;
67
usingSystem.Text;
78
usingSystem.Linq;
89
usingSystem.Reflection;
@@ -23,7 +24,7 @@ public class HelpText
2324
privatereadonlyStringBuilderpreOptionsHelp;
2425
privatereadonlyStringBuilderpostOptionsHelp;
2526
privatereadonlySentenceBuildersentenceBuilder;
26-
privateint?maximumDisplayWidth;
27+
privateintmaximumDisplayWidth;
2728
privatestringheading;
2829
privatestringcopyright;
2930
privatebooladditionalNewLineAfterOption;
@@ -101,7 +102,14 @@ public HelpText(SentenceBuilder sentenceBuilder, string heading, string copyrigh
101102

102103
preOptionsHelp=newStringBuilder(BuilderCapacity);
103104
postOptionsHelp=newStringBuilder(BuilderCapacity);
104-
105+
try
106+
{
107+
maximumDisplayWidth=Console.WindowWidth;
108+
}
109+
catch(IOException)
110+
{
111+
maximumDisplayWidth=DefaultMaximumLength;
112+
}
105113
this.sentenceBuilder=sentenceBuilder;
106114
this.heading=heading;
107115
this.copyright=copyright;
@@ -143,7 +151,7 @@ public string Copyright
143151
/// <value>The maximum width of the display.</value>
144152
publicintMaximumDisplayWidth
145153
{
146-
get{returnmaximumDisplayWidth.HasValue?maximumDisplayWidth.Value:DefaultMaximumLength;}
154+
get{returnmaximumDisplayWidth;}
147155
set{maximumDisplayWidth=value;}
148156
}
149157

@@ -193,18 +201,22 @@ public SentenceBuilder SentenceBuilder
193201
/// <param name='onError'>A delegate used to customize the text block of reporting parsing errors text block.</param>
194202
/// <param name='onExample'>A delegate used to customize <see cref="CommandLine.Text.Example"/> model used to render text block of usage examples.</param>
195203
/// <param name="verbsIndex">If true the output style is consistent with verb commands (no dashes), otherwise it outputs options.</param>
204+
/// <param name="maxDisplayWidth">The maximum width of the display.</param>
196205
/// <remarks>The parameter <paramref name="verbsIndex"/> is not ontly a metter of formatting, it controls whether to handle verbs or options.</remarks>
197206
publicstaticHelpTextAutoBuild<T>(
198207
ParserResult<T>parserResult,
199208
Func<HelpText,HelpText>onError,
200209
Func<Example,Example>onExample,
201-
boolverbsIndex=false)
210+
boolverbsIndex=false,
211+
intmaxDisplayWidth=DefaultMaximumLength)
202212
{
203-
varauto=newHelpText{
213+
varauto=newHelpText
214+
{
204215
Heading=HeadingInfo.Default,
205216
Copyright=CopyrightInfo.Default,
206217
AdditionalNewLineAfterOption=true,
207-
AddDashesToOption=!verbsIndex
218+
AddDashesToOption=!verbsIndex,
219+
MaximumDisplayWidth=maxDisplayWidth
208220
};
209221

210222
varerrors=Enumerable.Empty<Error>();
@@ -253,29 +265,30 @@ public static HelpText AutoBuild<T>(
253265
/// automatically handling verbs or options scenario.
254266
/// </summary>
255267
/// <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>
268+
/// <param name="maxDisplayWidth">The maximum width of the display.</param>
256269
/// <returns>
257270
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
258271
/// </returns>
259272
/// <remarks>This feature is meant to be invoked automatically by the parser, setting the HelpWriter property
260273
/// of <see cref="CommandLine.ParserSettings"/>.</remarks>
261-
publicstaticHelpTextAutoBuild<T>(ParserResult<T>parserResult)
274+
publicstaticHelpTextAutoBuild<T>(ParserResult<T>parserResult,intmaxDisplayWidth=DefaultMaximumLength)
262275
{
263276
if(parserResult.Tag!=ParserResultType.NotParsed)
264277
thrownewArgumentException("Excepting NotParsed<T> type.","parserResult");
265278

266279
varerrors=((NotParsed<T>)parserResult).Errors;
267280

268281
if(errors.Any(e =>e.Tag==ErrorType.VersionRequestedError))
269-
returnnewHelpText(HeadingInfo.Default).AddPreOptionsLine(Environment.NewLine);
282+
returnnewHelpText(HeadingInfo.Default){MaximumDisplayWidth=maxDisplayWidth}.AddPreOptionsLine(Environment.NewLine);
270283

271284
if(!errors.Any(e =>e.Tag==ErrorType.HelpVerbRequestedError))
272-
returnAutoBuild(parserResult, current =>DefaultParsingErrorsHandler(parserResult,current), e =>e);
285+
returnAutoBuild(parserResult, current =>DefaultParsingErrorsHandler(parserResult,current), e =>e,maxDisplayWidth:maxDisplayWidth);
273286

274287
varerr=errors.OfType<HelpVerbRequestedError>().Single();
275288
varpr=newNotParsed<object>(TypeInfo.Create(err.Type),Enumerable.Empty<Error>());
276289
returnerr.Matched
277-
?AutoBuild(pr, current =>DefaultParsingErrorsHandler(pr,current), e =>e)
278-
:AutoBuild(parserResult, current =>DefaultParsingErrorsHandler(parserResult,current), e =>e,true);
290+
?AutoBuild(pr, current =>DefaultParsingErrorsHandler(pr,current), e =>e,maxDisplayWidth:maxDisplayWidth)
291+
:AutoBuild(parserResult, current =>DefaultParsingErrorsHandler(parserResult,current), e =>e,true,maxDisplayWidth);
279292
}
280293

281294
/// <summary>

‎tests/CommandLine.Tests/Unit/Text/HelpTextTests.cs‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ public void When_defined_MetaValue_should_be_rendered()
131131
}
132132

133133
[Fact]
134-
publicvoidWhen_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_column()
134+
publicvoidWhen_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_column_given_width_of_40()
135135
{
136136
// Fixture setup
137137
// Exercize system
@@ -153,6 +153,28 @@ public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_c
153153
// Teardown
154154
}
155155

156+
157+
158+
[Fact]
159+
publicvoidWhen_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_column_given_width_of_100()
160+
{
161+
// Fixture setup
162+
// Exercize system
163+
varsut=newHelpText(newHeadingInfo("CommandLine.Tests.dll","1.9.4.131")){MaximumDisplayWidth=100};
164+
//sut.MaximumDisplayWidth = 100;
165+
sut.AddOptions(
166+
newNotParsed<Simple_Options_With_HelpText_Set_To_Long_Description>(
167+
TypeInfo.Create(typeof(Simple_Options_With_HelpText_Set_To_Long_Description)),
168+
Enumerable.Empty<Error>()));
169+
170+
// Verify outcome
171+
varlines=sut.ToString().Split(new[]{Environment.NewLine},StringSplitOptions.None);
172+
lines[2].ShouldBeEquivalentTo(" v, verbose This is the description of the verbosity to test out the wrapping capabilities of ");//"The first line should have the arguments and the start of the Help Text.");
173+
//string formattingMessage = "Beyond the second line should be formatted as though it's in a column."
174+
lines[3].ShouldBeEquivalentTo(" the Help Text.");
175+
// Teardown
176+
}
177+
156178
[Fact]
157179
publicvoidLong_help_text_without_spaces()
158180
{
@@ -315,6 +337,32 @@ public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_fo
315337
// Teardown
316338
}
317339

340+
[Fact]
341+
publicvoidInvoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_formatted_text_given_display_width_100()
342+
{
343+
// Fixture setup
344+
varfakeResult=newNotParsed<object>(
345+
TypeInfo.Create(typeof(NullInstance)),
346+
newError[]
347+
{
348+
newHelpVerbRequestedError("commit",typeof(Commit_Verb),true)
349+
});
350+
351+
// Exercize system
352+
varhelpText=HelpText.AutoBuild(fakeResult,maxDisplayWidth:100);
353+
354+
// Verify outcome
355+
varlines=helpText.ToString().ToNotEmptyLines().TrimStringArray();
356+
357+
lines[0].Should().StartWithEquivalent("CommandLine");
358+
lines[1].Should().StartWithEquivalent("Copyright (c)");
359+
lines[2].ShouldBeEquivalentTo("-p, --patch Use the interactive patch selection interface to chose which changes to commit.");
360+
lines[3].ShouldBeEquivalentTo("--amend Used to amend the tip of the current branch.");
361+
lines[4].ShouldBeEquivalentTo("-m, --message Use the given message as the commit message.");
362+
lines[5].ShouldBeEquivalentTo("--help Display this help screen.");
363+
// Teardown
364+
}
365+
318366
[Fact]
319367
publicvoidInvoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_formatted_text()
320368
{

0 commit comments

Comments
(0)