Skip to content
Closed
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
14 changes: 14 additions & 0 deletions Microsoft.Maui.sln
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ VisualStudioVersion = 17.0.31410.414
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core", "src\Core\src\Core.csproj", "{95BA42B5-B00E-4986-B9B5-517140378452}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.ConfigurationSourceGen", "src\Core\src\ConfigurationSourceGen\Core.ConfigurationSourceGen.csproj", "{2A1B3C4D-5E6F-7890-ABCD-EF1234567890}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Controls.Core", "src\Controls\src\Core\Controls.Core.csproj", "{AF64451F-E2BD-41C2-B083-F60C26AE2A9F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Compatibility", "src\Compatibility\Core\src\Compatibility.csproj", "{00A11C2F-969F-4964-8557-91ADF4B1523D}"
Expand Down Expand Up @@ -38,6 +40,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtils", "src\TestUtils\
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.UnitTests", "src\Core\tests\UnitTests\Core.UnitTests.csproj", "{92644F6F-5946-48FC-A21A-A3D6EE24E8B3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.ConfigurationSourceGen.UnitTests", "src\Core\tests\ConfigurationSourceGen.UnitTests\Core.ConfigurationSourceGen.UnitTests.csproj", "{1F2E3D4C-5B6A-7890-CDEF-123456789ABC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E8AD265B-3C67-4640-AC58-A522F9FB3361}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{C564DDD6-DE79-45CD-88EA-3F690481572A}"
Expand Down Expand Up @@ -259,6 +263,10 @@ Global
{95BA42B5-B00E-4986-B9B5-517140378452}.Debug|Any CPU.Build.0 = Debug|Any CPU
{95BA42B5-B00E-4986-B9B5-517140378452}.Release|Any CPU.ActiveCfg = Release|Any CPU
{95BA42B5-B00E-4986-B9B5-517140378452}.Release|Any CPU.Build.0 = Release|Any CPU
{2A1B3C4D-5E6F-7890-ABCD-EF1234567890}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2A1B3C4D-5E6F-7890-ABCD-EF1234567890}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2A1B3C4D-5E6F-7890-ABCD-EF1234567890}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2A1B3C4D-5E6F-7890-ABCD-EF1234567890}.Release|Any CPU.Build.0 = Release|Any CPU
{AF64451F-E2BD-41C2-B083-F60C26AE2A9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AF64451F-E2BD-41C2-B083-F60C26AE2A9F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF64451F-E2BD-41C2-B083-F60C26AE2A9F}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand Down Expand Up @@ -301,6 +309,10 @@ Global
{92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Release|Any CPU.Build.0 = Release|Any CPU
{1F2E3D4C-5B6A-7890-CDEF-123456789ABC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1F2E3D4C-5B6A-7890-CDEF-123456789ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1F2E3D4C-5B6A-7890-CDEF-123456789ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1F2E3D4C-5B6A-7890-CDEF-123456789ABC}.Release|Any CPU.Build.0 = Release|Any CPU
{F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand Down Expand Up @@ -648,6 +660,7 @@ Global
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{95BA42B5-B00E-4986-B9B5-517140378452} = {E8AD265B-3C67-4640-AC58-A522F9FB3361}
{2A1B3C4D-5E6F-7890-ABCD-EF1234567890} = {E8AD265B-3C67-4640-AC58-A522F9FB3361}
{AF64451F-E2BD-41C2-B083-F60C26AE2A9F} = {50C758FE-4E10-409A-94F5-A75480960864}
{00A11C2F-969F-4964-8557-91ADF4B1523D} = {446EB407-57EB-441D-9ADB-1A006CBF672A}
{E1082E26-D700-4127-9329-66D673FD2D55} = {459BF674-83CB-46F6-881F-A2D2117DBF4D}
Expand All @@ -659,6 +672,7 @@ Global
{DAAC2822-63B6-4DE0-83AE-04873CD2F364} = {72397ADB-40A8-4B8E-8E08-2DBE2803C845}
{FBB3270F-1924-4A72-845E-A6DF39C402F6} = {7AC28763-9C68-4BF9-A1BA-25CBFFD2D15C}
{92644F6F-5946-48FC-A21A-A3D6EE24E8B3} = {C564DDD6-DE79-45CD-88EA-3F690481572A}
{1F2E3D4C-5B6A-7890-CDEF-123456789ABC} = {C564DDD6-DE79-45CD-88EA-3F690481572A}
{E8AD265B-3C67-4640-AC58-A522F9FB3361} = {09C264E9-E3F3-4586-9151-DCBB1F6DA7AB}
{C564DDD6-DE79-45CD-88EA-3F690481572A} = {09C264E9-E3F3-4586-9151-DCBB1F6DA7AB}
{50C758FE-4E10-409A-94F5-A75480960864} = {459BF674-83CB-46F6-881F-A2D2117DBF4D}
Expand Down
186 changes: 186 additions & 0 deletions src/Core/src/ConfigurationSourceGen/AppSettingsSourceGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.Maui.Core.ConfigurationSourceGen;

[Generator]
public class AppSettingsSourceGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get additional files (like appsettings.json) and combine them
var appSettingsProvider = context.AdditionalTextsProvider
.Where(static file => Path.GetFileName(file.Path).Equals("appsettings.json", StringComparison.OrdinalIgnoreCase))
.Select(static (file, cancellationToken) =>
{
var content = file.GetText(cancellationToken)?.ToString();
return content;
})
.Where(static content => !string.IsNullOrEmpty(content))
.Collect(); // Collect all appsettings.json files into a single value

// Generate source when we have any appsettings.json files
context.RegisterSourceOutput(appSettingsProvider, static (context, contents) =>
{
try
{
if (contents.IsEmpty)
return;

// Combine all appsettings files into one configuration
var allConfigurationEntries = new Dictionary<string, string>();

foreach (var content in contents)
{
if (!string.IsNullOrEmpty(content))
{
var entries = ParseJsonToConfigurationEntries(content!);
foreach (var entry in entries)
{
allConfigurationEntries[entry.Key] = entry.Value; // Later files override earlier ones
}
}
}

// Generate the extension method source code
var sourceCode = GenerateExtensionMethod(allConfigurationEntries);

// Add the generated source to the compilation
context.AddSource("LocalAppSettingsExtensions.g.cs", SourceText.From(sourceCode, Encoding.UTF8));
}
catch (Exception ex)
{
// Add diagnostic for any errors
context.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor(
"MAS001",
"AppSettings Source Generator Error",
"Error generating app settings extension: {0}",
"MauiAppSettings",
DiagnosticSeverity.Warning,
isEnabledByDefault: true),
Location.None,
ex.Message));
}
});
}

private static Dictionary<string, string> ParseJsonToConfigurationEntries(string jsonContent)
{
var entries = new Dictionary<string, string>();

try
{
using var document = JsonDocument.Parse(jsonContent);
FlattenJsonElement(document.RootElement, entries, string.Empty);
}
catch (JsonException)
{
// If JSON parsing fails, return empty dictionary
}

return entries;
}

private static void FlattenJsonElement(JsonElement element, Dictionary<string, string> entries, string prefix)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
var key = string.IsNullOrEmpty(prefix) ? property.Name : $"{prefix}:{property.Name}";
FlattenJsonElement(property.Value, entries, key);
}
break;

case JsonValueKind.Array:
var index = 0;
foreach (var item in element.EnumerateArray())
{
var key = $"{prefix}:{index}";
FlattenJsonElement(item, entries, key);
index++;
}
break;

case JsonValueKind.String:
entries[prefix] = element.GetString() ?? string.Empty;
break;

case JsonValueKind.Number:
entries[prefix] = element.GetRawText();
break;

case JsonValueKind.True:
case JsonValueKind.False:
entries[prefix] = element.GetBoolean().ToString().ToLowerInvariant();
break;

case JsonValueKind.Null:
entries[prefix] = string.Empty;
break;
}
}

private static string GenerateExtensionMethod(Dictionary<string, string> configurationEntries)
{
var sourceBuilder = new StringBuilder();

sourceBuilder.AppendLine("//------------------------------------------------------------------------------");
sourceBuilder.AppendLine("// <auto-generated>");
sourceBuilder.AppendLine("// This code was generated by the MAUI AppSettings source generator.");
sourceBuilder.AppendLine("//");
sourceBuilder.AppendLine("// Changes to this file may cause incorrect behavior and will be lost if");
sourceBuilder.AppendLine("// the code is regenerated.");
sourceBuilder.AppendLine("// </auto-generated>");
sourceBuilder.AppendLine("//------------------------------------------------------------------------------");
sourceBuilder.AppendLine();
sourceBuilder.AppendLine("using System.Collections.Generic;");
sourceBuilder.AppendLine("using Microsoft.Extensions.Configuration;");
sourceBuilder.AppendLine();
sourceBuilder.AppendLine("namespace Microsoft.Extensions.Configuration");
sourceBuilder.AppendLine("{");
sourceBuilder.AppendLine(" /// <summary>");
sourceBuilder.AppendLine(" /// Extension methods for IConfigurationBuilder to add local app settings.");
sourceBuilder.AppendLine(" /// </summary>");
sourceBuilder.AppendLine(" public static class LocalAppSettingsExtensions");
sourceBuilder.AppendLine(" {");
sourceBuilder.AppendLine(" /// <summary>");
sourceBuilder.AppendLine(" /// Adds configuration values from the local appsettings.json file as an in-memory collection.");
sourceBuilder.AppendLine(" /// </summary>");
sourceBuilder.AppendLine(" /// <param name=\"configurationBuilder\">The configuration builder.</param>");
sourceBuilder.AppendLine(" /// <returns>The configuration builder.</returns>");
sourceBuilder.AppendLine(" public static IConfigurationBuilder AddLocalAppSettings(this IConfigurationBuilder configurationBuilder)");
sourceBuilder.AppendLine(" {");
sourceBuilder.AppendLine(" var configurationData = new Dictionary<string, string>");
sourceBuilder.AppendLine(" {");

foreach (var entry in configurationEntries)
{
var escapedKey = EscapeStringLiteral(entry.Key);
var escapedValue = EscapeStringLiteral(entry.Value);
sourceBuilder.AppendLine($" {{ \"{escapedKey}\", \"{escapedValue}\" }},");
}

sourceBuilder.AppendLine(" };");
sourceBuilder.AppendLine();
sourceBuilder.AppendLine(" return configurationBuilder.AddInMemoryCollection(configurationData);");
sourceBuilder.AppendLine(" }");
sourceBuilder.AppendLine(" }");
sourceBuilder.AppendLine("}");

return sourceBuilder.ToString();
}

private static string EscapeStringLiteral(string input)
{
return input.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", "\\t");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>true</ImplicitUsings>
<LangVersion>Latest</LangVersion>
<AssemblyName>Microsoft.Maui.Core.ConfigurationSourceGen</AssemblyName>
<RootNamespace>Microsoft.Maui.Core.ConfigurationSourceGen</RootNamespace>
<PackageId>Microsoft.Maui.Core.ConfigurationSourceGen</PackageId>
<IsPackable>false</IsPackable>
</PropertyGroup>

<PropertyGroup>
<IncludeBuildOutput>false</IncludeBuildOutput>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<IsRoslynComponent>true</IsRoslynComponent>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
<PackageReference Include="System.Text.Json" Version="8.0.0" PrivateAssets="all" />
</ItemGroup>

<Target Name="_CopyToBuildTasksDir" AfterTargets="Build">
<ItemGroup>
<_CopyItems Include="$(TargetDir)*.dll" Exclude="$(TargetDir)System.*.dll" />
<_CopyItems Include="$(TargetDir)*.pdb" Exclude="$(TargetDir)System.*.pdb" />
</ItemGroup>
<Copy SourceFiles="@(_CopyItems)" DestinationFolder="$(_MauiBuildTasksLocation)" ContinueOnError="true" Retries="0" />
</Target>
</Project>
14 changes: 14 additions & 0 deletions src/Core/src/Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@

<Import Project="$(MauiSrcDirectory)MultiTargeting.targets" />

<ItemGroup>
<Compile Remove="ConfigurationSourceGen\**" />
<EmbeddedResource Remove="ConfigurationSourceGen\**" />
<None Remove="ConfigurationSourceGen\**" />
</ItemGroup>

<ItemGroup>
<ProjectReference
Include="ConfigurationSourceGen\Core.ConfigurationSourceGen.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="MemoryAnalyzers" />
<PackageReference Include="Microsoft.Extensions.Configuration" />
Expand Down Expand Up @@ -69,6 +82,7 @@
<None Remove="nuget\**" />
<None Include="nuget\**" Exclude="nuget\**\*.in.*;nuget\**\net-windows\*" PackagePath="" Pack="true" />
<None Include="nuget\buildTransitive\net-windows\**" PackagePath="buildTransitive\net$(_MauiMinimumSupportedDotNetTfm)-windows$(MinimumWindowsTargetFrameworkVersion)" Pack="true" />
<None Include="$(_MauiBuildTasksLocation)Microsoft.Maui.Core.ConfigurationSourceGen.dll" PackagePath="buildTransitive" Pack="true" />
</ItemGroup>

<!-- TypeScript compilation -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,9 @@
<AfterMicrosoftNETSdkTargets>$(AfterMicrosoftNETSdkTargets);$(MSBuildThisFileDirectory)Microsoft.Maui.Core.After.targets</AfterMicrosoftNETSdkTargets>
</PropertyGroup>

<!-- Enable Configuration Source Generator -->
<ItemGroup Condition=" '$(DisableMauiAnalyzers)' != 'true' ">
<Analyzer Include="$(MSBuildThisFileDirectory)Microsoft.Maui.Core.ConfigurationSourceGen.dll" IsImplicitlyDefined="true" />
</ItemGroup>

</Project>
Loading
Loading