-
Notifications
You must be signed in to change notification settings - Fork 416
Expand file tree
/
Copy pathHelpBuilder.Default.cs
More file actions
292 lines (253 loc) · 11.7 KB
/
HelpBuilder.Default.cs
File metadata and controls
292 lines (253 loc) · 11.7 KB
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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.CommandLine.Completions;
using System.Linq;
namespace System.CommandLine.Help;
internal partial class HelpBuilder
{
/// <summary>
/// Provides default formatting for help output.
/// </summary>
public static class Default
{
/// <summary>
/// Gets an argument's default value to be displayed in help.
/// </summary>
/// <param name="symbol">The argument or option to get the default value for.</param>
public static string GetArgumentDefaultValue(Symbol symbol)
{
return symbol switch
{
Argument argument => ShouldShowDefaultValue(argument)
? ToString(argument.GetDefaultValue(), argument.ValueType)
: "",
Option option => ShouldShowDefaultValue(option)
? ToString(option.GetDefaultValue(), option.ValueType)
: "",
_ => throw new InvalidOperationException("Symbol must be an Argument or Option.")
};
static string ToString(object? value, Type valueType) => value switch
{
_ when (valueType == typeof(bool) || valueType == typeof(bool?)) && value is not true => string.Empty,
bool boolValue => boolValue ? "true" : "false",
null => string.Empty,
string str => str,
IEnumerable enumerable => string.Join("|", enumerable.Cast<object>()),
_ => value.ToString() ?? string.Empty
};
}
public static bool ShouldShowDefaultValue(Symbol symbol) =>
symbol switch
{
Option option => ShouldShowDefaultValue(option),
Argument argument => ShouldShowDefaultValue(argument),
_ => false
};
public static bool ShouldShowDefaultValue(Option option) =>
option.HasDefaultValue;
public static bool ShouldShowDefaultValue(Argument argument) =>
argument.HasDefaultValue;
/// <summary>
/// Gets the description for an argument (typically used in the second column text in the arguments section).
/// </summary>
public static string GetArgumentDescription(Argument argument) => argument.Description ?? string.Empty;
/// <summary>
/// Gets the usage title for an argument (for example: <c><value></c>, typically used in the first column text in the arguments usage section, or within the synopsis.
/// </summary>
public static string GetArgumentUsageLabel(Symbol parameter)
{
// By default Option.Name == Argument.Name, don't repeat it
return parameter switch
{
Argument argument => GetUsageLabel(argument.HelpName, argument.ValueType, argument.CompletionSources, argument, argument.Arity) ?? $"<{argument.Name}>",
Option option => GetUsageLabel(option.HelpName, option.ValueType, option.CompletionSources, option, option.Arity) ?? "",
_ => throw new InvalidOperationException()
};
static string? GetUsageLabel(
string? helpName,
Type valueType,
List<Func<CompletionContext, IEnumerable<CompletionItem>>> completionSources,
Symbol symbol,
ArgumentArity arity)
{
if (!string.IsNullOrWhiteSpace(helpName))
{
return $"<{helpName}>";
}
if (valueType == typeof(bool) ||
valueType == typeof(bool?) ||
arity.MaximumNumberOfValues <= 0) // allowing zero arguments means we don't need to show usage
{
return null;
}
if (completionSources.Count <= 0)
{
if (symbol is Option)
{
return $"<{symbol.Name.TrimStart('-', '/')}>";
}
return null;
}
IEnumerable<string> completions = symbol
.GetCompletions(CompletionContext.Empty)
.Select(item => item.Label);
string joined = string.Join("|", completions);
if (!string.IsNullOrEmpty(joined))
{
return $"<{joined}>";
}
return null;
}
}
/// <summary>
/// Gets the usage label for the specified symbol (typically used as the first column text in help output).
/// </summary>
/// <param name="symbol">The symbol to get a help item for.</param>
/// <returns>Text to display.</returns>
public static string GetCommandUsageLabel(Command symbol)
=> GetIdentifierSymbolUsageLabel(symbol, symbol.Aliases);
/// <inheritdoc cref="GetCommandUsageLabel(Command)"/>
public static string GetOptionUsageLabel(Option symbol)
=> GetIdentifierSymbolUsageLabel(symbol, symbol.Aliases);
private static string GetIdentifierSymbolUsageLabel(Symbol symbol, ICollection<string>? aliasSet)
{
var aliases = aliasSet is null
? new[] { symbol.Name }
: new[] { symbol.Name }.Concat(aliasSet)
.Select(r => r.SplitPrefix())
.OrderBy(r => r.Prefix, StringComparer.OrdinalIgnoreCase)
.ThenBy(r => r.Alias, StringComparer.OrdinalIgnoreCase)
.GroupBy(t => t.Alias)
.Select(t => t.First())
.Select(t => $"{t.Prefix}{t.Alias}");
var firstColumnText = string.Join(", ", aliases);
foreach (var argument in symbol.GetParameters())
{
if (!argument.Hidden)
{
var argumentFirstColumnText = GetArgumentUsageLabel(argument);
if (!string.IsNullOrWhiteSpace(argumentFirstColumnText))
{
firstColumnText += $" {argumentFirstColumnText}";
}
}
}
if (symbol is Option { Required: true })
{
firstColumnText += $" {LocalizationResources.HelpOptionsRequiredLabel()}";
}
return firstColumnText;
}
/// <summary>
/// Gets the default sections to be written for command line help.
/// </summary>
public static IEnumerable<Func<HelpContext, bool>> GetLayout()
{
yield return SynopsisSection();
yield return CommandUsageSection();
yield return CommandArgumentsSection();
yield return OptionsSection();
yield return SubcommandsSection();
yield return AdditionalArgumentsSection();
}
/// <summary>
/// Writes a help section describing a command's synopsis.
/// </summary>
public static Func<HelpContext, bool> SynopsisSection() =>
ctx =>
{
ctx.HelpBuilder.WriteHeading(LocalizationResources.HelpDescriptionTitle(), ctx.Command.Description, ctx.Output);
return true;
};
/// <summary>
/// Writes a help section describing a command's usage.
/// </summary>
public static Func<HelpContext, bool> CommandUsageSection() =>
ctx =>
{
ctx.HelpBuilder.WriteHeading(LocalizationResources.HelpUsageTitle(), ctx.HelpBuilder.GetUsage(ctx.Command), ctx.Output);
return true;
};
/// <summary>
/// Writes a help section describing a command's arguments.
/// </summary>
public static Func<HelpContext, bool> CommandArgumentsSection() =>
ctx =>
{
TwoColumnHelpRow[] commandArguments = ctx.HelpBuilder.GetCommandArgumentRows(ctx.Command, ctx).ToArray();
if (commandArguments.Length > 0)
{
ctx.HelpBuilder.WriteHeading(LocalizationResources.HelpArgumentsTitle(), null, ctx.Output);
ctx.HelpBuilder.WriteColumns(commandArguments, ctx);
return true;
}
return false;
};
/// <summary>
/// Writes a help section describing a command's subcommands.
/// </summary>
public static Func<HelpContext, bool> SubcommandsSection() =>
ctx => ctx.HelpBuilder.WriteSubcommands(ctx);
/// <summary>
/// Writes a help section describing a command's options.
/// </summary>
public static Func<HelpContext, bool> OptionsSection() =>
ctx =>
{
List<TwoColumnHelpRow> optionRows = new();
bool addedHelpOption = false;
foreach (Option option in ctx.Command.Options.OrderBy(o => o is HelpOption or VersionOption))
{
if (!option.Hidden)
{
if (option is HelpOption)
{
addedHelpOption = true;
}
optionRows.Add(ctx.HelpBuilder.GetTwoColumnRow(option, ctx));
}
}
Command? current = ctx.Command;
while (current is not null)
{
Command? parentCommand = null;
foreach (Symbol parent in current.Parents)
{
if ((parentCommand = parent as Command) is not null)
{
if (parentCommand.Options.Any())
{
foreach (var option in parentCommand.Options)
{
// global help aliases may be duplicated, we just ignore them
if (option is { Recursive: true, Hidden: false })
{
if (option is not HelpOption || !addedHelpOption)
{
optionRows.Add(ctx.HelpBuilder.GetTwoColumnRow(option, ctx));
}
}
}
}
break;
}
}
current = parentCommand;
}
if (optionRows.Count > 0)
{
ctx.HelpBuilder.WriteHeading(LocalizationResources.HelpOptionsTitle(), null, ctx.Output);
ctx.HelpBuilder.WriteColumns(optionRows, ctx);
return true;
}
return false;
};
/// <summary>
/// Writes a help section describing a command's additional arguments, typically shown only when <see cref="Command.TreatUnmatchedTokensAsErrors"/> is set to <see langword="true"/>.
/// </summary>
public static Func<HelpContext, bool> AdditionalArgumentsSection() =>
ctx => ctx.HelpBuilder.WriteAdditionalArguments(ctx);
}
}