|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System.CommandLine; |
| 6 | +using System.CommandLine.Help; |
| 7 | +using System.CommandLine.Invocation; |
| 8 | +using System.Runtime.CompilerServices; |
| 9 | + |
| 10 | +namespace DevProxy.Commands; |
| 11 | + |
| 12 | +static class HelpExamples |
| 13 | +{ |
| 14 | + private static readonly ConditionalWeakTable<Command, string[]> _examples = new(); |
| 15 | + |
| 16 | + public static void Add(Command command, string[] examples) |
| 17 | + { |
| 18 | + _examples.AddOrUpdate(command, examples); |
| 19 | + } |
| 20 | + |
| 21 | + public static void Install(RootCommand rootCommand) |
| 22 | + { |
| 23 | + var helpOption = rootCommand.Options.OfType<HelpOption>().First(); |
| 24 | + helpOption.Action = new ExamplesHelpAction(); |
| 25 | + } |
| 26 | + |
| 27 | + private sealed class ExamplesHelpAction : SynchronousCommandLineAction |
| 28 | + { |
| 29 | + public override int Invoke(ParseResult parseResult) |
| 30 | + { |
| 31 | + new HelpAction().Invoke(parseResult); |
| 32 | + |
| 33 | + var command = parseResult.CommandResult.Command; |
| 34 | + if (_examples.TryGetValue(command, out var examples)) |
| 35 | + { |
| 36 | + var output = parseResult.Configuration.Output; |
| 37 | + output.WriteLine("Examples:"); |
| 38 | + foreach (var example in examples) |
| 39 | + { |
| 40 | + output.Write(" "); |
| 41 | + output.WriteLine(example); |
| 42 | + } |
| 43 | + output.WriteLine(); |
| 44 | + } |
| 45 | + return 0; |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments