Skip to content

Commit fd96d14

Browse files
authored
Prevent exception if there are no options types with the attribute. (#4)
1 parent 06827df commit fd96d14

File tree

3 files changed

+42
-2
lines changed

3 files changed

+42
-2
lines changed

OptionsBindingsGenerator.UnitTests/Tests.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,31 @@ public void Setup()
1717
implementationAssembly = GetAssembly("OptionsBindingsGenerator");
1818
}
1919

20+
[Test]
21+
public async Task NoBindings()
22+
{
23+
var source = await ReadCSharpFile<NoBindingsOptions>(true);
24+
25+
await new VerifyCS.Test
26+
{
27+
CompilerDiagnostics = CompilerDiagnostics.None,
28+
TestState = {
29+
ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
30+
AdditionalReferences =
31+
{
32+
implementationAssembly,
33+
GetAssembly("TestLibrary")
34+
},
35+
36+
Sources = { source },
37+
GeneratedSources =
38+
{
39+
40+
},
41+
},
42+
}.RunAsync();
43+
}
44+
2045
[Test]
2146
public async Task MixedBindings()
2247
{

OptionsBindingsGenerator/Main.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Immutable;
3+
using System.Linq;
34
using System.Text;
45
using System.Threading;
56
using Microsoft.CodeAnalysis;
@@ -36,9 +37,12 @@ private static INamedTypeSymbol GetSemanticTargetForGeneration(GeneratorAttribut
3637

3738
private static void Execute(SourceProductionContext context, ImmutableArray<INamedTypeSymbol> typeSymbols)
3839
{
39-
var (source, className) = OutputGenerator.GenerateOutput(typeSymbols);
40+
if (typeSymbols.Any())
41+
{
42+
var (source, className) = OutputGenerator.GenerateOutput(typeSymbols);
4043

41-
context.AddSource($"{className}.generated.cs", SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha256));
44+
context.AddSource($"{className}.generated.cs", SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha256));
45+
}
4246
}
4347
}
4448
}

TestLibrary/NoBindingsOptions.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
using System.ComponentModel.DataAnnotations;
2+
3+
namespace TestLibrary;
4+
5+
internal record NoBindingsOptions
6+
{
7+
[Required]
8+
public required string ServiceHost { get; init; }
9+
10+
public required string Port { get; init; }
11+
}

0 commit comments

Comments
 (0)