Skip to content

Commit

Permalink
fix: fixing issue with BuildConfiguration overrides
Browse files Browse the repository at this point in the history
  • Loading branch information
Dan Siegel authored and Dan Siegel committed Dec 19, 2024
1 parent cf2ea83 commit 0761386
Show file tree
Hide file tree
Showing 6 changed files with 123 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ namespace Mobile.BuildTools.AppSettings.Generators
[Generator]
public sealed class AppSettingsGenerator : GeneratorBase
{
private const string DefaultPrefix = "BuildTools_";

public const string AutoGeneratedMessage = @"This code was generated by Mobile.BuildTools. For more information please visit
https://mobilebuildtools.com or to file an issue please see
https://github.com/dansiegel/Mobile.BuildTools
Expand Down Expand Up @@ -57,7 +59,7 @@ protected override void Generate()
settingsConfig.Delimiter = settingsConfig.Delimiter.Trim();

if (string.IsNullOrEmpty(settingsConfig.Prefix))
settingsConfig.Prefix = "BuildTools_";
settingsConfig.Prefix = DefaultPrefix;
else
settingsConfig.Prefix = settingsConfig.Prefix.Trim();

Expand Down Expand Up @@ -224,21 +226,28 @@ internal IDictionary<string, string> GetMergedSecrets(SettingsConfig settingsCon
hasErrors = false;
foreach (var prop in settingsConfig.Properties)
{
var searchKeys = new[]
var prefixKey = settingsConfig.Prefix.EndsWith("_") ? $"{settingsConfig.Prefix}{prop.Name}" : $"{settingsConfig.Prefix}_{prop.Name}";

var searchKeys = new List<string>
{
$"{settingsConfig.Prefix}{prop.Name}",
$"{settingsConfig.Prefix}_{prop.Name}",
prop.Name,
prefixKey
};

if (settingsConfig.Prefix != DefaultPrefix)
{
searchKeys.Add($"{DefaultPrefix}{prefixKey}");
}

string key = null;
foreach (var searchKey in searchKeys)
{
if (!string.IsNullOrEmpty(key))
break;

key = env.Keys.FirstOrDefault(x =>
x.Equals(searchKey, StringComparison.InvariantCultureIgnoreCase));
x.Equals(searchKey, StringComparison.InvariantCultureIgnoreCase) ||
x.Equals($"{BuildConfiguration}_{searchKey}", StringComparison.InvariantCultureIgnoreCase));
}

if (string.IsNullOrEmpty(key))
Expand Down
2 changes: 2 additions & 0 deletions src/Mobile.BuildTools.AppSettings/Generators/GeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public abstract class GeneratorBase : ISourceGenerator
protected string ProjectName => _projectName;
protected string RootNamespace => _rootNamespace;

protected string BuildConfiguration => _buildConfiguration;

protected BuildToolsConfig Config { get; private set; }

public void Execute(GeneratorExecutionContext context)
Expand Down
72 changes: 43 additions & 29 deletions src/Mobile.BuildTools.Reference/Utils/EnvironmentAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Text.RegularExpressions;
using Mobile.BuildTools.Build;
using Mobile.BuildTools.Handlers;
using Mobile.BuildTools.Reference.IO;

namespace Mobile.BuildTools.Utils
{
Expand All @@ -19,14 +18,14 @@ public static class EnvironmentAnalyzer
public static IDictionary<string, string> GatherEnvironmentVariables(IBuildConfiguration buildConfiguration = null, bool includeManifest = false)
{
var env = new Dictionary<string, string>();
if(buildConfiguration is null)
if (buildConfiguration is null)
{
foreach (var key in Environment.GetEnvironmentVariables().Keys)
{
env[key.ToString()] = Environment.GetEnvironmentVariable(key.ToString());
}

return env;
return env;
}

env = GetEnvironmentVariables(buildConfiguration);
Expand Down Expand Up @@ -60,7 +59,7 @@ public static IDictionary<string, string> GatherEnvironmentVariables(IBuildConfi
{
break;
}
else if(!directories.Contains(lookupDir))
else if (!directories.Contains(lookupDir))
{
directories.Add(lookupDir);
}
Expand All @@ -79,30 +78,45 @@ public static IDictionary<string, string> GatherEnvironmentVariables(IBuildConfi
.Where(x => x.Exists)
.ToList();

directories
.SelectMany(x =>
x.EnumerateFiles("*.json", SearchOption.TopDirectoryOnly)
.Where(x => x.Name == Constants.SecretsJsonFileName || x.Name == string.Format(Constants.SecretsJsonConfigurationFileFormat, configuration)))
.Where(x => x.Exists)
.Select(x => x.FullName)
.Distinct()
.ForEach(x =>
string[] expectedFileNames =
[
Constants.SecretsJsonFileName,
string.Format(Constants.SecretsJsonConfigurationFileFormat, configuration)
];
foreach (var fileName in expectedFileNames)
{
foreach (var directory in directories)
{
buildConfiguration.Logger.LogWarning($"The secrets.json has been deprecated and will no longer be supported in a future version. Please migrate '{x}' to appsettings.json");
LoadSecrets(x, ref env);
});

directories
.SelectMany(x =>
x.EnumerateFiles("*.json", SearchOption.TopDirectoryOnly)
.Where(x => x.Name == Constants.AppSettingsJsonFileName
|| x.Name == string.Format(Constants.AppSettingsJsonConfigurationFileFormat, configuration)
|| x.Name == string.Format(Constants.AppSettingsJsonConfigurationFileFormat, $"{buildConfiguration.Platform}")
|| x.Name == string.Format(Constants.AppSettingsJsonConfigurationFileFormat, $"{buildConfiguration.Platform}.{configuration}")))
.Where(x => x.Exists)
.Select(x => x.FullName)
.Distinct()
.ForEach(x => LoadSecrets(x, ref env));
var file = new FileInfo(Path.Combine(directory.FullName, fileName));
if (file.Exists)
{
buildConfiguration.Logger.LogWarning($"The secrets.json has been deprecated and will no longer be supported in a future version. Please migrate '{fileName}' to appsettings.json");
LoadSecrets(file.FullName, ref env);
break;
}
}
}

expectedFileNames =
[
Constants.AppSettingsJsonFileName,
string.Format(Constants.AppSettingsJsonConfigurationFileFormat, configuration),
string.Format(Constants.AppSettingsJsonConfigurationFileFormat, $"{buildConfiguration.Platform}"),
string.Format(Constants.AppSettingsJsonConfigurationFileFormat, $"{buildConfiguration.Platform}.{configuration}")
];

foreach(var fileName in expectedFileNames)
{
foreach(var directory in directories)
{
var file = new FileInfo(Path.Combine(directory.FullName, fileName));
if (file.Exists)
{
LoadSecrets(file.FullName, ref env);
break;
}
}
}

if (includeManifest)
{
Expand Down Expand Up @@ -134,12 +148,12 @@ public static IDictionary<string, string> GatherEnvironmentVariables(IBuildConfi
private static Dictionary<string, string> GetEnvironmentVariables(IBuildConfiguration buildConfiguration)
{
var env = new Dictionary<string, string>();
foreach((var key, var value) in buildConfiguration.Configuration.Environment.Defaults)
foreach ((var key, var value) in buildConfiguration.Configuration.Environment.Defaults)
{
env[key] = value;
}

if(buildConfiguration.Configuration.Environment.Configuration.ContainsKey(buildConfiguration.BuildConfiguration))
if (buildConfiguration.Configuration.Environment.Configuration.ContainsKey(buildConfiguration.BuildConfiguration))
{
var configEnvironment = buildConfiguration.Configuration.Environment.Configuration[buildConfiguration.BuildConfiguration];
if(configEnvironment is not null)
Expand Down
42 changes: 21 additions & 21 deletions tests/Mobile.BuildTools.Tests/Fixtures/FixtureBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,47 @@ public abstract class FixtureBase
protected ITestOutputHelper _testOutputHelper { get; }
protected string ProjectDirectory { get; }

protected FixtureBase(ITestOutputHelper testOutputHelper)
protected FixtureBase(ITestOutputHelper testOutputHelper)
: this(null, testOutputHelper)
{
}

protected FixtureBase(string projectDirectory, ITestOutputHelper testOutputHelper)
{
{
_testOutputHelper = testOutputHelper;
ProjectDirectory = projectDirectory;
}

protected TestBuildConfiguration GetConfiguration(string testName = null)
{
if(string.IsNullOrEmpty(testName))
{
var stackTrace = new StackTrace();
testName = stackTrace.GetFrame(1).GetMethod().Name;
}

if (testName.Length > 20)
testName = System.Guid.NewGuid().ToString();

var tempDir = Path.GetTempPath();
var projectDirectory = ProjectDirectory;
var solutionDirectory = ProjectDirectory;
if (string.IsNullOrEmpty(projectDirectory))
{
projectDirectory = Path.Combine(tempDir, "Tests", GetType().Name, testName, "SolutionDir", "src", testName);
solutionDirectory = Path.Combine(tempDir, "Tests", GetType().Name, testName, "SolutionDir");
{
if(string.IsNullOrEmpty(testName))
{
var stackTrace = new StackTrace();
testName = stackTrace.GetFrame(1).GetMethod().Name;
}

if (testName.Length > 20)
testName = System.Guid.NewGuid().ToString();

var tempDir = Path.GetTempPath();
var projectDirectory = ProjectDirectory;
var solutionDirectory = ProjectDirectory;
if (string.IsNullOrEmpty(projectDirectory))
{
projectDirectory = Path.Combine(tempDir, "Tests", GetType().Name, testName, "SolutionDir", "src", testName);
solutionDirectory = Path.Combine(tempDir, "Tests", GetType().Name, testName, "SolutionDir");
}

var testOutput = Path.Combine(tempDir, "Tests", GetType().Name, testName);
ResetTestOutputDirectory(testOutput);
ResetTestOutputDirectory(testOutput);
ResetTestOutputDirectory(projectDirectory);

return new TestBuildConfiguration
{
Logger = new XunitLog(_testOutputHelper),
Platform = Platform.Unsupported,
IntermediateOutputPath = testOutput,
ProjectDirectory = projectDirectory,
ProjectDirectory = projectDirectory,
SolutionDirectory = solutionDirectory,
BuildConfiguration = "Debug",
ProjectName = "AwesomeApp",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json;
using Mobile.BuildTools.Models.Settings;
using Mobile.BuildTools.Utils;
using Xunit;
Expand Down Expand Up @@ -42,6 +39,41 @@ public void GetsValuesFromJson(string filename)
Assert.Equal(secrets.SampleProp, mergedSecrets["SampleProp"]);
}

[Fact]
public void GetsValueFromBuildConfigurationOverrideJson()
{
var config = GetConfiguration();
var settingsConfig = new SettingsConfig
{
Properties =
[
new ValueConfig
{
Name = "SampleProp",
PropertyType = PropertyType.String
}
]
};

config.Configuration.AppSettings[config.ProjectName] = new List<SettingsConfig>([settingsConfig]);

var secrets = new
{
SampleProp = "Hello Tests"
};
File.WriteAllText(Path.Combine(config.ProjectDirectory, "appsettings.json"), JsonSerializer.Serialize(secrets));
var buildConfigurationSecrets = new
{
SampleProp = $"Hello {config.BuildConfiguration}"
};
File.WriteAllText(Path.Combine(config.ProjectDirectory, $"appsettings.{config.BuildConfiguration}.json"), JsonSerializer.Serialize(buildConfigurationSecrets));

var mergedSecrets = EnvironmentAnalyzer.GatherEnvironmentVariables(config);

Assert.True(mergedSecrets.ContainsKey("SampleProp"));
Assert.Equal(buildConfigurationSecrets.SampleProp, mergedSecrets["SampleProp"]);
}

[Fact]
public void GetsValuesFromConfigurationEnvironment()
{
Expand Down
14 changes: 7 additions & 7 deletions tests/Mobile.BuildTools.Tests/Mobile.BuildTools.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net472</TargetFramework>
Expand All @@ -9,9 +9,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="GitHubActionsTestLogger">
<PrivateAssets>all</PrivateAssets>
Expand All @@ -20,9 +20,9 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Build" />
<PackageReference Include="Microsoft.Build.Tasks.Core" />
Expand Down

0 comments on commit 0761386

Please sign in to comment.