Skip to content
Merged
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
2 changes: 1 addition & 1 deletion DevProxy.Abstractions/DevProxy.Abstractions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<PackageReference Include="Microsoft.OpenApi.Readers" Version="1.6.24" />
<PackageReference Include="Newtonsoft.Json.Schema" Version="4.0.1" />
<PackageReference Include="Prompty.Core" Version="0.2.2-beta" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta5.25306.1" />
<PackageReference Include="Unobtanium.Web.Proxy" Version="0.1.5" />
</ItemGroup>

Expand Down
22 changes: 18 additions & 4 deletions DevProxy.Abstractions/Extensions/CommandLineExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace System.CommandLine.Parsing;

public static class CommandLineExtensions
{
public static T? GetValueForOption<T>(this ParseResult parseResult, string optionName, IReadOnlyList<Option> options)
public static T? GetValue<T>(this ParseResult parseResult, string optionName, IList<Option> options)
{
ArgumentNullException.ThrowIfNull(parseResult);

Expand All @@ -20,7 +20,21 @@ public static class CommandLineExtensions
throw new InvalidOperationException($"Could not find option with name {optionName} and value type {typeof(T).Name}");
}

return parseResult.GetValueForOption(option);
return parseResult.GetValue(option);
}

public static T? GetValueOrDefault<T>(this ParseResult parseResult, string optionName)
{
ArgumentNullException.ThrowIfNull(parseResult);

try
{
return parseResult.GetValue<T>(optionName);
}
catch (Exception ex) when (ex is InvalidCastException or ArgumentException or InvalidOperationException)
{
return default;
}
}

public static IEnumerable<T> OrderByName<T>(this IEnumerable<T> symbols) where T : Symbol
Expand All @@ -37,7 +51,7 @@ public static void AddCommands(this Command command, IEnumerable<Command> subcom

foreach (var subcommand in subcommands)
{
command.AddCommand(subcommand);
command.Add(subcommand);
}
}

Expand All @@ -48,7 +62,7 @@ public static void AddOptions(this Command command, IEnumerable<Option> options)

foreach (var option in options)
{
command.AddOption(option);
command.Add(option);
}
}

Expand Down
9 changes: 3 additions & 6 deletions DevProxy.Abstractions/Proxy/ProxyEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using DevProxy.Abstractions.Utils;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Text.Json.Serialization;
using Titanium.Web.Proxy.EventArguments;

Expand Down Expand Up @@ -48,12 +47,10 @@ public class InitArgs
public required IServiceProvider ServiceProvider { get; init; }
}

public class OptionsLoadedArgs(InvocationContext context, IReadOnlyList<Option> options)
public class OptionsLoadedArgs(ParseResult parseResult)
{
public InvocationContext Context { get; set; } = context ??
throw new ArgumentNullException(nameof(context));
public IReadOnlyList<Option> Options { get; set; } = options ??
throw new ArgumentNullException(nameof(options));
public ParseResult ParseResult { get; set; } = parseResult ??
throw new ArgumentNullException(nameof(parseResult));
}

public class RequestLog
Expand Down
6 changes: 3 additions & 3 deletions DevProxy.Abstractions/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@
},
"System.CommandLine": {
"type": "Direct",
"requested": "[2.0.0-beta4.22272.1, )",
"resolved": "2.0.0-beta4.22272.1",
"contentHash": "1uqED/q2H0kKoLJ4+hI2iPSBSEdTuhfCYADeJrAqERmiGQ2NNacYKRNEQ+gFbU4glgVyK8rxI+ZOe1onEtr/Pg=="
"requested": "[2.0.0-beta5.25306.1, )",
"resolved": "2.0.0-beta5.25306.1",
"contentHash": "ce0wuowuh13Cd7GXqLCq77/YWlxQMxrVCMIO/2/QUP6CdP/JWnlYSN/N3/55wwGsUwa9CvPuT8ddjgyypUr5ag=="
},
"Unobtanium.Web.Proxy": {
"type": "Direct",
Expand Down
20 changes: 10 additions & 10 deletions DevProxy.Plugins/Behavior/GenericRandomErrorPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,24 @@ public override async Task InitializeAsync(InitArgs e)

public override Option[] GetOptions()
{
var _rateOption = new Option<int?>(_rateOptionName, "The percentage of chance that a request will fail");
_rateOption.AddAlias("-f");
_rateOption.ArgumentHelpName = "failure rate";
_rateOption.AddValidator((input) =>
var _rateOption = new Option<int?>(_rateOptionName, "-f")
{
Description = "The percentage of chance that a request will fail",
HelpName = "failure-rate"
};
_rateOption.Validators.Add((input) =>
{
try
{
var value = input.GetValueForOption(_rateOption);
var value = input.GetValue(_rateOption);
if (value.HasValue && (value < 0 || value > 100))
{
input.ErrorMessage = $"{value} is not a valid failure rate. Specify a number between 0 and 100";
input.AddError($"{value} is not a valid failure rate. Specify a number between 0 and 100");
}
}
catch (InvalidOperationException ex)
{
input.ErrorMessage = ex.Message;
input.AddError(ex.Message);
}
});

Expand All @@ -97,9 +99,7 @@ public override void OptionsLoaded(OptionsLoadedArgs e)

base.OptionsLoaded(e);

var context = e.Context;

var rate = context.ParseResult.GetValueForOption<int?>(_rateOptionName, e.Options);
var rate = e.ParseResult.GetValueOrDefault<int?>(_rateOptionName);
if (rate is not null)
{
Configuration.Rate = rate.Value;
Expand Down
30 changes: 16 additions & 14 deletions DevProxy.Plugins/Behavior/GraphRandomErrorPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,29 +105,31 @@ public sealed class GraphRandomErrorPlugin(

public override Option[] GetOptions()
{
var _allowedErrors = new Option<IEnumerable<int>>(_allowedErrorsOptionName, "List of errors that Dev Proxy may produce")
var _allowedErrors = new Option<IEnumerable<int>>(_allowedErrorsOptionName, "-a")
{
ArgumentHelpName = "allowed errors",
AllowMultipleArgumentsPerToken = true
AllowMultipleArgumentsPerToken = true,
Description = "List of errors that Dev Proxy may produce",
HelpName = "allowed-errors"
};
_allowedErrors.AddAlias("-a");

var _rateOption = new Option<int?>(_rateOptionName, "The percentage of chance that a request will fail");
_rateOption.AddAlias("-f");
_rateOption.ArgumentHelpName = "failure rate";
_rateOption.AddValidator((input) =>
var _rateOption = new Option<int?>(_rateOptionName, "-f")
{
Description = "The percentage of chance that a request will fail",
HelpName = "failure-rate"
};
_rateOption.Validators.Add((input) =>
{
try
{
var value = input.GetValueForOption(_rateOption);
var value = input.GetValue(_rateOption);
if (value.HasValue && (value < 0 || value > 100))
{
input.ErrorMessage = $"{value} is not a valid failure rate. Specify a number between 0 and 100";
input.AddError($"{value} is not a valid failure rate. Specify a number between 0 and 100");
}
}
catch (InvalidOperationException ex)
{
input.ErrorMessage = ex.Message;
input.AddError(ex.Message);
}
});

Expand All @@ -140,10 +142,10 @@ public override void OptionsLoaded(OptionsLoadedArgs e)

base.OptionsLoaded(e);

var context = e.Context;
var parseResult = e.ParseResult;

// Configure the allowed errors
var allowedErrors = context.ParseResult.GetValueForOption<IEnumerable<int>?>(_allowedErrorsOptionName, e.Options);
var allowedErrors = parseResult.GetValueOrDefault<IEnumerable<int>?>(_allowedErrorsOptionName);
if (allowedErrors?.Any() ?? false)
{
Configuration.AllowedErrors = [.. allowedErrors];
Expand All @@ -157,7 +159,7 @@ public override void OptionsLoaded(OptionsLoadedArgs e)
}
}

var rate = context.ParseResult.GetValueForOption<int?>(_rateOptionName, e.Options);
var rate = parseResult.GetValueOrDefault<int?>(_rateOptionName);
if (rate is not null)
{
Configuration.Rate = rate.Value;
Expand Down
2 changes: 1 addition & 1 deletion DevProxy.Plugins/DevProxy.Plugins.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
<Private>false</Private>
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1">
<PackageReference Include="System.CommandLine" Version="2.0.0-beta5.25306.1">
<Private>false</Private>
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
Expand Down
17 changes: 9 additions & 8 deletions DevProxy.Plugins/Mocking/MockResponsePlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,16 @@ public override async Task InitializeAsync(InitArgs e)

public override Option[] GetOptions()
{
var _noMocks = new Option<bool?>(_noMocksOptionName, "Disable loading mock requests")
var _noMocks = new Option<bool?>(_noMocksOptionName, "-n")
{
ArgumentHelpName = "no mocks"
Description = "Disable loading mock requests",
HelpName = "no-mocks"
};
_noMocks.AddAlias("-n");

var _mocksFile = new Option<string?>(_mocksFileOptionName, "Provide a file populated with mock responses")
var _mocksFile = new Option<string?>(_mocksFileOptionName)
{
ArgumentHelpName = "mocks file"
Description = "Provide a file populated with mock responses",
HelpName = "mocks-file"
};

return [_noMocks, _mocksFile];
Expand All @@ -92,10 +93,10 @@ public override void OptionsLoaded(OptionsLoadedArgs e)

base.OptionsLoaded(e);

var context = e.Context;
var parseResult = e.ParseResult;

// allow disabling of mocks as a command line option
var noMocks = context.ParseResult.GetValueForOption<bool?>(_noMocksOptionName, e.Options);
var noMocks = parseResult.GetValueOrDefault<bool?>(_noMocksOptionName);
if (noMocks.HasValue)
{
Configuration.NoMocks = noMocks.Value;
Expand All @@ -107,7 +108,7 @@ public override void OptionsLoaded(OptionsLoadedArgs e)
}

// update the name of the mocks file to load from if supplied
var mocksFile = context.ParseResult.GetValueForOption<string?>(_mocksFileOptionName, e.Options);
var mocksFile = parseResult.GetValueOrDefault<string?>(_mocksFileOptionName);
if (mocksFile is not null)
{
Configuration.MocksFile = mocksFile;
Expand Down
13 changes: 7 additions & 6 deletions DevProxy.Plugins/Reporting/ExecutionSummaryPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,16 @@ public sealed class ExecutionSummaryPlugin(

public override Option[] GetOptions()
{
var groupBy = new Option<SummaryGroupBy?>(_groupByOptionName, "Specifies how the information should be grouped in the summary. Available options: `url` (default), `messageType`.")
var groupBy = new Option<SummaryGroupBy?>(_groupByOptionName)
{
ArgumentHelpName = "summary-group-by"
Description = "Specifies how the information should be grouped in the summary. Available options: `url` (default), `messageType`.",
HelpName = "summary-group-by"
};
groupBy.AddValidator(input =>
groupBy.Validators.Add(input =>
{
if (!Enum.TryParse<SummaryGroupBy>(input.Tokens[0].Value, true, out var groupBy))
{
input.ErrorMessage = $"{input.Tokens[0].Value} is not a valid option to group by. Allowed values are: {string.Join(", ", Enum.GetNames<SummaryGroupBy>())}";
input.AddError($"{input.Tokens[0].Value} is not a valid option to group by. Allowed values are: {string.Join(", ", Enum.GetNames<SummaryGroupBy>())}");
}
});

Expand All @@ -63,9 +64,9 @@ public override void OptionsLoaded(OptionsLoadedArgs e)

base.OptionsLoaded(e);

var context = e.Context;
var parseResult = e.ParseResult;

var groupBy = context.ParseResult.GetValueForOption<SummaryGroupBy?>(_groupByOptionName, e.Options);
var groupBy = parseResult.GetValueOrDefault<SummaryGroupBy?>(_groupByOptionName);
if (groupBy is not null)
{
Configuration.GroupBy = groupBy.Value;
Expand Down
8 changes: 4 additions & 4 deletions DevProxy.Plugins/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@
},
"System.CommandLine": {
"type": "Direct",
"requested": "[2.0.0-beta4.22272.1, )",
"resolved": "2.0.0-beta4.22272.1",
"contentHash": "1uqED/q2H0kKoLJ4+hI2iPSBSEdTuhfCYADeJrAqERmiGQ2NNacYKRNEQ+gFbU4glgVyK8rxI+ZOe1onEtr/Pg=="
"requested": "[2.0.0-beta5.25306.1, )",
"resolved": "2.0.0-beta5.25306.1",
"contentHash": "ce0wuowuh13Cd7GXqLCq77/YWlxQMxrVCMIO/2/QUP6CdP/JWnlYSN/N3/55wwGsUwa9CvPuT8ddjgyypUr5ag=="
},
"System.IdentityModel.Tokens.Jwt": {
"type": "Direct",
Expand Down Expand Up @@ -603,7 +603,7 @@
"Microsoft.OpenApi.Readers": "[1.6.24, )",
"Newtonsoft.Json.Schema": "[4.0.1, )",
"Prompty.Core": "[0.2.2-beta, )",
"System.CommandLine": "[2.0.0-beta4.22272.1, )",
"System.CommandLine": "[2.0.0-beta5.25306.1, )",
"Unobtanium.Web.Proxy": "[0.1.5, )"
}
}
Expand Down
14 changes: 8 additions & 6 deletions DevProxy/Commands/CertCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using DevProxy.Abstractions.Utils;
using DevProxy.Proxy;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.Diagnostics;
using Titanium.Web.Proxy.Helpers;
Expand All @@ -15,7 +14,10 @@ namespace DevProxy.Commands;
sealed class CertCommand : Command
{
private readonly ILogger _logger;
private readonly Option<bool> _forceOption = new(["--force", "-f"], "Don't prompt for confirmation when removing the certificate");
private readonly Option<bool> _forceOption = new("--force", "-f")
{
Description = "Don't prompt for confirmation when removing the certificate"
};

public CertCommand(ILogger<CertCommand> logger) :
base("cert", "Manage the Dev Proxy certificate")
Expand All @@ -28,10 +30,10 @@ public CertCommand(ILogger<CertCommand> logger) :
private void ConfigureCommand()
{
var certEnsureCommand = new Command("ensure", "Ensure certificates are setup (creates root if required). Also makes root certificate trusted.");
certEnsureCommand.SetHandler(EnsureCertAsync);
certEnsureCommand.SetAction(async _ => await EnsureCertAsync());

var certRemoveCommand = new Command("remove", "Remove the certificate from Root Store");
certRemoveCommand.SetHandler(RemoveCert);
certRemoveCommand.SetAction(RemoveCert);
certRemoveCommand.AddOptions(new[] { _forceOption }.OrderByName());

this.AddCommands(new List<Command>
Expand Down Expand Up @@ -59,13 +61,13 @@ private async Task EnsureCertAsync()
_logger.LogTrace("EnsureCertAsync() finished");
}

public void RemoveCert(InvocationContext invocationContext)
public void RemoveCert(ParseResult parseResult)
{
_logger.LogTrace("RemoveCert() called");

try
{
var isForced = invocationContext.ParseResult.GetValueForOption(_forceOption);
var isForced = parseResult.GetValue(_forceOption);
if (!isForced)
{
var isConfirmed = PromptConfirmation("Do you want to remove the root certificate", acceptByDefault: false);
Expand Down
Loading