|
10 | 10 | using DevProxy.Plugins.Models; |
11 | 11 | using Microsoft.Extensions.Configuration; |
12 | 12 | using Microsoft.Extensions.DependencyInjection; |
| 13 | +using Microsoft.Extensions.FileSystemGlobbing; |
13 | 14 | using Microsoft.Extensions.Logging; |
14 | 15 | using System.Collections.Concurrent; |
15 | 16 | using System.CommandLine; |
@@ -60,6 +61,8 @@ public class MockResponsePlugin( |
60 | 61 | private readonly ConcurrentDictionary<string, int> _appliedMocks = []; |
61 | 62 |
|
62 | 63 | private MockResponsesLoader? _loader; |
| 64 | + private Argument<IEnumerable<string>>? _httpResponseFilesArgument; |
| 65 | + private Option<string>? _httpResponseMocksFileNameOption; |
63 | 66 |
|
64 | 67 | public override string Name => nameof(MockResponsePlugin); |
65 | 68 |
|
@@ -89,6 +92,33 @@ public override Option[] GetOptions() |
89 | 92 | return [_noMocks, _mocksFile]; |
90 | 93 | } |
91 | 94 |
|
| 95 | + public override Command[] GetCommands() |
| 96 | + { |
| 97 | + var mocksCommand = new Command("mocks", "Manage mock responses"); |
| 98 | + var mocksFromHttpResponseCommand = new Command("from-http-responses", "Create a mock response from HTTP responses"); |
| 99 | + _httpResponseFilesArgument = new Argument<IEnumerable<string>>("http-response-files") |
| 100 | + { |
| 101 | + Arity = ArgumentArity.OneOrMore, |
| 102 | + Description = "Glob pattern to the file(s) containing HTTP responses to create mock responses from", |
| 103 | + }; |
| 104 | + mocksFromHttpResponseCommand.Add(_httpResponseFilesArgument); |
| 105 | + _httpResponseMocksFileNameOption = new Option<string>("--mocks-file") |
| 106 | + { |
| 107 | + HelpName = "mocks file", |
| 108 | + Arity = ArgumentArity.ExactlyOne, |
| 109 | + Description = "File to save the generated mock responses to", |
| 110 | + Required = true |
| 111 | + }; |
| 112 | + mocksFromHttpResponseCommand.Add(_httpResponseMocksFileNameOption); |
| 113 | + mocksFromHttpResponseCommand.SetAction(GenerateMocksFromHttpResponsesAsync); |
| 114 | + |
| 115 | + mocksCommand.AddCommands(new[] |
| 116 | + { |
| 117 | + mocksFromHttpResponseCommand |
| 118 | + }.OrderByName()); |
| 119 | + return [mocksCommand]; |
| 120 | + } |
| 121 | + |
92 | 122 | public override void OptionsLoaded(OptionsLoadedArgs e) |
93 | 123 | { |
94 | 124 | ArgumentNullException.ThrowIfNull(e); |
@@ -392,6 +422,75 @@ private void ProcessMockResponseInternal(ProxyRequestArgs e, MockResponse matchi |
392 | 422 | Logger.LogRequest($"{matchingResponse.Response?.StatusCode ?? 200} {matchingResponse.Request?.Url}", MessageType.Mocked, new(e.Session)); |
393 | 423 | } |
394 | 424 |
|
| 425 | + private async Task GenerateMocksFromHttpResponsesAsync(ParseResult parseResult) |
| 426 | + { |
| 427 | + Logger.LogTrace("{Method} called", nameof(GenerateMocksFromHttpResponsesAsync)); |
| 428 | + |
| 429 | + if (_httpResponseFilesArgument is null) |
| 430 | + { |
| 431 | + throw new InvalidOperationException("HTTP response files argument is not initialized."); |
| 432 | + } |
| 433 | + if (_httpResponseMocksFileNameOption is null) |
| 434 | + { |
| 435 | + throw new InvalidOperationException("HTTP response mocks file name option is not initialized."); |
| 436 | + } |
| 437 | + |
| 438 | + var outputFilePath = parseResult.GetValue(_httpResponseMocksFileNameOption); |
| 439 | + if (string.IsNullOrEmpty(outputFilePath)) |
| 440 | + { |
| 441 | + Logger.LogError("No output file path provided for mock responses."); |
| 442 | + return; |
| 443 | + } |
| 444 | + |
| 445 | + var httpResponseFiles = parseResult.GetValue(_httpResponseFilesArgument); |
| 446 | + if (httpResponseFiles is null || !httpResponseFiles.Any()) |
| 447 | + { |
| 448 | + Logger.LogError("No HTTP response files provided."); |
| 449 | + return; |
| 450 | + } |
| 451 | + |
| 452 | + var matcher = new Matcher(); |
| 453 | + matcher.AddIncludePatterns(httpResponseFiles); |
| 454 | + |
| 455 | + var matchingFiles = matcher.GetResultsInFullPath("."); |
| 456 | + if (!matchingFiles.Any()) |
| 457 | + { |
| 458 | + Logger.LogError("No matching HTTP response files found."); |
| 459 | + return; |
| 460 | + } |
| 461 | + |
| 462 | + Logger.LogInformation("Found {FileCount} matching HTTP response files", matchingFiles.Count()); |
| 463 | + Logger.LogDebug("Matching files: {Files}", string.Join(", ", matchingFiles)); |
| 464 | + |
| 465 | + var mockResponses = new List<MockResponse>(); |
| 466 | + foreach (var file in matchingFiles) |
| 467 | + { |
| 468 | + Logger.LogInformation("Processing file: {File}", Path.GetRelativePath(".", file)); |
| 469 | + try |
| 470 | + { |
| 471 | + mockResponses.Add(MockResponse.FromHttpResponse(await File.ReadAllTextAsync(file), Logger)); |
| 472 | + } |
| 473 | + catch (Exception ex) |
| 474 | + { |
| 475 | + Logger.LogError(ex, "Error processing file {File}", file); |
| 476 | + continue; |
| 477 | + } |
| 478 | + } |
| 479 | + |
| 480 | + var mocksFile = new MockResponseConfiguration |
| 481 | + { |
| 482 | + Mocks = mockResponses |
| 483 | + }; |
| 484 | + await File.WriteAllTextAsync( |
| 485 | + outputFilePath, |
| 486 | + JsonSerializer.Serialize(mocksFile, ProxyUtils.JsonSerializerOptions) |
| 487 | + ); |
| 488 | + |
| 489 | + Logger.LogInformation("Generated mock responses saved to {OutputFile}", outputFilePath); |
| 490 | + |
| 491 | + Logger.LogTrace("Left {Method}", nameof(GenerateMocksFromHttpResponsesAsync)); |
| 492 | + } |
| 493 | + |
395 | 494 | private static bool HasMatchingBody(MockResponse mockResponse, Request request) |
396 | 495 | { |
397 | 496 | if (request.Method == "GET") |
|
0 commit comments