Skip to content

Commit ef9974f

Browse files
Add --report-dir option and reportsFolder setting for report output (#2099)
* Add --report-dir option and reportsFolder setting for report output Reporters wrote reports to Dev Proxy's current working directory, forcing scripts to change cwd (which also changes how config paths resolve) just to control where reports land. - New reportsFolder setting in devproxyrc.json, resolved relative to the config file (supports ~/, ~appFolder, ~dataFolder tokens) - New --report-dir option, resolved relative to the working directory, which overrides reportsFolder - BaseReporter writes to the folder (creating it if needed); default stays the working directory - Updated v4.0.0 rc schema Closes #2071 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Keep reporter and IProxyConfiguration APIs backward compatible - Move ReportsFolder to optional IReportsProxyConfiguration so existing IProxyConfiguration implementations keep compiling - Restore two-argument constructors on JsonReporter, MarkdownReporter and PlainTextReporter; mark config-aware ones for DI activation - Move reportsFolder schema to v4.1.0 and leave v4.0.0 unchanged Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Require a value for --report-dir and forward empty args to detached daemon - Set --report-dir arity to exactly one and reject missing values - Pass daemon args via ArgumentList so empty values aren't dropped - Prepend --_internal-daemon so a trailing option can't consume it Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 2be6d04 commit ef9974f

14 files changed

Lines changed: 406 additions & 31 deletions

File tree

‎DevProxy.Abstractions/Proxy/IProxyConfiguration.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,13 @@ public interface IProxyConfiguration
5555
public interface IProcessTreeProxyConfiguration
5656
{
5757
bool WatchProcessTree { get; set; }
58+
}
59+
60+
public interface IReportsProxyConfiguration
61+
{
62+
/// <summary>
63+
/// Absolute path of the folder where reporters write report files.
64+
/// When null or empty, reports are written to the current working directory.
65+
/// </summary>
66+
string? ReportsFolder { get; set; }
5867
}

‎DevProxy.Integration.Tests/JsonReporterTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ namespace DevProxy.Integration.Tests;
1414

1515
public sealed class JsonReporterTests
1616
{
17-
private sealed class TestJsonReporter() : JsonReporter(NullLogger<JsonReporter>.Instance, new HashSet<UrlToWatch>())
17+
private sealed class TestJsonReporter() : JsonReporter(NullLogger<JsonReporter>.Instance, new HashSet<UrlToWatch>(), new TestProxyConfiguration())
1818
{
1919
public string? Report(string key, object value) => GetReport(new(key, value));
2020
}
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
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 DevProxy.Abstractions.Proxy;
6+
using DevProxy.Abstractions.Utils;
7+
using DevProxy.Plugins.Reporters;
8+
using Microsoft.Extensions.DependencyInjection;
9+
using Microsoft.Extensions.Logging;
10+
using Microsoft.Extensions.Logging.Abstractions;
11+
using Xunit;
12+
13+
namespace DevProxy.Integration.Tests;
14+
15+
/// <summary>
16+
/// Verifies that reporters honour <see cref="IReportsProxyConfiguration.ReportsFolder"/>
17+
/// and fall back to the current working directory when it isn't set.
18+
/// </summary>
19+
public sealed class ReporterReportsFolderTests
20+
{
21+
private static RecordingArgs Recording() =>
22+
new([])
23+
{
24+
GlobalData = new()
25+
{
26+
[ProxyUtils.ReportsKey] = new Dictionary<string, object>
27+
{
28+
["TestPlugin"] = new { Value = 1 }
29+
}
30+
},
31+
};
32+
33+
private static JsonReporter CreateReporter(string? reportsFolder) =>
34+
new(NullLogger<JsonReporter>.Instance, new HashSet<UrlToWatch>(), new TestProxyConfiguration { ReportsFolder = reportsFolder });
35+
36+
[Fact]
37+
public async Task WritesReportToReportsFolder_CreatingItWhenMissing()
38+
{
39+
var root = Directory.CreateTempSubdirectory("devproxy-reports-");
40+
var cwd = Directory.CreateTempSubdirectory("devproxy-cwd-");
41+
var originalCwd = Directory.GetCurrentDirectory();
42+
Directory.SetCurrentDirectory(cwd.FullName);
43+
try
44+
{
45+
var reportsFolder = Path.Combine(root.FullName, "nested", "reports");
46+
var reporter = CreateReporter(reportsFolder);
47+
48+
await reporter.AfterRecordingStopAsync(Recording(), CancellationToken.None);
49+
50+
Assert.True(File.Exists(Path.Combine(reportsFolder, "TestPlugin_JsonReporter.json")));
51+
Assert.Empty(Directory.GetFiles(cwd.FullName));
52+
}
53+
finally
54+
{
55+
Directory.SetCurrentDirectory(originalCwd);
56+
root.Delete(true);
57+
cwd.Delete(true);
58+
}
59+
}
60+
61+
[Fact]
62+
public async Task PluginActivation_UsesConfigurationAwareConstructor()
63+
{
64+
var root = Directory.CreateTempSubdirectory("devproxy-reports-");
65+
try
66+
{
67+
using var serviceProvider = new ServiceCollection()
68+
.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance)
69+
.AddSingleton(typeof(ILogger<>), typeof(Logger<>))
70+
.AddSingleton<IProxyConfiguration>(new TestProxyConfiguration { ReportsFolder = root.FullName })
71+
.BuildServiceProvider();
72+
var reporter = ActivatorUtilities.CreateInstance<JsonReporter>(serviceProvider, new HashSet<UrlToWatch>());
73+
74+
await reporter.AfterRecordingStopAsync(Recording(), CancellationToken.None);
75+
76+
Assert.True(File.Exists(Path.Combine(root.FullName, "TestPlugin_JsonReporter.json")));
77+
}
78+
finally
79+
{
80+
root.Delete(true);
81+
}
82+
}
83+
84+
[Fact]
85+
public async Task AppendsTimestamp_WhenReportExistsInReportsFolder()
86+
{
87+
var root = Directory.CreateTempSubdirectory("devproxy-reports-");
88+
try
89+
{
90+
await File.WriteAllTextAsync(Path.Combine(root.FullName, "TestPlugin_JsonReporter.json"), "{}");
91+
var reporter = CreateReporter(root.FullName);
92+
93+
await reporter.AfterRecordingStopAsync(Recording(), CancellationToken.None);
94+
95+
Assert.Equal(2, Directory.GetFiles(root.FullName, "TestPlugin_JsonReporter*.json").Length);
96+
}
97+
finally
98+
{
99+
root.Delete(true);
100+
}
101+
}
102+
103+
[Theory]
104+
[InlineData(null)]
105+
[InlineData("")]
106+
public async Task WritesReportToWorkingDirectory_WhenReportsFolderNotSet(string? reportsFolder)
107+
{
108+
var cwd = Directory.CreateTempSubdirectory("devproxy-cwd-");
109+
var originalCwd = Directory.GetCurrentDirectory();
110+
Directory.SetCurrentDirectory(cwd.FullName);
111+
try
112+
{
113+
var reporter = CreateReporter(reportsFolder);
114+
115+
await reporter.AfterRecordingStopAsync(Recording(), CancellationToken.None);
116+
117+
Assert.True(File.Exists(Path.Combine(cwd.FullName, "TestPlugin_JsonReporter.json")));
118+
}
119+
finally
120+
{
121+
Directory.SetCurrentDirectory(originalCwd);
122+
cwd.Delete(true);
123+
}
124+
}
125+
}

‎DevProxy.Integration.Tests/TestProxyConfiguration.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ namespace DevProxy.Integration.Tests;
1313
/// members the Kestrel engine reads at boot (Port, IPAddress, AsSystemProxy,
1414
/// WatchPids/WatchProcessNames/WatchProcessTree) actually matter; the rest carry inert defaults.
1515
/// </summary>
16-
internal sealed class TestProxyConfiguration : IProxyConfiguration, IProcessTreeProxyConfiguration
16+
internal sealed class TestProxyConfiguration : IProxyConfiguration, IProcessTreeProxyConfiguration, IReportsProxyConfiguration
1717
{
1818
public string ApiIpAddress { get; set; } = "127.0.0.1";
1919
public int ApiPort { get; set; }
@@ -30,6 +30,7 @@ internal sealed class TestProxyConfiguration : IProxyConfiguration, IProcessTree
3030
public bool NoWatch { get; set; }
3131
public int Port { get; set; }
3232
public bool Record { get; set; }
33+
public string? ReportsFolder { get; set; }
3334
public bool ShowTimestamps => false;
3435
public long? TimeoutSeconds { get; set; }
3536
public bool ValidateSchemas => false;

‎DevProxy.Plugins/Reporters/BaseReporter.cs‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,22 @@
99

1010
namespace DevProxy.Plugins.Reporters;
1111

12-
public abstract class BaseReporter(
13-
ILogger logger,
14-
ISet<UrlToWatch> urlsToWatch) : BasePlugin(logger, urlsToWatch)
12+
public abstract class BaseReporter : BasePlugin
1513
{
14+
private readonly IProxyConfiguration? _proxyConfiguration;
15+
16+
protected BaseReporter(ILogger logger, ISet<UrlToWatch> urlsToWatch) : base(logger, urlsToWatch)
17+
{
18+
}
19+
20+
protected BaseReporter(
21+
ILogger logger,
22+
ISet<UrlToWatch> urlsToWatch,
23+
IProxyConfiguration proxyConfiguration) : base(logger, urlsToWatch)
24+
{
25+
_proxyConfiguration = proxyConfiguration;
26+
}
27+
1628
public abstract string FileExtension { get; }
1729

1830
public override async Task AfterRecordingStopAsync(RecordingArgs e, CancellationToken cancellationToken)
@@ -45,21 +57,34 @@ value is not Dictionary<string, object> reports ||
4557
continue;
4658
}
4759

48-
var fileName = $"{report.Key}_{Name}{FileExtension}";
60+
var fileName = GetReportFilePath($"{report.Key}_{Name}{FileExtension}");
4961
Logger.LogDebug("File name for report {Report}: {FileName}", report.Key, fileName);
5062

5163
if (File.Exists(fileName))
5264
{
5365
Logger.LogDebug("File {FileName} already exists, appending timestamp", fileName);
54-
fileName = $"{report.Key}_{Name}_{DateTime.Now:yyyyMMddHHmmss}{FileExtension}";
66+
fileName = GetReportFilePath($"{report.Key}_{Name}_{DateTime.Now:yyyyMMddHHmmss}{FileExtension}");
5567
}
5668

5769
Logger.LogInformation("Writing report {ReportKey} to {FileName}...", report.Key, fileName);
70+
if (!string.IsNullOrEmpty(ReportsFolder))
71+
{
72+
_ = Directory.CreateDirectory(ReportsFolder);
73+
}
5874
await File.WriteAllTextAsync(fileName, reportContents, cancellationToken);
5975
}
6076

6177
Logger.LogTrace("Left {Name}", nameof(AfterRecordingStopAsync));
6278
}
6379

6480
protected abstract string? GetReport(KeyValuePair<string, object> report);
81+
82+
/// <summary>
83+
/// Folder where reports are written. When null or empty, reports are written
84+
/// to the current working directory.
85+
/// </summary>
86+
protected string? ReportsFolder => (_proxyConfiguration as IReportsProxyConfiguration)?.ReportsFolder;
87+
88+
protected string GetReportFilePath(string fileName) =>
89+
string.IsNullOrEmpty(ReportsFolder) ? fileName : Path.Combine(ReportsFolder, fileName);
6590
}

‎DevProxy.Plugins/Reporters/JsonReporter.cs‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,28 @@
55
using DevProxy.Abstractions.Plugins;
66
using DevProxy.Abstractions.Proxy;
77
using DevProxy.Abstractions.Utils;
8+
using Microsoft.Extensions.DependencyInjection;
89
using Microsoft.Extensions.Logging;
910
using System.Text.Json;
1011

1112
namespace DevProxy.Plugins.Reporters;
1213

13-
public class JsonReporter(
14-
ILogger<JsonReporter> logger,
15-
ISet<UrlToWatch> urlsToWatch) : BaseReporter(logger, urlsToWatch)
14+
public class JsonReporter : BaseReporter
1615
{
16+
public JsonReporter(
17+
ILogger<JsonReporter> logger,
18+
ISet<UrlToWatch> urlsToWatch) : base(logger, urlsToWatch)
19+
{
20+
}
21+
22+
[ActivatorUtilitiesConstructor]
23+
public JsonReporter(
24+
ILogger<JsonReporter> logger,
25+
ISet<UrlToWatch> urlsToWatch,
26+
IProxyConfiguration proxyConfiguration) : base(logger, urlsToWatch, proxyConfiguration)
27+
{
28+
}
29+
1730
private const string DefaultFileExtension = ".json";
1831
private string _fileExtension = DefaultFileExtension;
1932

‎DevProxy.Plugins/Reporters/MarkdownReporter.cs‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,27 @@
44

55
using DevProxy.Abstractions.Plugins;
66
using DevProxy.Abstractions.Proxy;
7+
using Microsoft.Extensions.DependencyInjection;
78
using Microsoft.Extensions.Logging;
89

910
namespace DevProxy.Plugins.Reporters;
1011

11-
public class MarkdownReporter(
12-
ILogger<MarkdownReporter> logger,
13-
ISet<UrlToWatch> urlsToWatch) : BaseReporter(logger, urlsToWatch)
12+
public class MarkdownReporter : BaseReporter
1413
{
14+
public MarkdownReporter(
15+
ILogger<MarkdownReporter> logger,
16+
ISet<UrlToWatch> urlsToWatch) : base(logger, urlsToWatch)
17+
{
18+
}
19+
20+
[ActivatorUtilitiesConstructor]
21+
public MarkdownReporter(
22+
ILogger<MarkdownReporter> logger,
23+
ISet<UrlToWatch> urlsToWatch,
24+
IProxyConfiguration proxyConfiguration) : base(logger, urlsToWatch, proxyConfiguration)
25+
{
26+
}
27+
1528
public override string Name => nameof(MarkdownReporter);
1629
public override string FileExtension => ".md";
1730

‎DevProxy.Plugins/Reporters/PlainTextReporter.cs‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,27 @@
44

55
using DevProxy.Abstractions.Plugins;
66
using DevProxy.Abstractions.Proxy;
7+
using Microsoft.Extensions.DependencyInjection;
78
using Microsoft.Extensions.Logging;
89

910
namespace DevProxy.Plugins.Reporters;
1011

11-
public class PlainTextReporter(
12-
ILogger<PlainTextReporter> logger,
13-
ISet<UrlToWatch> urlsToWatch) : BaseReporter(logger, urlsToWatch)
12+
public class PlainTextReporter : BaseReporter
1413
{
14+
public PlainTextReporter(
15+
ILogger<PlainTextReporter> logger,
16+
ISet<UrlToWatch> urlsToWatch) : base(logger, urlsToWatch)
17+
{
18+
}
19+
20+
[ActivatorUtilitiesConstructor]
21+
public PlainTextReporter(
22+
ILogger<PlainTextReporter> logger,
23+
ISet<UrlToWatch> urlsToWatch,
24+
IProxyConfiguration proxyConfiguration) : base(logger, urlsToWatch, proxyConfiguration)
25+
{
26+
}
27+
1528
public override string Name => nameof(PlainTextReporter);
1629
public override string FileExtension => ".txt";
1730

‎DevProxy.Tests/Fakes.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
8181
/// Minimal <see cref="IProxyConfiguration"/>; only Output/ApiIpAddress/ApiPort/Record
8282
/// are read by the interactive console, the rest carry inert defaults.
8383
/// </summary>
84-
internal sealed class FakeProxyConfiguration : IProxyConfiguration, IProcessTreeProxyConfiguration
84+
internal sealed class FakeProxyConfiguration : IProxyConfiguration, IProcessTreeProxyConfiguration, IReportsProxyConfiguration
8585
{
8686
public string ApiIpAddress { get; set; } = "127.0.0.1";
8787
public int ApiPort { get; set; } = 8897;
@@ -98,6 +98,7 @@ internal sealed class FakeProxyConfiguration : IProxyConfiguration, IProcessTree
9898
public bool NoWatch { get; set; }
9999
public int Port { get; set; } = 8000;
100100
public bool Record { get; set; }
101+
public string? ReportsFolder { get; set; }
101102
public bool ShowTimestamps => false;
102103
public long? TimeoutSeconds { get; set; }
103104
public bool ValidateSchemas { get; set; }

0 commit comments

Comments
 (0)