Skip to content

Commit eee9d74

Browse files
waldekmastykarzgarrytrinder
authored andcommitted
Adds ~appFolder token. Closes #156
1 parent 2eccb17 commit eee9d74

File tree

9 files changed

+37
-11
lines changed

9 files changed

+37
-11
lines changed

msgraph-developer-proxy-abstractions/IProxyConfiguration.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation.
1+
// Copyright (c) Microsoft Corporation.
22
// Licensed under the MIT License.
33

44
using System.Runtime.Serialization;
@@ -22,4 +22,5 @@ public interface IProxyConfiguration {
2222
IEnumerable<int> WatchPids { get; }
2323
IEnumerable<string> WatchProcessNames { get; }
2424
int Rate { get; }
25+
string ConfigFile { get; }
2526
}

msgraph-developer-proxy-abstractions/ProxyUtils.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@ public static bool IsGraphBetaRequest(Request request) =>
1818
request.RequestUri.AbsolutePath.Contains("/beta/", StringComparison.OrdinalIgnoreCase);
1919

2020
/// <summary>
21-
/// Utiliy to build HTTP respopnse headers consistent with Microsoft Graph
21+
/// Utility to build HTTP response headers consistent with Microsoft Graph
2222
/// </summary>
2323
/// <param name="request">The http request for which response headers are being constructed</param>
2424
/// <param name="requestId">string a guid representing the a unique identifier for the request</param>
25-
/// <param name="requestDate">string represetation of the date and time the request was made</param>
25+
/// <param name="requestDate">string representation of the date and time the request was made</param>
2626
/// <returns>IList<HttpHeader> with defaults consistent with Microsoft Graph. Automatically adds CORS headers when the Origin header is present</returns>
2727
public static IList<HttpHeader> BuildGraphResponseHeaders(Request request, string requestId, string requestDate) {
2828
var headers = new List<HttpHeader>
@@ -40,4 +40,14 @@ public static IList<HttpHeader> BuildGraphResponseHeaders(Request request, strin
4040
}
4141
return headers;
4242
}
43+
44+
public static string ReplacePathTokens(string? path) {
45+
if (string.IsNullOrEmpty(path)) {
46+
return path ?? string.Empty;
47+
}
48+
49+
// doesn't end with a path separator
50+
var appFolder = Path.GetDirectoryName(AppContext.BaseDirectory);
51+
return path.Replace("~appFolder", appFolder, StringComparison.OrdinalIgnoreCase);
52+
}
4353
}

msgraph-developer-proxy-plugins/MockResponses/MockResponsePlugin.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public class MockResponsePlugin : BaseProxyPlugin {
2929
private readonly Option<bool?> _noMocks;
3030
private readonly Option<string?> _mocksFile;
3131
public override string Name => nameof(MockResponsePlugin);
32+
private IProxyConfiguration? _proxyConfiguration;
3233

3334
public MockResponsePlugin() {
3435
_noMocks = new Option<bool?>("--no-mocks", "Disable loading mock requests");
@@ -51,6 +52,8 @@ public override void Register(IPluginEvents pluginEvents,
5152
pluginEvents.Init += OnInit;
5253
pluginEvents.OptionsLoaded += OnOptionsLoaded;
5354
pluginEvents.BeforeRequest += OnRequest;
55+
56+
_proxyConfiguration = context.Configuration;
5457
}
5558

5659
private void OnInit(object? sender, InitArgs e) {
@@ -76,6 +79,9 @@ private void OnOptionsLoaded(object? sender, OptionsLoadedArgs e) {
7679
if (mocksFile is not null) {
7780
_configuration.MocksFile = mocksFile;
7881
}
82+
83+
_configuration.MocksFile = Path.GetFullPath(ProxyUtils.ReplacePathTokens(_configuration.MocksFile), Path.GetDirectoryName(_proxyConfiguration?.ConfigFile ?? string.Empty) ?? string.Empty);
84+
7985
// load the responses from the configured mocks file
8086
_loader?.InitResponsesWatcher();
8187
}
@@ -147,7 +153,7 @@ private void ProcessMockResponse(SessionEventArgs e, MockResponse matchingRespon
147153
// if we can read the file, we can immediately send the response and
148154
// skip the rest of the logic in this method
149155
// remove the surrounding quotes and the @-token
150-
var filePath = Path.Combine(Directory.GetCurrentDirectory(), bodyString.Trim('"').Substring(1));
156+
var filePath = Path.Combine(Path.GetDirectoryName(_configuration.MocksFile) ?? "", ProxyUtils.ReplacePathTokens(bodyString.Trim('"').Substring(1)));
151157
if (!File.Exists(filePath)) {
152158
_logger?.LogError($"File {filePath} not found. Serving file path in the mock response");
153159
body = bodyString;

msgraph-developer-proxy-plugins/MockResponses/MockResponsesLoader.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public MockResponsesLoader(ILogger logger, MockResponseConfiguration configurati
2020

2121
public void LoadResponses() {
2222
if (!File.Exists(_responsesFilePath)) {
23-
_logger.LogWarn($"File {_configuration.MocksFile} not found in the current directory. No mocks will be provided");
23+
_logger.LogWarn($"File {_configuration.MocksFile} not found. No mocks will be provided");
2424
_configuration.Responses = Array.Empty<MockResponse>();
2525
return;
2626
}

msgraph-developer-proxy-plugins/RandomErrors/GenericRandomErrorPlugin.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ private void UpdateProxyResponse(ProxyRequestArgs ev, GenericErrorResponse error
9898
// if we can read the file, we can immediately send the response and
9999
// skip the rest of the logic in this method
100100
// remove the surrounding quotes and the @-token
101-
var filePath = Path.Combine(Directory.GetCurrentDirectory(), body.Trim('"').Substring(1));
101+
var filePath = Path.Combine(Path.GetDirectoryName(_configuration.ErrorsFile) ?? "", ProxyUtils.ReplacePathTokens(body.Trim('"').Substring(1)));
102102
if (!File.Exists(filePath)) {
103103
_logger?.LogError($"File {filePath} not found. Serving file path in the mock response");
104104
session.GenericResponse(body, statusCode, headers);
@@ -122,7 +122,11 @@ public override void Register(IPluginEvents pluginEvents,
122122
IConfigurationSection? configSection = null) {
123123
base.Register(pluginEvents, context, urlsToWatch, configSection);
124124

125+
_proxyConfiguration = context.Configuration;
126+
125127
configSection?.Bind(_configuration);
128+
_configuration.ErrorsFile = Path.GetFullPath(ProxyUtils.ReplacePathTokens(_configuration.ErrorsFile ?? string.Empty), Path.GetDirectoryName(_proxyConfiguration?.ConfigFile ?? string.Empty) ?? string.Empty);
129+
126130
_loader = new GenericErrorResponsesLoader(_logger!, _configuration);
127131

128132
pluginEvents.Init += OnInit;

msgraph-developer-proxy/PluginLoader.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ public PluginLoaderResult LoadPlugins(IPluginEvents pluginEvents, IProxyContext
2727
PluginConfig config = PluginConfig;
2828
List<UrlToWatch> globallyWatchedUrls = PluginConfig.UrlsToWatch.Select(ConvertToRegex).ToList();
2929
ISet<UrlToWatch> defaultUrlsToWatch = globallyWatchedUrls.ToHashSet();
30-
string? rootDirectory = Path.GetDirectoryName(AppContext.BaseDirectory);
31-
if (!string.IsNullOrEmpty(rootDirectory)) {
30+
string? configFileDirectory = Path.GetDirectoryName(Path.GetFullPath(ProxyUtils.ReplacePathTokens(ProxyHost.ConfigFile)));
31+
if (!string.IsNullOrEmpty(configFileDirectory)) {
3232
foreach (PluginReference h in config.Plugins) {
3333
if (!h.Enabled) continue;
3434
// Load Handler Assembly if enabled
35-
string pluginLocation = Path.GetFullPath(Path.Combine(rootDirectory, h.PluginPath.Replace('\\', Path.DirectorySeparatorChar)));
35+
string pluginLocation = Path.GetFullPath(Path.Combine(configFileDirectory, ProxyUtils.ReplacePathTokens(h.PluginPath.Replace('\\', Path.DirectorySeparatorChar))));
3636
PluginLoadContext pluginLoadContext = new PluginLoadContext(pluginLocation);
3737
_logger.LogDebug($"Loading from: {pluginLocation}");
3838
Assembly assembly = pluginLoadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)));
@@ -48,6 +48,7 @@ public PluginLoaderResult LoadPlugins(IPluginEvents pluginEvents, IProxyContext
4848
plugins.Add(plugin);
4949
}
5050
}
51+
5152
return plugins.Count > 0
5253
? new PluginLoaderResult(globallyWatchedUrls.ToHashSet(), plugins)
5354
: throw new InvalidDataException("No plugins were loaded");

msgraph-developer-proxy/ProxyConfiguration.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,6 @@ public class ProxyConfiguration: IProxyConfiguration {
2121
public IEnumerable<string> WatchProcessNames { get; set; } = new List<string>();
2222
[JsonPropertyName("rate")]
2323
public int Rate { get; set; } = 50;
24+
public string ConfigFile { get; set; } = "appsettings.json";
2425
}
2526

msgraph-developer-proxy/ProxyContext.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ namespace Microsoft.Graph.DeveloperProxy;
88
internal class ProxyContext : IProxyContext
99
{
1010
public ILogger Logger { get; }
11-
1211
public IProxyConfiguration Configuration { get; }
1312

1413
public ProxyContext(ILogger logger, IProxyConfiguration configuration)

msgraph-developer-proxy/ProxyHost.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public static string ConfigFile {
2929
_configFileOption.AddAlias("-c");
3030
_configFileOption.ArgumentHelpName = "configFile";
3131
_configFileOption.AddValidator(input => {
32-
var filePath = input.Tokens.First().Value;
32+
var filePath = ProxyUtils.ReplacePathTokens(input.Tokens.First().Value);
3333
if (String.IsNullOrEmpty(filePath)) {
3434
return;
3535
}
@@ -46,6 +46,8 @@ public static string ConfigFile {
4646
_configFile = configFile;
4747
}
4848

49+
_configFile = Path.GetFullPath(ProxyUtils.ReplacePathTokens(_configFile));
50+
4951
_configFileResolved = true;
5052

5153
return _configFile;
@@ -84,6 +86,8 @@ public ProxyHost() {
8486
input.ErrorMessage = $"{value} is not a valid failure rate. Specify a number between 0 and 100";
8587
}
8688
});
89+
90+
ProxyCommandHandler.Configuration.ConfigFile = ConfigFile;
8791
}
8892

8993
public RootCommand GetRootCommand() {

0 commit comments

Comments
 (0)