From 1c41b6b753aad942af0d40e5b16100fdf99dc747 Mon Sep 17 00:00:00 2001 From: CodingFlow <3643313+CodingFlow@users.noreply.github.com> Date: Mon, 15 Dec 2025 19:43:56 -0500 Subject: [PATCH] Prevent exception if there are no options types with the attribute. --- OptionsBindingsGenerator.UnitTests/Tests.cs | 25 +++++++++++++++++++++ OptionsBindingsGenerator/Main.cs | 8 +++++-- TestLibrary/NoBindingsOptions.cs | 11 +++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 TestLibrary/NoBindingsOptions.cs diff --git a/OptionsBindingsGenerator.UnitTests/Tests.cs b/OptionsBindingsGenerator.UnitTests/Tests.cs index 1b6f86d..e498d76 100644 --- a/OptionsBindingsGenerator.UnitTests/Tests.cs +++ b/OptionsBindingsGenerator.UnitTests/Tests.cs @@ -17,6 +17,31 @@ public void Setup() implementationAssembly = GetAssembly("OptionsBindingsGenerator"); } + [Test] + public async Task NoBindings() + { + var source = await ReadCSharpFile(true); + + await new VerifyCS.Test + { + CompilerDiagnostics = CompilerDiagnostics.None, + TestState = { + ReferenceAssemblies = ReferenceAssemblies.Net.Net90, + AdditionalReferences = + { + implementationAssembly, + GetAssembly("TestLibrary") + }, + + Sources = { source }, + GeneratedSources = + { + + }, + }, + }.RunAsync(); + } + [Test] public async Task MixedBindings() { diff --git a/OptionsBindingsGenerator/Main.cs b/OptionsBindingsGenerator/Main.cs index b810d52..802ddc1 100644 --- a/OptionsBindingsGenerator/Main.cs +++ b/OptionsBindingsGenerator/Main.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Immutable; +using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; @@ -36,9 +37,12 @@ private static INamedTypeSymbol GetSemanticTargetForGeneration(GeneratorAttribut private static void Execute(SourceProductionContext context, ImmutableArray typeSymbols) { - var (source, className) = OutputGenerator.GenerateOutput(typeSymbols); + if (typeSymbols.Any()) + { + var (source, className) = OutputGenerator.GenerateOutput(typeSymbols); - context.AddSource($"{className}.generated.cs", SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha256)); + context.AddSource($"{className}.generated.cs", SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha256)); + } } } } \ No newline at end of file diff --git a/TestLibrary/NoBindingsOptions.cs b/TestLibrary/NoBindingsOptions.cs new file mode 100644 index 0000000..02e351e --- /dev/null +++ b/TestLibrary/NoBindingsOptions.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace TestLibrary; + +internal record NoBindingsOptions +{ + [Required] + public required string ServiceHost { get; init; } + + public required string Port { get; init; } +}