-
Notifications
You must be signed in to change notification settings - Fork 382
/
CommandLineBuilderExtensions.cs
742 lines (668 loc) · 32.8 KB
/
CommandLineBuilderExtensions.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
// 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.CommandLine.Binding;
using System.CommandLine.Help;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.CommandLine.Parsing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using static System.Environment;
using Process = System.CommandLine.Invocation.Process;
namespace System.CommandLine.Builder
{
/// <summary>
/// Provides extension methods for <see cref="CommandLineBuilder"/>.
/// </summary>
public static class CommandLineBuilderExtensions
{
private static readonly Lazy<string> _assemblyVersion =
new(() =>
{
var assembly = RootCommand.GetAssembly();
var assemblyVersionAttribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if (assemblyVersionAttribute is null)
{
return assembly.GetName().Version?.ToString() ?? "";
}
else
{
return assemblyVersionAttribute.InformationalVersion;
}
});
/// <summary>
/// Enables signaling and handling of process termination via a <see cref="CancellationToken"/> that can be passed to a <see cref="ICommandHandler"/> during invocation.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="timeout">
/// Optional timeout for the command to process the exit cancellation.
/// If not passed, or passed null or non-positive timeout (including <see cref="Timeout.InfiniteTimeSpan"/>), no timeout is enforced.
/// If positive value is passed - command is forcefully terminated after the timeout with exit code 130 (as if <see cref="CancelOnProcessTermination"/> was not called).
/// Host enforced timeout for ProcessExit event cannot be extended - default is 2 seconds: https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.processexit?view=net-6.0.
/// </param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder CancelOnProcessTermination(
this CommandLineBuilder builder,
TimeSpan? timeout = null)
{
// https://tldp.org/LDP/abs/html/exitcodes.html - 130 - script terminated by ctrl-c
const int SIGINT_EXIT_CODE = 130;
if (timeout == null || timeout.Value < TimeSpan.Zero)
{
timeout = Timeout.InfiniteTimeSpan;
}
builder.AddMiddleware(async (context, next) =>
{
bool cancellationHandlingAdded = false;
ManualResetEventSlim? blockProcessExit = null;
ConsoleCancelEventHandler? consoleHandler = null;
EventHandler? processExitHandler = null;
context.CancellationHandlingAdded += (CancellationTokenSource cts) =>
{
blockProcessExit = new ManualResetEventSlim(initialState: false);
cancellationHandlingAdded = true;
// Default limit for ProcesExit handler is 2 seconds
// https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.processexit?view=net-6.0
processExitHandler = (_, _) =>
{
// Cancel asynchronously not to block the handler (as then the process might possibly run longer then what was the requested timeout)
Task timeoutTask = Task.Delay(timeout.Value);
Task cancelTask = Task.Factory.StartNew(cts.Cancel);
// The process exits as soon as the event handler returns.
// We provide a return value using Environment.ExitCode
// because Main will not finish executing.
// Wait for the invocation to finish.
if (!blockProcessExit.Wait(timeout > TimeSpan.Zero
? timeout.Value
: Timeout.InfiniteTimeSpan))
{
context.ExitCode = SIGINT_EXIT_CODE;
}
// Let's block here (to prevent process bailing out) for the rest of the timeout (if any), for cancellation to finish (if it hasn't yet)
else if (Task.WaitAny(timeoutTask, cancelTask) == 0)
{
// The async cancellation didn't finish in timely manner
context.ExitCode = SIGINT_EXIT_CODE;
}
ExitCode = context.ExitCode;
};
consoleHandler = (_, args) =>
{
// Stop the process from terminating.
// Since the context was cancelled, the invocation should
// finish and Main will return.
args.Cancel = true;
// If timeout was requested - make sure cancellation processing (or any other activity within the current process)
// doesn't keep the process running after the timeout
if (timeout! > TimeSpan.Zero)
{
Task
.Delay(timeout.Value, default)
.ContinueWith(t =>
{
// Prevent our ProcessExit from intervene and block the exit
AppDomain.CurrentDomain.ProcessExit -= processExitHandler;
Environment.Exit(SIGINT_EXIT_CODE);
}, (CancellationToken)default);
}
// Cancel synchronously here - no need to perform it asynchronously as the timeout is already running (and would kill the process if needed),
// plus we cannot wait only on the cancellation (e.g. via `Task.Factory.StartNew(cts.Cancel).Wait(cancelationProcessingTimeout.Value)`)
// as we need to abort any other possible execution within the process - even outside the context of cancellation processing
cts.Cancel();
};
Console.CancelKeyPress += consoleHandler;
AppDomain.CurrentDomain.ProcessExit += processExitHandler;
};
try
{
await next(context);
}
finally
{
if (cancellationHandlingAdded)
{
Console.CancelKeyPress -= consoleHandler;
AppDomain.CurrentDomain.ProcessExit -= processExitHandler;
blockProcessExit!.Set();
}
}
}, MiddlewareOrderInternal.Startup);
return builder;
}
/// <summary>
/// Enables the parser to recognize command line directives.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="value"><see langword="true" /> to enable directives. <see langword="false" /> to parse directive-like tokens in the same way as any other token.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
/// <seealso href="/dotnet/standard/commandline/syntax#directives">Command-line directives</seealso>
/// <seealso cref="DirectiveCollection"/>
public static CommandLineBuilder EnableDirectives(
this CommandLineBuilder builder,
bool value = true)
{
builder.EnableDirectives = value;
return builder;
}
/// <summary>
/// Determines the behavior when parsing a double dash (<c>--</c>) in a command line.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="value"><see langword="true" /> to place all tokens following <c>--</c> into the <see cref="ParseResult.UnparsedTokens"/> collection. <see langword="false" /> to treat all tokens following <c>--</c> as command arguments, even if they match an existing option.</param>
public static CommandLineBuilder EnableLegacyDoubleDashBehavior(
this CommandLineBuilder builder,
bool value = true)
{
builder.EnableLegacyDoubleDashBehavior = value;
return builder;
}
/// <summary>
/// Enables the parser to recognize and expand POSIX-style bundled options.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="value"><see langword="true"/> to parse POSIX bundles; otherwise, <see langword="false"/>.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
/// <remarks>
/// POSIX conventions recommend that single-character options be allowed to be specified together after a single <c>-</c> prefix. When <see cref="EnablePosixBundling"/> is set to <see langword="true"/>, the following command lines are equivalent:
///
/// <code>
/// > myapp -a -b -c
/// > myapp -abc
/// </code>
///
/// If an argument is provided after an option bundle, it applies to the last option in the bundle. When <see cref="EnablePosixBundling"/> is set to <see langword="true"/>, all of the following command lines are equivalent:
/// <code>
/// > myapp -a -b -c arg
/// > myapp -abc arg
/// > myapp -abcarg
/// </code>
///
/// </remarks>
public static CommandLineBuilder EnablePosixBundling(
this CommandLineBuilder builder,
bool value = true)
{
builder.EnablePosixBundling = value;
return builder;
}
/// <summary>
/// Ensures that the application is registered with the <c>dotnet-suggest</c> tool to enable command line completions.
/// </summary>
/// <remarks>For command line completions to work, users must install the <c>dotnet-suggest</c> tool as well as the appropriate shim script for their shell.</remarks>
/// <param name="builder">A command line builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder RegisterWithDotnetSuggest(
this CommandLineBuilder builder)
{
builder.AddMiddleware(async (context, next) =>
{
var feature = new FeatureRegistration("dotnet-suggest-registration");
await feature.EnsureRegistered(async () =>
{
var stdOut = StringBuilderPool.Default.Rent();
var stdErr = StringBuilderPool.Default.Rent();
try
{
var currentProcessFullPath = Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
var currentProcessFileNameWithoutExtension = Path.GetFileNameWithoutExtension(currentProcessFullPath);
var dotnetSuggestProcess = Process.StartProcess(
command: "dotnet-suggest",
args: $"register --command-path \"{currentProcessFullPath}\" --suggestion-command \"{currentProcessFileNameWithoutExtension}\"",
stdOut: value => stdOut.Append(value),
stdErr: value => stdOut.Append(value));
await dotnetSuggestProcess.CompleteAsync();
return $@"{dotnetSuggestProcess.StartInfo.FileName} exited with code {dotnetSuggestProcess.ExitCode}
OUT:
{stdOut}
ERR:
{stdErr}";
}
catch (Exception exception)
{
return $@"Exception during registration:
{exception}";
}
finally
{
StringBuilderPool.Default.ReturnToPool(stdOut);
StringBuilderPool.Default.ReturnToPool(stdErr);
}
});
await next(context);
}, MiddlewareOrderInternal.RegisterWithDotnetSuggest);
return builder;
}
/// <summary>
/// Enables the use of the <c>[env:key=value]</c> directive, allowing environment variables to be set from the command line during invocation.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseEnvironmentVariableDirective(
this CommandLineBuilder builder)
{
builder.AddMiddleware((context, next) =>
{
if (context.ParseResult.Directives.TryGetValues("env", out var keyValuePairs))
{
for (var i = 0; i < keyValuePairs.Count; i++)
{
var envDirective = keyValuePairs[i];
var components = envDirective.Split(new[] { '=' }, count: 2);
var variable = components.Length > 0 ? components[0].Trim() : string.Empty;
if (string.IsNullOrEmpty(variable) || components.Length < 2)
{
continue;
}
var value = components[1].Trim();
SetEnvironmentVariable(variable, value);
}
}
return next(context);
}, MiddlewareOrderInternal.EnvironmentVariableDirective);
return builder;
}
/// <summary>
/// Uses the default configuration.
/// </summary>
/// <remarks>Calling this method is the equivalent to calling:
/// <code>
/// builder
/// .UseVersionOption()
/// .UseHelp()
/// .UseEnvironmentVariableDirective()
/// .UseParseDirective()
/// .UseSuggestDirective()
/// .RegisterWithDotnetSuggest()
/// .UseTypoCorrections()
/// .UseParseErrorReporting()
/// .UseExceptionHandler()
/// .CancelOnProcessTermination();
/// </code>
/// </remarks>
/// <param name="builder">A command line builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseDefaults(this CommandLineBuilder builder)
{
return builder
.UseVersionOption()
.UseHelp()
.UseEnvironmentVariableDirective()
.UseParseDirective()
.UseSuggestDirective()
.RegisterWithDotnetSuggest()
.UseTypoCorrections()
.UseParseErrorReporting()
.UseExceptionHandler()
.CancelOnProcessTermination();
}
/// <summary>
/// Enables an exception handler to catch any unhandled exceptions thrown by a command handler during invocation.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="onException">A delegate that will be called when an exception is thrown by a command handler.</param>
/// <param name="errorExitCode">The exit code to be used when an exception is thrown.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseExceptionHandler(
this CommandLineBuilder builder,
Action<Exception, InvocationContext>? onException = null,
int? errorExitCode = null)
{
builder.AddMiddleware(async (context, next) =>
{
try
{
await next(context);
}
catch (Exception exception)
{
(onException ?? Default)(exception, context);
}
}, MiddlewareOrderInternal.ExceptionHandler);
return builder;
void Default(Exception exception, InvocationContext context)
{
if (exception is not OperationCanceledException)
{
context.Console.ResetTerminalForegroundColor();
context.Console.SetTerminalForegroundRed();
context.Console.Error.Write(context.LocalizationResources.ExceptionHandlerHeader());
context.Console.Error.WriteLine(exception.ToString());
context.Console.ResetTerminalForegroundColor();
}
context.ExitCode = errorExitCode ?? 1;
}
}
/// <summary>
/// Configures the application to show help when one of the following options are specified on the command line:
/// <code>
/// -h
/// /h
/// --help
/// -?
/// /?
/// </code>
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="maxWidth">Maximum output width for default help builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseHelp(this CommandLineBuilder builder, int? maxWidth = null)
{
return builder.UseHelp(new HelpOption(() => builder.LocalizationResources), maxWidth);
}
/// <summary>
/// Configures the application to show help when one of the specified option aliases are used on the command line.
/// </summary>
/// <remarks>The specified aliases will override the default values.</remarks>
/// <param name="builder">A command line builder.</param>
/// <param name="helpAliases">The set of aliases that can be specified on the command line to request help.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseHelp(
this CommandLineBuilder builder,
params string[] helpAliases)
{
return builder.UseHelp(new HelpOption(helpAliases, () => builder.LocalizationResources));
}
/// <summary>
/// Configures the application to show help when one of the specified option aliases are used on the command line.
/// </summary>
/// <remarks>The specified aliases will override the default values.</remarks>
/// <param name="builder">A command line builder.</param>
/// <param name="customize">A delegate that will be called to customize help if help is requested.</param>
/// <param name="maxWidth">Maximum output width for default help builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseHelp(
this CommandLineBuilder builder,
Action<HelpContext> customize,
int? maxWidth = null)
{
builder.CustomizeHelpLayout(customize);
if (builder.HelpOption is null)
{
builder.UseHelp(new HelpOption(() => builder.LocalizationResources), maxWidth);
}
return builder;
}
internal static CommandLineBuilder UseHelp(
this CommandLineBuilder builder,
HelpOption helpOption,
int? maxWidth = null)
{
if (builder.HelpOption is null)
{
builder.HelpOption = helpOption;
builder.Command.AddGlobalOption(helpOption);
builder.MaxHelpWidth = maxWidth;
builder.AddMiddleware(async (context, next) =>
{
if (!ShowHelp(context, builder.HelpOption))
{
await next(context);
}
}, MiddlewareOrderInternal.HelpOption);
}
return builder;
}
/// <summary>
/// Specifies an <see cref="HelpBuilder"/> to be used to format help output when help is requested.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="getHelpBuilder">A delegate that returns an instance of <see cref="HelpBuilder"/></param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static TBuilder UseHelpBuilder<TBuilder>(this TBuilder builder,
Func<BindingContext, HelpBuilder> getHelpBuilder)
where TBuilder : CommandLineBuilder
{
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.UseHelpBuilderFactory(getHelpBuilder);
return builder;
}
/// <summary>
/// Adds a middleware delegate to the invocation pipeline called before a command handler is invoked.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="middleware">A delegate that will be invoked before a call to a command handler.</param>
/// <param name="order">A value indicating the order in which the added delegate will be invoked relative to others in the pipeline.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder AddMiddleware(
this CommandLineBuilder builder,
InvocationMiddleware middleware,
MiddlewareOrder order = MiddlewareOrder.Default)
{
builder.AddMiddleware(
middleware,
order);
return builder;
}
/// <summary>
/// Adds a middleware delegate to the invocation pipeline called before a command handler is invoked.
/// </summary>
/// <param name="onInvoke">A delegate that will be invoked before a call to a command handler.</param>
/// <param name="order">A value indicating the order in which the added delegate will be invoked relative to others in the pipeline.</param>
/// <param name="builder">A command line builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder AddMiddleware(
this CommandLineBuilder builder,
Action<InvocationContext> onInvoke,
MiddlewareOrder order = MiddlewareOrder.Default)
{
builder.AddMiddleware(async (context, next) =>
{
onInvoke(context);
await next(context);
}, order);
return builder;
}
/// <summary>
/// Enables the use of the <c>[parse]</c> directive, which when specified on the command line will short circuit normal command handling and display a diagram explaining the parse result for the command line input.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="errorExitCode">If the parse result contains errors, this exit code will be used when the process exits.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseParseDirective(
this CommandLineBuilder builder,
int? errorExitCode = null)
{
builder.AddMiddleware(async (context, next) =>
{
if (context.ParseResult.Directives.Contains("parse"))
{
context.InvocationResult = new ParseDirectiveResult(errorExitCode);
}
else
{
await next(context);
}
}, MiddlewareOrderInternal.ParseDirective);
return builder;
}
/// <summary>
/// Configures the command line to write error information to standard error when there are errors parsing command line input.
/// </summary>
/// <param name="errorExitCode">The exit code to use when parser errors occur.</param>
/// <param name="builder">A command line builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseParseErrorReporting(
this CommandLineBuilder builder,
int? errorExitCode = null)
{
builder.AddMiddleware(async (context, next) =>
{
if (context.ParseResult.Errors.Count > 0)
{
context.InvocationResult = new ParseErrorResult(errorExitCode);
}
else
{
await next(context);
}
}, MiddlewareOrderInternal.ParseErrorReporting);
return builder;
}
/// <summary>
/// Enables the use of the <c>[suggest]</c> directive which when specified in command line input short circuits normal command handling and writes a newline-delimited list of suggestions suitable for use by most shells to provide command line completions.
/// </summary>
/// <remarks>The <c>dotnet-suggest</c> tool requires the suggest directive to be enabled for an application to provide completions.</remarks>
/// <param name="builder">A command line builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseSuggestDirective(
this CommandLineBuilder builder)
{
builder.AddMiddleware(async (context, next) =>
{
if (context.ParseResult.Directives.TryGetValues("suggest", out var values))
{
int position;
if (values.FirstOrDefault() is { } positionString)
{
position = int.Parse(positionString);
}
else
{
position = context.ParseResult.CommandLineText?.Length ?? 0;
}
context.InvocationResult = new SuggestDirectiveResult(position);
}
else
{
await next(context);
}
}, MiddlewareOrderInternal.SuggestDirective);
return builder;
}
/// <summary>
/// Configures the application to provide alternative suggestions when a parse error is detected.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="maxLevenshteinDistance">The maximum Levenshtein distance for suggestions based on detected typos in command line input.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseTypoCorrections(
this CommandLineBuilder builder,
int maxLevenshteinDistance = 3)
{
builder.AddMiddleware(async (context, next) =>
{
if (context.ParseResult.CommandResult.Command.TreatUnmatchedTokensAsErrors &&
context.ParseResult.UnmatchedTokens.Count > 0)
{
var typoCorrection = new TypoCorrection(maxLevenshteinDistance);
typoCorrection.ProvideSuggestions(context.ParseResult, context.Console);
}
await next(context);
}, MiddlewareOrderInternal.TypoCorrection);
return builder;
}
/// <summary>
/// Specifies localization resources to be used when displaying help, error messages, and other user-facing strings.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="validationMessages">The localizations resources to use.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseLocalizationResources(
this CommandLineBuilder builder,
LocalizationResources validationMessages)
{
builder.LocalizationResources = validationMessages;
return builder;
}
/// <summary>
/// Specifies a delegate used to replace any token prefixed with <code>@</code> with zero or more other tokens, prior to parsing.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <param name="replaceToken">Replaces the specified token with any number of other tokens.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseTokenReplacer(
this CommandLineBuilder builder,
TryReplaceToken? replaceToken)
{
builder.TokenReplacer = replaceToken;
return builder;
}
/// <summary>
/// Enables the use of a option (defaulting to the alias <c>--version</c>) which when specified in command line input will short circuit normal command handling and instead write out version information before exiting.
/// </summary>
/// <param name="builder">A command line builder.</param>
/// <returns>The same instance of <see cref="CommandLineBuilder"/>.</returns>
public static CommandLineBuilder UseVersionOption(
this CommandLineBuilder builder)
{
if (builder.VersionOption is not null)
{
return builder;
}
var versionOption = new VersionOption(builder);
builder.VersionOption = versionOption;
builder.Command.AddOption(versionOption);
builder.AddMiddleware(async (context, next) =>
{
if (context.ParseResult.FindResultFor(versionOption) is { })
{
if (context.ParseResult.Errors.Any(e => e.SymbolResult?.Symbol is VersionOption))
{
context.InvocationResult = new ParseErrorResult(null);
}
else
{
context.Console.Out.WriteLine(_assemblyVersion.Value);
}
}
else
{
await next(context);
}
}, MiddlewareOrderInternal.VersionOption);
return builder;
}
/// <inheritdoc cref="UseVersionOption(System.CommandLine.Builder.CommandLineBuilder)"/>
/// <param name="aliases">One or more aliases to use instead of the default to signal that version information should be displayed.</param>
/// <param name="builder">A command line builder.</param>
public static CommandLineBuilder UseVersionOption(
this CommandLineBuilder builder,
params string[] aliases)
{
var command = builder.Command;
if (builder.VersionOption is not null)
{
return builder;
}
var versionOption = new VersionOption(aliases, builder);
builder.VersionOption = versionOption;
command.AddOption(versionOption);
builder.AddMiddleware(async (context, next) =>
{
if (context.ParseResult.FindResultFor(versionOption) is { })
{
if (context.ParseResult.Errors.Any(e => e.SymbolResult?.Symbol is VersionOption))
{
context.InvocationResult = new ParseErrorResult(null);
}
else
{
context.Console.Out.WriteLine(_assemblyVersion.Value);
}
}
else
{
await next(context);
}
}, MiddlewareOrderInternal.VersionOption);
return builder;
}
private static bool ShowHelp(
InvocationContext context,
Option helpOption)
{
if (context.ParseResult.FindResultFor(helpOption) is { })
{
context.InvocationResult = new HelpResult();
return true;
}
return false;
}
}
}