Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion DevProxy.Abstractions/Plugins/BasePlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,15 @@ public override async Task InitializeAsync(InitArgs e, CancellationToken cancell
{
if (Logger.IsEnabled(LogLevel.Error))
{
Logger.LogError("Plugin configuration validation failed with the following errors: {Errors}", string.Join(", ", ValidationErrors));
var docsLink = DocsLinks.ForPlugin(GetType());
if (docsLink is null)
{
Logger.LogError("Plugin configuration validation failed with the following errors: {Errors}", string.Join(", ", ValidationErrors));
}
else
{
Logger.LogError("Plugin configuration validation failed with the following errors: {Errors}. Docs: {DocsUrl}", string.Join(", ", ValidationErrors).TrimEnd('.'), docsLink);
}
}
}
}
Expand Down
43 changes: 43 additions & 0 deletions DevProxy.Abstractions/Utils/DocsLinks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Reflection;

namespace DevProxy.Abstractions.Utils;

/// <summary>
/// Builds stable documentation shortlinks (https://go.devproxy.net?go=&lt;code&gt;).
/// The shortlink service redirects codes to the actual documentation pages,
/// so the CLI never hard-codes documentation paths.
/// </summary>
public static class DocsLinks
{
private const string BaseUrl = "https://go.devproxy.net?go=";
private const string BuiltInPluginsAssemblyName = "DevProxy.Plugins";

public static string Api { get; } = Get("api");
public static string Cli { get; } = Get("cli");

public static string Get(string code)
{
ArgumentException.ThrowIfNullOrWhiteSpace(code);
return BaseUrl + Uri.EscapeDataString(code.ToLowerInvariant());
}

public static bool IsBuiltInPluginAssembly(Assembly assembly)
{
ArgumentNullException.ThrowIfNull(assembly);
return string.Equals(assembly.GetName().Name, BuiltInPluginsAssemblyName, StringComparison.Ordinal);
}

/// <summary>
/// Returns the documentation link for a plugin, or null if the plugin
/// isn't shipped with Dev Proxy and has no canonical documentation page.
/// </summary>
public static string? ForPlugin(Type pluginType)
{
ArgumentNullException.ThrowIfNull(pluginType);
return IsBuiltInPluginAssembly(pluginType.Assembly) ? Get(pluginType.Name) : null;
}
}
80 changes: 80 additions & 0 deletions DevProxy.Tests/HelpDocsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using DevProxy.Abstractions.Utils;
using DevProxy.Commands;
using System.CommandLine;
using Xunit;

namespace DevProxy.Tests;

public sealed class HelpDocsTests
{
private static RootCommand CreateRootCommand(out Command pluginCommand)
{
var root = new RootCommand();
var api = new Command("api");
var show = new Command("show");
show.SetAction(_ => { });
api.Subcommands.Add(show);
root.Subcommands.Add(api);

pluginCommand = new Command("mocks");
var pluginSubcommand = new Command("from-http-responses");
pluginSubcommand.SetAction(_ => { });
pluginCommand.Subcommands.Add(pluginSubcommand);
root.Subcommands.Add(pluginCommand);

return root;
}

[Fact]
public void GetLink_RootCommand_ReturnsCliLink()
{
var root = CreateRootCommand(out _);

Assert.Equal("https://go.devproxy.net?go=cli", HelpDocs.GetLink(root.Parse("")));
}

[Fact]
public void GetLink_LeafCommand_ReturnsCommandPathLink()
{
var root = CreateRootCommand(out _);

Assert.Equal("https://go.devproxy.net?go=cli-api-show", HelpDocs.GetLink(root.Parse("api show")));
}

[Fact]
public void GetLink_GroupCommand_ReturnsCliLink()
{
var root = CreateRootCommand(out _);

Assert.Equal("https://go.devproxy.net?go=cli", HelpDocs.GetLink(root.Parse("api")));
}

[Fact]
public void GetLink_CommandWithExplicitLink_AppliesToSubcommands()
{
var root = CreateRootCommand(out var pluginCommand);
HelpDocs.Set(pluginCommand, DocsLinks.Get("MockResponsePlugin"));

Assert.Equal("https://go.devproxy.net?go=mockresponseplugin", HelpDocs.GetLink(root.Parse("mocks")));
Assert.Equal("https://go.devproxy.net?go=mockresponseplugin", HelpDocs.GetLink(root.Parse("mocks from-http-responses")));
}

[Fact]
public void GetLink_CommandWithoutDocs_ReturnsNull()
{
var root = CreateRootCommand(out var pluginCommand);
HelpDocs.Set(pluginCommand, null);

Assert.Null(HelpDocs.GetLink(root.Parse("mocks from-http-responses")));
}

[Fact]
public void ForPlugin_ThirdPartyPlugin_ReturnsNull()
{
Assert.Null(DocsLinks.ForPlugin(typeof(HelpDocsTests)));
}
}
40 changes: 40 additions & 0 deletions DevProxy.Tests/PluginCommandHelpTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using DevProxy.Commands;
using Xunit;

namespace DevProxy.Tests;

[Collection("console-output")]
public sealed class PluginCommandHelpTests
{
[Theory]
[InlineData(new[] { "plugin", "--help" }, "https://go.devproxy.net?go=cli")]
[InlineData(new[] { "plugin", "list", "--help" }, "https://go.devproxy.net?go=cli-plugin-list")]
public async Task RunStandaloneAsync_Help_PrintsDocsFooterAfterExamples(string[] args, string expectedLink)
{
var originalOut = Console.Out;
using var output = new StringWriter();
Console.SetOut(output);
int exitCode;
try
{
exitCode = await PluginCommand.RunStandaloneAsync([.. args, "--log-level", "None"]);
}
finally
{
Console.SetOut(originalOut);
}

Assert.Equal(0, exitCode);
var text = output.ToString();
var lines = text.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
Assert.Equal($"Docs: {expectedLink}", lines[^1]);
if (args.Contains("list"))
{
Assert.True(text.IndexOf("Examples:", StringComparison.Ordinal) < text.IndexOf("Docs:", StringComparison.Ordinal));
}
}
}
5 changes: 4 additions & 1 deletion DevProxy/Commands/ApiCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,8 @@ private void PrintApiInfo(OutputFormat outputFormat)
requestBody = schema?.RequestBody,
responses = schema?.Responses
};
})
}),
docs = DocsLinks.Api
}, ProxyUtils.JsonSerializerOptions);
_logger.LogStructuredOutput(json);
}
Expand All @@ -186,6 +187,8 @@ private void PrintApiInfo(OutputFormat outputFormat)
{
_logger.LogInformation(" {Method,-6} {Path,-30} {Description}", endpoint.Method, endpoint.Path, FormatDescription(endpoint));
}
_logger.LogInformation("");
_logger.LogInformation("Docs: {DocsUrl}", DocsLinks.Api);
}
}
}
Expand Down
18 changes: 5 additions & 13 deletions DevProxy/Commands/DevProxyCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -900,10 +900,11 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions)
ActivatorUtilities.CreateInstance<ValidateCommand>(_serviceProvider),
ActivatorUtilities.CreateInstance<PluginCommand>(_serviceProvider)
};
var pluginCommands = _plugins.SelectMany(p => p.GetCommands());
foreach (var group in pluginCommands.GroupBy(c => c.Name))
var pluginCommands = _plugins.SelectMany(p => p.GetCommands().Select(c => (Plugin: p, Command: c)));
foreach (var group in pluginCommands.GroupBy(pc => pc.Command.Name))
{
var command = group.First();
var (plugin, command) = group.First();
HelpDocs.Set(command, DocsLinks.ForPlugin(plugin.GetType()));
commands.Add(command);
if (group.Count() > 1)
{
Expand All @@ -922,20 +923,11 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions)
]);
HelpExamples.Install(this);

CustomizeHelp();
DevProxyHelpAction.Install(this);

SetAction(InvokeAsync);
}

private void CustomizeHelp()
{
var helpOption = Options.OfType<HelpOption>().FirstOrDefault();
if (helpOption?.Action is SynchronousCommandLineAction currentAction)
{
helpOption.Action = new DevProxyHelpAction(currentAction);
}
}

internal static void ApplyDiscoverOption(IProxyConfiguration proxyConfiguration, bool? isDiscover)
{
// Discovery mode requires recording, but --discover false must not enable it
Expand Down
31 changes: 26 additions & 5 deletions DevProxy/Commands/DevProxyHelpAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,39 @@ namespace DevProxy.Commands;

sealed class DevProxyHelpAction(SynchronousCommandLineAction originalAction) : SynchronousCommandLineAction
{
// Wraps the root command's current help action (e.g. the examples action)
// so the docs footer is printed after it.
public static void Install(RootCommand rootCommand)
{
var helpOption = rootCommand.Options.OfType<HelpOption>().FirstOrDefault();
if (helpOption?.Action is SynchronousCommandLineAction currentAction)
{
helpOption.Action = new DevProxyHelpAction(currentAction);
}
}

public override int Invoke(ParseResult parseResult)
{
originalAction.Invoke(parseResult);

if (parseResult.CommandResult.Command is not RootCommand)
var output = Console.Out;

if (parseResult.CommandResult.Command is RootCommand)
{
return 0;
WriteRootHelp(output);
}

var output = Console.Out;
var docsLink = HelpDocs.GetLink(parseResult);
if (docsLink is not null)
{
output.WriteLine($"Docs: {docsLink}");
Comment thread
waldekmastykarz marked this conversation as resolved.
Resolved
}

return 0;
}

private static void WriteRootHelp(TextWriter output)
{
output.WriteLine();
output.WriteLine(" Additional commands may be available depending on configured plugins.");
output.WriteLine(" Use -c <config-file> to load a specific configuration.");
Expand All @@ -36,7 +58,6 @@ public override int Invoke(ParseResult parseResult)
output.WriteLine(" 0 Success");
output.WriteLine(" 1 Runtime error");
output.WriteLine(" 2 Invalid input or usage");

return 0;
output.WriteLine();
}
}
57 changes: 57 additions & 0 deletions DevProxy/Commands/HelpDocs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using DevProxy.Abstractions.Utils;
using System.CommandLine;
using System.CommandLine.Parsing;
using System.Runtime.CompilerServices;

namespace DevProxy.Commands;

static class HelpDocs
{
// Commands with an explicit docs link (for example contributed by plugins).
// A null value means the command has no canonical docs page.
private static readonly ConditionalWeakTable<Command, StrongBox<string?>> _links = new();

public static void Set(Command command, string? link, bool recursive = true)
{
_links.AddOrUpdate(command, new(link));
if (!recursive)
{
return;
}

foreach (var subcommand in command.Subcommands)
{
Set(subcommand, link, recursive);
}
}

public static string? GetLink(ParseResult parseResult)
{
var command = parseResult.CommandResult.Command;
if (_links.TryGetValue(command, out var link))
{
return link.Value;
}

if (command is RootCommand || command.Action is null)
{
return DocsLinks.Cli;
}

var path = new List<string>();
for (var result = parseResult.CommandResult; result is not null; result = result.Parent as CommandResult)
{
if (result.Command is RootCommand)
{
break;
}
path.Insert(0, result.Command.Name);
}

return DocsLinks.Get($"cli-{string.Join('-', path)}");
}
}
1 change: 1 addition & 0 deletions DevProxy/Commands/PluginCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ internal static async Task<int> RunStandaloneAsync(string[] args)
new PluginCommand(loggerFactory.CreateLogger<PluginCommand>())
};
HelpExamples.Install(rootCommand);
DevProxyHelpAction.Install(rootCommand);

var parseResult = rootCommand.Parse(args);
if (parseResult.Action is ParseErrorAction parseErrorAction)
Expand Down
Loading
Loading