diff --git a/docs/docs/operator/migration.mdx b/docs/docs/operator/migration.mdx
index b4602a9c8..157d2fc3f 100644
--- a/docs/docs/operator/migration.mdx
+++ b/docs/docs/operator/migration.mdx
@@ -76,6 +76,38 @@ Action required if you use custom queue components:
## Upgrading from v12 to v13
+### Generator multi-assembly composition
+
+The source generator now supports **multi-assembly composition**: controllers, finalizers and
+entities may live in referenced class libraries that also reference `KubeOps.Generator`.
+
+- Assemblies containing controllers or finalizers are marked with an assembly-level
+ `KubeOpsGeneratedRegistrationsAttribute`. The generated `RegisterComponents` of the consuming
+ compilation discovers these markers on all transitively referenced assemblies and registers
+ every assembly's components exactly once — components in referenced class libraries are now
+ registered automatically.
+- `ControllerRegistrations`, `FinalizerRegistrations`, `EntityDefinitions` and
+ `EntityInitializer` are only generated when the compilation contains matching components.
+ `EntityDefinitions` only lists entities declared in the compilation itself; entities from
+ referenced assemblies are listed by their declaring assembly.
+ `RegisterComponents` is generated whenever the compilation references `KubeOps.Operator` or
+ contains/references components, and only invokes the parts that exist.
+- The shared generated classes remain in the **global namespace** by default. When multiple
+ projects of one solution use the generator, set the new `KubeOpsGeneratorNamespace` MSBuild
+ property (e.g. to `$(RootNamespace)`) in the participating projects so the generated class
+ names do not conflict. The generator reports the warning **KOG002** and skips the conflicting
+ registration when it detects such a clash. Note that with the property set, top-level
+ `Program.cs` files need a using directive for the configured namespace so that
+ `RegisterComponents()` resolves.
+- `OperatorBuilderExtensions.RegisterComponents` and the `EntityInitializer.Initialize()`
+ extensions are now generated as `internal`. They are only meaningful for the compilation they
+ are generated into; keeping them invisible across assembly boundaries rules out ambiguous
+ extension method calls when multiple assemblies use the generator. This only affects the exotic
+ case of calling these generated extensions **from a different assembly** — such setups were
+ already broken by ambiguous calls as soon as two projects referenced the generator. If another
+ assembly relied on calling them, reference the generator in that assembly instead — it
+ generates its own.
+
v13 makes it possible to register **multiple controllers for the same entity type**, each with its
own label or field selector (see
[Multiple Controllers per Entity](./building-blocks/controllers#multiple-controllers-per-entity)).
diff --git a/docs/docs/operator/troubleshooting.mdx b/docs/docs/operator/troubleshooting.mdx
index 237f649b1..8466680b0 100644
--- a/docs/docs/operator/troubleshooting.mdx
+++ b/docs/docs/operator/troubleshooting.mdx
@@ -121,6 +121,27 @@ Install the CRDs before or with the operator: generate them with the [CLI](./cli
(`kubeops generate operator`), apply them as part of the [deployment](./deployment), or — for
development only — use the [CRD Installer](./configuration/crd-installer).
+## `RegisterComponents()` is not found (CS1061)
+
+**Symptom:** The build fails with `'IOperatorBuilder' does not contain a definition for
+'RegisterComponents'`.
+
+Make sure the `KubeOps.Generator` package is referenced and the project compiles otherwise —
+source generators do not run on broken compilations. If the `KubeOpsGeneratorNamespace` MSBuild
+property is set, the generated classes live in that namespace instead of the global namespace;
+top-level `Program.cs` files then need a matching using directive (e.g. `using MyOperator;`).
+
+## Components of a referenced library are not registered / warning KOG002
+
+**Symptom:** Controllers or finalizers that live in a referenced class library never reconcile,
+and the build reports `KOG002`.
+
+Two assemblies in the reference chain generate registration classes with the same fully qualified
+name (by default, the global namespace is used). The generator skips the conflicting registration
+instead of emitting ambiguous code. Set the `KubeOpsGeneratorNamespace` MSBuild property (e.g. to
+`$(RootNamespace)`) in the conflicting projects so each assembly generates into its own
+namespace — see [KubeOps.Generator](../packages/generator).
+
## Leader election issues
See [Leader Election — Troubleshooting](./configuration/leader-election#troubleshooting) for lease
diff --git a/src/KubeOps.Abstractions/Builder/KubeOpsGeneratedRegistrationsAttribute.cs b/src/KubeOps.Abstractions/Builder/KubeOpsGeneratedRegistrationsAttribute.cs
new file mode 100644
index 000000000..91601e56b
--- /dev/null
+++ b/src/KubeOps.Abstractions/Builder/KubeOpsGeneratedRegistrationsAttribute.cs
@@ -0,0 +1,52 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the Apache 2.0 License.
+// See the LICENSE file in the project root for more information.
+
+namespace KubeOps.Abstractions.Builder;
+
+///
+/// Marks an assembly as containing KubeOps source-generated registration classes.
+///
+///
+///
+/// The KubeOps source generator applies this attribute automatically to every assembly that
+/// contains controllers or finalizers; it is not meant to be applied manually.
+///
+///
+/// The referenced registration classes register only the components that are defined in the
+/// annotated assembly itself (they never chain into further assemblies). A consuming compilation
+/// discovers these attributes on all (transitively) referenced assemblies and invokes every
+/// registration class exactly once from its own generated RegisterComponents method.
+/// This flat composition guarantees that no component is registered twice, regardless of how the
+/// assemblies reference each other.
+///
+///
+///
+/// The fully qualified name (without global::) of the generated class whose
+/// RegisterControllers method registers the controllers of the annotated assembly,
+/// or null if the assembly contains no controllers.
+///
+///
+/// The fully qualified name (without global::) of the generated class whose
+/// RegisterFinalizers method registers the finalizers of the annotated assembly,
+/// or null if the assembly contains no finalizers.
+///
+[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
+public sealed class KubeOpsGeneratedRegistrationsAttribute(
+ string? controllerRegistrations,
+ string? finalizerRegistrations) : Attribute
+{
+ ///
+ /// Gets the fully qualified name (without global::) of the generated class whose
+ /// RegisterControllers method registers the controllers of the annotated assembly,
+ /// or null if the assembly contains no controllers.
+ ///
+ public string? ControllerRegistrations { get; } = controllerRegistrations;
+
+ ///
+ /// Gets the fully qualified name (without global::) of the generated class whose
+ /// RegisterFinalizers method registers the finalizers of the annotated assembly,
+ /// or null if the assembly contains no finalizers.
+ ///
+ public string? FinalizerRegistrations { get; } = finalizerRegistrations;
+}
diff --git a/src/KubeOps.Generator/AnalyzerReleases.Unshipped.md b/src/KubeOps.Generator/AnalyzerReleases.Unshipped.md
index b4ae38191..cd5c579ca 100644
--- a/src/KubeOps.Generator/AnalyzerReleases.Unshipped.md
+++ b/src/KubeOps.Generator/AnalyzerReleases.Unshipped.md
@@ -5,4 +5,5 @@
Rule ID | Category | Severity | Notes
--------|----------|----------|-------------------------------------------------------------------------
-KOG001 | KubeOps.Generator | Error | Controller declares both [LabelSelector] and [FieldSelector]
\ No newline at end of file
+KOG001 | KubeOps.Generator | Error | Controller declares both [LabelSelector] and [FieldSelector]
+KOG002 | KubeOps.Generator | Warning | Conflicting generated registration class names; the conflicting referenced registration is skipped. Set the KubeOpsGeneratorNamespace MSBuild property to disambiguate.
diff --git a/src/KubeOps.Generator/Discovery/EntityDiscovery.cs b/src/KubeOps.Generator/Discovery/EntityDiscovery.cs
index 013c77d2a..9852a643e 100644
--- a/src/KubeOps.Generator/Discovery/EntityDiscovery.cs
+++ b/src/KubeOps.Generator/Discovery/EntityDiscovery.cs
@@ -70,7 +70,10 @@ public static IncrementalValueProvider> Ge
.Where(static f => f is not null)
.Select(static (f, _) => f!.Value)
.Collect()
- .Select(static (arr, _) => new EquatableArray(arr.Distinct().ToImmutableArray()));
+ .Select(static (arr, _) => new EquatableArray(arr
+ .GroupBy(static f => f with { Location = null })
+ .Select(static g => g.First())
+ .ToImmutableArray()));
private static EquatableArray Merge(
ImmutableArray local,
@@ -255,7 +258,8 @@ private static ImmutableArray GetReferencedEntities(GeneratorS
: new FinalizerRegistration(
classSymbol!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
classSymbol.Name,
- entity);
+ entity,
+ LocationInfo.CreateFrom(context.Node));
}
private static string? GetImplementedEntity(
diff --git a/src/KubeOps.Generator/Discovery/FinalizerRegistration.cs b/src/KubeOps.Generator/Discovery/FinalizerRegistration.cs
index 82acd2afc..4a12ffb0b 100644
--- a/src/KubeOps.Generator/Discovery/FinalizerRegistration.cs
+++ b/src/KubeOps.Generator/Discovery/FinalizerRegistration.cs
@@ -7,4 +7,5 @@ namespace KubeOps.Generator.Discovery;
internal record struct FinalizerRegistration(
string FullyQualifiedFinalizer,
string IdentifierName,
- string FullyQualifiedEntityName);
+ string FullyQualifiedEntityName,
+ LocationInfo? Location = null);
diff --git a/src/KubeOps.Generator/Discovery/GeneratorOptions.cs b/src/KubeOps.Generator/Discovery/GeneratorOptions.cs
new file mode 100644
index 000000000..fbb35846e
--- /dev/null
+++ b/src/KubeOps.Generator/Discovery/GeneratorOptions.cs
@@ -0,0 +1,51 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the Apache 2.0 License.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+
+namespace KubeOps.Generator.Discovery;
+
+internal static class GeneratorOptions
+{
+ private const string GeneratorNamespaceProperty = "build_property.KubeOpsGeneratorNamespace";
+
+ public static IncrementalValueProvider GetGeneratorNamespace(
+ IncrementalGeneratorInitializationContext context)
+ => context.AnalyzerConfigOptionsProvider.Select(static (options, _) =>
+ options.GlobalOptions.TryGetValue(GeneratorNamespaceProperty, out var generatorNamespace)
+ && !string.IsNullOrWhiteSpace(generatorNamespace)
+ ? SanitizeNamespace(generatorNamespace)
+ : null);
+
+ private static string? SanitizeNamespace(string @namespace)
+ {
+ var segments = @namespace
+ .Split('.')
+ .Select(SanitizeSegment)
+ .Where(segment => segment.Length > 0)
+ .ToArray();
+
+ return segments.Length == 0 ? null : string.Join(".", segments);
+ }
+
+ private static string SanitizeSegment(string segment)
+ {
+ var sanitized = new string(segment
+ .Select(c => char.IsLetterOrDigit(c) || c == '_' ? c : '_')
+ .ToArray());
+
+ if (sanitized.Length == 0)
+ {
+ return sanitized;
+ }
+
+ if (char.IsDigit(sanitized[0]) || SyntaxFacts.GetKeywordKind(sanitized) != SyntaxKind.None)
+ {
+ sanitized = "_" + sanitized;
+ }
+
+ return sanitized;
+ }
+}
diff --git a/src/KubeOps.Generator/Discovery/ReferencedRegistrations.cs b/src/KubeOps.Generator/Discovery/ReferencedRegistrations.cs
new file mode 100644
index 000000000..c751bcb08
--- /dev/null
+++ b/src/KubeOps.Generator/Discovery/ReferencedRegistrations.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the Apache 2.0 License.
+// See the LICENSE file in the project root for more information.
+
+namespace KubeOps.Generator.Discovery;
+
+///
+/// Registration classes of a referenced assembly, discovered via the
+/// KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrationsAttribute assembly marker.
+/// The class names are fully qualified but carry no global:: prefix.
+///
+internal record struct ReferencedRegistrations(
+ string AssemblyName,
+ string? ControllerRegistrations,
+ string? FinalizerRegistrations);
diff --git a/src/KubeOps.Generator/Discovery/RegistrationDiscovery.cs b/src/KubeOps.Generator/Discovery/RegistrationDiscovery.cs
new file mode 100644
index 000000000..f9f20d98a
--- /dev/null
+++ b/src/KubeOps.Generator/Discovery/RegistrationDiscovery.cs
@@ -0,0 +1,109 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the Apache 2.0 License.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Immutable;
+
+using Microsoft.CodeAnalysis;
+
+namespace KubeOps.Generator.Discovery;
+
+internal static class RegistrationDiscovery
+{
+ private const string AbstractionsAssemblyName = "KubeOps.Abstractions";
+
+ private const string RegistrationsAttributeName = "KubeOpsGeneratedRegistrationsAttribute";
+
+ private const string RegistrationsAttributeFullName =
+ "KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrationsAttribute";
+
+ // Public key tokens of .NET platform assemblies (BCL, netstandard, ASP.NET Core / extensions,
+ // WPF). Platform assemblies never reference user code, so their subgraphs cannot contain
+ // marked assemblies and are skipped entirely - the framework closure is by far the largest
+ // part of a compilation's reference graph, and the discovery runs on every edit.
+ private static readonly HashSet PlatformPublicKeyTokens = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "b77a5c561934e089", // mscorlib / System.*
+ "b03f5f7f11d50a3a", // System.* / Microsoft.*
+ "7cec85d7bea7798e", // System.Private.CoreLib
+ "cc7b13ffcd2ddd51", // netstandard
+ "adb9793829ddae60", // Microsoft.Extensions.* / ASP.NET Core
+ "31bf3856ad364e35", // WPF / WindowsBase
+ };
+
+ public static IncrementalValueProvider> GetReferencedRegistrations(
+ IncrementalGeneratorInitializationContext context)
+ => context.CompilationProvider.Select(static (compilation, cancellationToken) =>
+ {
+ var registrations = new List();
+ var visited = new HashSet(StringComparer.Ordinal);
+ var queue = new Queue();
+
+ foreach (var assembly in compilation.SourceModule.ReferencedAssemblySymbols)
+ {
+ queue.Enqueue(assembly);
+ }
+
+ while (queue.Count > 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var assembly = queue.Dequeue();
+ if (!visited.Add(assembly.Identity.GetDisplayName()) || IsPlatformAssembly(assembly))
+ {
+ continue;
+ }
+
+ // Only assemblies that reference KubeOps.Abstractions can carry the marker
+ // attribute (its type lives there), so the attribute decoding is skipped for all
+ // others. The check works on plain assembly identities and does not resolve any
+ // further symbols.
+ if (ReferencesAbstractions(assembly))
+ {
+ var attribute = assembly.GetAttributes().FirstOrDefault(a =>
+ a.AttributeClass is { Name: RegistrationsAttributeName } attributeClass
+ && attributeClass.ToDisplayString() == RegistrationsAttributeFullName);
+
+ if (attribute is not null)
+ {
+ registrations.Add(new ReferencedRegistrations(
+ assembly.Name,
+ GetConstructorArgument(attribute, 0),
+ GetConstructorArgument(attribute, 1)));
+ }
+ }
+
+ foreach (var module in assembly.Modules)
+ {
+ foreach (var referenced in module.ReferencedAssemblySymbols)
+ {
+ queue.Enqueue(referenced);
+ }
+ }
+ }
+
+ registrations.Sort((left, right) => string.CompareOrdinal(left.AssemblyName, right.AssemblyName));
+ return new EquatableArray(registrations.ToImmutableArray());
+ });
+
+ private static bool IsPlatformAssembly(IAssemblySymbol assembly)
+ {
+ var publicKeyToken = assembly.Identity.PublicKeyToken;
+ if (publicKeyToken.IsDefaultOrEmpty)
+ {
+ return false;
+ }
+
+ return PlatformPublicKeyTokens.Contains(
+ string.Concat(publicKeyToken.Select(b => b.ToString("x2"))));
+ }
+
+ private static bool ReferencesAbstractions(IAssemblySymbol assembly)
+ => assembly.Modules.Any(m => m.ReferencedAssemblies.Any(id =>
+ string.Equals(id.Name, AbstractionsAssemblyName, StringComparison.OrdinalIgnoreCase)));
+
+ private static string? GetConstructorArgument(AttributeData attribute, int index)
+ => attribute.ConstructorArguments.Length > index
+ ? attribute.ConstructorArguments[index].Value as string
+ : null;
+}
diff --git a/src/KubeOps.Generator/Generators/ControllerRegistrationGenerator.cs b/src/KubeOps.Generator/Generators/ControllerRegistrationGenerator.cs
index bb194e5c6..71055d283 100644
--- a/src/KubeOps.Generator/Generators/ControllerRegistrationGenerator.cs
+++ b/src/KubeOps.Generator/Generators/ControllerRegistrationGenerator.cs
@@ -32,14 +32,17 @@ internal sealed class ControllerRegistrationGenerator : IIncrementalGenerator
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterSourceOutput(
- EntityDiscovery.GetControllers(context).Combine(EntityDiscovery.GetEntities(context)),
- (spc, source) => Execute(spc, source.Left, source.Right));
+ EntityDiscovery.GetControllers(context)
+ .Combine(EntityDiscovery.GetEntities(context))
+ .Combine(GeneratorOptions.GetGeneratorNamespace(context)),
+ (spc, source) => Execute(spc, source.Left.Left, source.Left.Right, source.Right));
}
private static void Execute(
SourceProductionContext context,
EquatableArray controllers,
- EquatableArray entities)
+ EquatableArray entities,
+ string? generatorNamespace)
{
// Controllers that declare both a label and a field selector are reported as an error and excluded
// from registration, so no misleading label-only registration is emitted for them.
@@ -59,6 +62,19 @@ private static void Execute(
validControllers.Add(controller);
}
+ var registrations = validControllers
+ .Where(c => entities.Any(e =>
+ e.ClassDeclaration.FullyQualifiedName == c.FullyQualifiedEntityName))
+ .OrderBy(c => c.FullyQualifiedEntityName, StringComparer.Ordinal)
+ .Select(c => (Controller: c, Entity: entities.First(e =>
+ e.ClassDeclaration.FullyQualifiedName == c.FullyQualifiedEntityName)))
+ .ToList();
+
+ if (registrations.Count == 0)
+ {
+ return;
+ }
+
var declaration = CompilationUnit()
.WithUsings(
List(
@@ -67,7 +83,8 @@ private static void Execute(
UsingDirective(IdentifierName("KubeOps.Abstractions.Builder")),
}))
.WithLeadingTrivia(AutoGeneratedSyntaxTrivia.Instance)
- .WithMembers(SingletonList(ClassDeclaration("ControllerRegistrations")
+ .AddNamespaceScope(generatorNamespace)
+ .AddMembers(ClassDeclaration("ControllerRegistrations")
.WithModifiers(TokenList(
Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
.AddMembers(MethodDeclaration(IdentifierName("IOperatorBuilder"), "RegisterControllers")
@@ -83,19 +100,14 @@ private static void Execute(
.WithType(
IdentifierName("IOperatorBuilder")))))
.WithBody(Block(
- validControllers
- .Where(c => entities.Any(e =>
- e.ClassDeclaration.FullyQualifiedName == c.FullyQualifiedEntityName))
- .OrderBy(c => c.FullyQualifiedEntityName, StringComparer.Ordinal)
- .Select(c => (Controller: c, Entity: entities.First(e =>
- e.ClassDeclaration.FullyQualifiedName == c.FullyQualifiedEntityName)))
+ registrations
.Select(e => ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("builder"),
RegistrationMethodFor(e.Controller, e.Entity)))))
- .Append(ReturnStatement(IdentifierName("builder"))))))))
+ .Append(ReturnStatement(IdentifierName("builder")))))))
.NormalizeWhitespace();
context.AddSource(
diff --git a/src/KubeOps.Generator/Generators/EntityDefinitionGenerator.cs b/src/KubeOps.Generator/Generators/EntityDefinitionGenerator.cs
index 1114acabc..9b90fb482 100644
--- a/src/KubeOps.Generator/Generators/EntityDefinitionGenerator.cs
+++ b/src/KubeOps.Generator/Generators/EntityDefinitionGenerator.cs
@@ -20,11 +20,27 @@ internal sealed class EntityDefinitionGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
- context.RegisterSourceOutput(EntityDiscovery.GetEntities(context), Execute);
+ context.RegisterSourceOutput(
+ EntityDiscovery.GetEntities(context).Combine(GeneratorOptions.GetGeneratorNamespace(context)),
+ (spc, source) => Execute(spc, source.Left, source.Right));
}
- private static void Execute(SourceProductionContext context, EquatableArray entities)
+ private static void Execute(
+ SourceProductionContext context,
+ EquatableArray entities,
+ string? generatorNamespace)
{
+ // Only entities declared in this compilation: entities discovered through usage of
+ // referenced assemblies belong to (and are listed by) the assembly that declares them.
+ var localEntities = entities
+ .Where(e => !e.ClassDeclaration.IsFromReferencedAssembly)
+ .ToList();
+
+ if (localEntities.Count == 0)
+ {
+ return;
+ }
+
var declaration = CompilationUnit()
.WithUsings(
List(
@@ -34,11 +50,12 @@ private static void Execute(SourceProductionContext context, EquatableArray(ClassDeclaration("EntityDefinitions")
+ .AddNamespaceScope(generatorNamespace)
+ .AddMembers(ClassDeclaration("EntityDefinitions")
.WithModifiers(TokenList(
Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
.WithMembers(
- List(entities
+ List(localEntities
.OrderBy(e => e.ClassDeclaration.FullyQualifiedName, StringComparer.Ordinal)
.Select(e => FieldDeclaration(
VariableDeclaration(
@@ -80,7 +97,7 @@ private static void Execute(SourceProductionContext context, EquatableArray Execute(spc, source.Left, source.Right));
}
- private static void Execute(SourceProductionContext context, EquatableArray entities)
+ private static void Execute(
+ SourceProductionContext context,
+ EquatableArray entities,
+ string? generatorNamespace)
{
// for each partial defined entity, create a partial class that
// introduces a default constructor that initializes the ApiVersion and Kind.
@@ -89,13 +94,22 @@ private static void Execute(SourceProductionContext context, EquatableArray e.ClassDeclaration.IsFromReferencedAssembly || !e.ClassDeclaration.IsPartial || e.ClassDeclaration.HasParameterlessConstructor)
+ .OrderBy(e => e.ClassDeclaration.FullyQualifiedName, StringComparer.Ordinal)
+ .ToList();
+
+ if (staticInitializedEntities.Count == 0)
+ {
+ return;
+ }
+
var staticInitializers = CompilationUnit()
- .WithMembers(SingletonList(ClassDeclaration("EntityInitializer")
+ .AddNamespaceScope(generatorNamespace)
+ .AddMembers(ClassDeclaration("EntityInitializer")
.WithModifiers(TokenList(
- Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
- .WithMembers(List(entities
- .Where(e => e.ClassDeclaration.IsFromReferencedAssembly || !e.ClassDeclaration.IsPartial || e.ClassDeclaration.HasParameterlessConstructor)
- .OrderBy(e => e.ClassDeclaration.FullyQualifiedName, StringComparer.Ordinal)
+ Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.StaticKeyword)))
+ .WithMembers(List(staticInitializedEntities
.Select(e => (Entity: e, ClassIdentifier: e.ClassDeclaration.FullyQualifiedName))
.Select(e => MethodDeclaration(
IdentifierName(e.ClassIdentifier),
@@ -131,7 +145,7 @@ private static void Execute(SourceProductionContext context, EquatableArray Execute(spc, source.Left, source.Right));
+ EntityDiscovery.GetFinalizers(context)
+ .Combine(EntityDiscovery.GetEntities(context))
+ .Combine(GeneratorOptions.GetGeneratorNamespace(context)),
+ (spc, source) => Execute(spc, source.Left.Left, source.Left.Right, source.Right));
}
private static void Execute(
SourceProductionContext context,
EquatableArray finalizerRegistrations,
- EquatableArray entities)
+ EquatableArray entities,
+ string? generatorNamespace)
{
var finalizers = finalizerRegistrations
.Where(c => entities.Any(e =>
@@ -39,12 +42,18 @@ private static void Execute(
.Select(c => (c.FullyQualifiedFinalizer, c.IdentifierName, Entity: entities.First(e =>
e.ClassDeclaration.FullyQualifiedName == c.FullyQualifiedEntityName))).ToList();
+ if (finalizers.Count == 0)
+ {
+ return;
+ }
+
var declaration = CompilationUnit()
.WithUsings(
List(
new List { UsingDirective(IdentifierName("KubeOps.Abstractions.Builder")), }))
.WithLeadingTrivia(AutoGeneratedSyntaxTrivia.Instance)
- .WithMembers(SingletonList(ClassDeclaration("FinalizerRegistrations")
+ .AddNamespaceScope(generatorNamespace)
+ .AddMembers(ClassDeclaration("FinalizerRegistrations")
.WithModifiers(TokenList(
Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
.WithMembers(List(finalizers.Select(f =>
@@ -93,7 +102,7 @@ private static void Execute(
SingletonSeparatedList(
Argument(
IdentifierName($"{f.IdentifierName}Identifier")))))))
- .Append(ReturnStatement(IdentifierName("builder"))))))))
+ .Append(ReturnStatement(IdentifierName("builder")))))))
.NormalizeWhitespace();
context.AddSource(
diff --git a/src/KubeOps.Generator/Generators/GeneratorSyntaxExtensions.cs b/src/KubeOps.Generator/Generators/GeneratorSyntaxExtensions.cs
new file mode 100644
index 000000000..22c726a51
--- /dev/null
+++ b/src/KubeOps.Generator/Generators/GeneratorSyntaxExtensions.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the Apache 2.0 License.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+namespace KubeOps.Generator.Generators;
+
+internal static class GeneratorSyntaxExtensions
+{
+ public static CompilationUnitSyntax AddNamespaceScope(this CompilationUnitSyntax unit, string? @namespace)
+ => @namespace is null
+ ? unit
+ : unit.AddMembers(FileScopedNamespaceDeclaration(ParseName(@namespace)));
+
+ public static string QualifyWith(this string className, string? @namespace)
+ => @namespace is null ? className : $"{@namespace}.{className}";
+}
diff --git a/src/KubeOps.Generator/Generators/OperatorBuilderGenerator.cs b/src/KubeOps.Generator/Generators/OperatorBuilderGenerator.cs
index de630429b..39c6306c4 100644
--- a/src/KubeOps.Generator/Generators/OperatorBuilderGenerator.cs
+++ b/src/KubeOps.Generator/Generators/OperatorBuilderGenerator.cs
@@ -4,6 +4,8 @@
using System.Text;
+using KubeOps.Generator.Discovery;
+
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -13,26 +15,186 @@
namespace KubeOps.Generator.Generators;
+///
+/// Generates the RegisterComponents extension method that composes all component
+/// registrations of the compilation and its referenced assemblies. If the compilation contains
+/// controllers or finalizers itself, an assembly-level
+/// KubeOpsGeneratedRegistrationsAttribute marker is emitted so referencing compilations
+/// can compose the registrations of this assembly. Referenced registrations are always invoked
+/// through their marker (which only ever describes the components of its own assembly), never by
+/// chaining aggregate methods; every component is therefore registered exactly once.
+/// The aggregate class itself is internal: it is only meaningful for the compilation it is
+/// generated into, and keeping it invisible across assembly boundaries rules out ambiguous
+/// extension method calls when multiple assemblies use the generator.
+///
[Generator]
internal sealed class OperatorBuilderGenerator : IIncrementalGenerator
{
private const string BuilderIdentifier = "builder";
+ private const string ControllerRegistrationsClassName = "ControllerRegistrations";
+ private const string FinalizerRegistrationsClassName = "FinalizerRegistrations";
+
+ private const string RegistrationsAttributeFullName =
+ "KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations";
+
+ private const string OperatorAssemblyName = "KubeOps.Operator";
+
+ // Referenced registration classes must have unique fully qualified names to be invoked from the
+ // generated RegisterComponents. A clash (typically two assemblies using the global namespace
+ // default) would emit ambiguous code, so the conflicting registration is skipped and reported.
+ private static readonly DiagnosticDescriptor ConflictingRegistrations = new(
+ id: "KOG002",
+ title: "Conflicting generated registration class names",
+ messageFormat: "The generated registration class '{0}' of the referenced assembly '{1}' " +
+ "conflicts with another registration class of the same fully qualified name; its " +
+ "components are not registered by 'RegisterComponents'. Set the " +
+ "'KubeOpsGeneratorNamespace' MSBuild property in the conflicting projects to generate " +
+ "into distinct namespaces.",
+ category: "KubeOps.Generator",
+ defaultSeverity: DiagnosticSeverity.Warning,
+ isEnabledByDefault: true);
public void Initialize(IncrementalGeneratorInitializationContext context)
{
- context.RegisterPostInitializationOutput(Execute);
+ var referencesOperator = context.CompilationProvider.Select(static (compilation, _) =>
+ compilation.ReferencedAssemblyNames.Any(id =>
+ string.Equals(id.Name, OperatorAssemblyName, StringComparison.OrdinalIgnoreCase)));
+
+ context.RegisterSourceOutput(
+ EntityDiscovery.GetControllers(context)
+ .Combine(EntityDiscovery.GetFinalizers(context))
+ .Combine(EntityDiscovery.GetEntities(context))
+ .Combine(RegistrationDiscovery.GetReferencedRegistrations(context))
+ .Combine(GeneratorOptions.GetGeneratorNamespace(context))
+ .Combine(referencesOperator),
+ (spc, source) => Execute(
+ spc,
+ source.Left.Left.Left.Left.Left,
+ source.Left.Left.Left.Left.Right,
+ source.Left.Left.Left.Right,
+ source.Left.Left.Right,
+ source.Left.Right,
+ source.Right));
}
- private static void Execute(IncrementalGeneratorPostInitializationContext context)
+ private static void Execute(
+ SourceProductionContext context,
+ EquatableArray controllers,
+ EquatableArray finalizers,
+ EquatableArray entities,
+ EquatableArray referencedRegistrations,
+ string? generatorNamespace,
+ bool referencesOperator)
{
+ var ownControllers = controllers.Where(c => entities.Any(e =>
+ e.ClassDeclaration.FullyQualifiedName == c.FullyQualifiedEntityName)).ToList();
+ var ownFinalizers = finalizers.Where(f => entities.Any(e =>
+ e.ClassDeclaration.FullyQualifiedName == f.FullyQualifiedEntityName)).ToList();
+ var hasOwnControllers = ownControllers.Count > 0;
+ var hasOwnFinalizers = ownFinalizers.Count > 0;
+
+ // The aggregate is only useful where an operator host exists (KubeOps.Operator is
+ // referenced) or components are present; pure entity libraries get no empty class.
+ if (!hasOwnControllers && !hasOwnFinalizers && referencedRegistrations.Count == 0 && !referencesOperator)
+ {
+ return;
+ }
+
+ // Class names that are already taken in this compilation, each with the source location a
+ // conflict is anchored to (the declaration of the first own component; referenced
+ // registrations carry no source location). Referenced registration classes with an already
+ // taken fully qualified name cannot be invoked unambiguously and would lead to double
+ // registrations - they are skipped and reported via KOG002 instead.
+ var takenClassNames = new Dictionary(StringComparer.Ordinal);
+ if (hasOwnControllers)
+ {
+ takenClassNames.Add(
+ ControllerRegistrationsClassName.QualifyWith(generatorNamespace),
+ ownControllers[0].Location);
+ }
+
+ if (hasOwnFinalizers)
+ {
+ takenClassNames[FinalizerRegistrationsClassName.QualifyWith(generatorNamespace)] =
+ ownFinalizers[0].Location;
+ }
+
+ var statements = new List();
+
+ // Register the components of the own compilation via the sibling generated classes.
+ if (hasOwnControllers)
+ {
+ statements.Add(ParseStatement($"{BuilderIdentifier}.RegisterControllers();"));
+ }
+
+ if (hasOwnFinalizers)
+ {
+ statements.Add(ParseStatement($"{BuilderIdentifier}.RegisterFinalizers();"));
+ }
+
+ // Register the components of every marked referenced assembly exactly once. The markers
+ // always point to registration classes that only cover their own assembly, so this flat
+ // list can never register a component twice - regardless of how the assemblies reference
+ // each other.
+ foreach (var referenced in referencedRegistrations)
+ {
+ if (referenced.ControllerRegistrations is not null)
+ {
+ if (takenClassNames.TryGetValue(referenced.ControllerRegistrations, out var conflictAnchor))
+ {
+ context.ReportDiagnostic(Diagnostic.Create(
+ ConflictingRegistrations,
+ conflictAnchor?.ToLocation() ?? Location.None,
+ referenced.ControllerRegistrations,
+ referenced.AssemblyName));
+ }
+ else
+ {
+ takenClassNames.Add(referenced.ControllerRegistrations, null);
+ statements.Add(ParseStatement(
+ $"global::{referenced.ControllerRegistrations}.RegisterControllers({BuilderIdentifier});"));
+ }
+ }
+
+ if (referenced.FinalizerRegistrations is not null)
+ {
+ if (takenClassNames.TryGetValue(referenced.FinalizerRegistrations, out var conflictAnchor))
+ {
+ context.ReportDiagnostic(Diagnostic.Create(
+ ConflictingRegistrations,
+ conflictAnchor?.ToLocation() ?? Location.None,
+ referenced.FinalizerRegistrations,
+ referenced.AssemblyName));
+ }
+ else
+ {
+ takenClassNames.Add(referenced.FinalizerRegistrations, null);
+ statements.Add(ParseStatement(
+ $"global::{referenced.FinalizerRegistrations}.RegisterFinalizers({BuilderIdentifier});"));
+ }
+ }
+ }
+
+ statements.Add(ReturnStatement(IdentifierName(BuilderIdentifier)));
+
var declaration = CompilationUnit()
.WithUsings(
List(
new List { UsingDirective(IdentifierName("KubeOps.Abstractions.Builder")), }))
- .WithLeadingTrivia(AutoGeneratedSyntaxTrivia.Instance)
- .WithMembers(SingletonList(ClassDeclaration("OperatorBuilderExtensions")
+ .WithLeadingTrivia(AutoGeneratedSyntaxTrivia.Instance);
+
+ if (hasOwnControllers || hasOwnFinalizers)
+ {
+ declaration = declaration.AddAttributeLists(CreateRegistrationsMarker(
+ hasOwnControllers ? ControllerRegistrationsClassName.QualifyWith(generatorNamespace) : null,
+ hasOwnFinalizers ? FinalizerRegistrationsClassName.QualifyWith(generatorNamespace) : null));
+ }
+
+ declaration = declaration
+ .AddNamespaceScope(generatorNamespace)
+ .AddMembers(ClassDeclaration("OperatorBuilderExtensions")
.WithModifiers(TokenList(
- Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
+ Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.StaticKeyword)))
.AddMembers(MethodDeclaration(IdentifierName("IOperatorBuilder"), "RegisterComponents")
.WithModifiers(
TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)))
@@ -45,24 +207,29 @@ private static void Execute(IncrementalGeneratorPostInitializationContext contex
Token(SyntaxKind.ThisKeyword)))
.WithType(
IdentifierName("IOperatorBuilder")))))
- .WithBody(Block(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName(BuilderIdentifier),
- IdentifierName("RegisterControllers")))),
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName(BuilderIdentifier),
- IdentifierName("RegisterFinalizers")))),
- ReturnStatement(IdentifierName(BuilderIdentifier)))))))
+ .WithBody(Block(statements))))
.NormalizeWhitespace();
context.AddSource(
"OperatorBuilder.g.cs",
SourceText.From(declaration.ToFullString(), Encoding.UTF8, SourceHashAlgorithm.Sha256));
}
+
+ private static AttributeListSyntax CreateRegistrationsMarker(
+ string? controllerRegistrations,
+ string? finalizerRegistrations)
+ => AttributeList(
+ AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)),
+ SingletonSeparatedList(
+ Attribute(ParseName($"global::{RegistrationsAttributeFullName}"))
+ .WithArgumentList(AttributeArgumentList(SeparatedList(new[]
+ {
+ AttributeArgument(ToLiteral(controllerRegistrations)),
+ AttributeArgument(ToLiteral(finalizerRegistrations)),
+ })))));
+
+ private static ExpressionSyntax ToLiteral(string? value)
+ => value is null
+ ? LiteralExpression(SyntaxKind.NullLiteralExpression)
+ : LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value));
}
diff --git a/src/KubeOps.Generator/KubeOps.Generator.csproj b/src/KubeOps.Generator/KubeOps.Generator.csproj
index 416a5133f..dc2aede4b 100644
--- a/src/KubeOps.Generator/KubeOps.Generator.csproj
+++ b/src/KubeOps.Generator/KubeOps.Generator.csproj
@@ -3,6 +3,8 @@
netstandard2.0
true
+ false
+ true
true
false
true
@@ -34,6 +36,9 @@
Pack="true"
PackagePath="analyzers/dotnet/cs"
Visible="false" />
+
\ No newline at end of file
diff --git a/src/KubeOps.Generator/KubeOps.Generator.props b/src/KubeOps.Generator/KubeOps.Generator.props
new file mode 100644
index 000000000..766ed3873
--- /dev/null
+++ b/src/KubeOps.Generator/KubeOps.Generator.props
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
diff --git a/src/KubeOps.Generator/README.md b/src/KubeOps.Generator/README.md
index 9e4da05b4..7125a35ff 100644
--- a/src/KubeOps.Generator/README.md
+++ b/src/KubeOps.Generator/README.md
@@ -9,7 +9,7 @@ resources within an operator.
## Motivation
-The primary goal of this generator is to reduce boilerplate code required in your operator's `Program.cs` (or startup logic). Instead of manually calling `builder.AddController<...>()`, `builder.AddFinalizer<...>()`, `builder.AddWebhook<...>()`, etc., for every component, the generator scans your project and creates extension methods that register all discovered components with a single call.
+The primary goal of this generator is to reduce boilerplate code required in your operator's `Program.cs` (or startup logic). Instead of manually calling `builder.AddController<...>()` and `builder.AddFinalizer<...>()` for every component, the generator scans your project and creates extension methods that register all discovered components with a single call.
## Usage
@@ -53,12 +53,77 @@ app.RunOperatorAsync();
The generator will automatically generate functions for the `IOperatorBuilder`.
+By default, all shared classes (`EntityDefinitions`, `EntityInitializer`,
+`ControllerRegistrations`, `FinalizerRegistrations`, `OperatorBuilderExtensions`) are generated
+into the **global namespace**. Two general rules apply:
+
+- `ControllerRegistrations` / `FinalizerRegistrations` / `EntityDefinitions` /
+ `EntityInitializer` are only generated when the compilation actually contains matching
+ components.
+- `OperatorBuilderExtensions` (the `RegisterComponents` aggregate) and `EntityInitializer` are
+ `internal`: they are only meaningful for the compilation they are generated into.
+
+### Configuring the Target Namespace
+
+When multiple projects of one solution reference the generator (e.g. a class library with
+controllers and the operator itself), the generated class names must not conflict. Set the
+`KubeOpsGeneratorNamespace` MSBuild property in the participating projects to generate the shared
+classes into a distinct namespace instead of the global namespace:
+
+```xml
+
+ $(RootNamespace)
+
+```
+
+Any namespace works (`$(RootNamespace)`, `$(AssemblyName)` or a literal); invalid characters are
+sanitized. Note that top-level `Program.cs` files then need a using directive for the configured
+namespace so that `RegisterComponents()` resolves.
+
+### Multi-Assembly Composition
+
+Controllers and finalizers may live in referenced class libraries that also use the generator.
+Every assembly that contains such components is marked with an assembly-level
+`KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrationsAttribute` pointing to its (public)
+registration classes. These classes register **only the components of their own assembly** and
+never chain into further assemblies.
+
+The generated `RegisterComponents` method of the consuming compilation discovers these markers on
+all transitively referenced assemblies and invokes every registration class exactly once via a
+fully qualified call:
+
+```csharp
+using KubeOps.Abstractions.Builder;
+
+[assembly: global::KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("MyOperator.ControllerRegistrations", "MyOperator.FinalizerRegistrations")]
+namespace MyOperator;
+internal static class OperatorBuilderExtensions
+{
+ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
+ {
+ builder.RegisterControllers();
+ builder.RegisterFinalizers();
+ global::MyLibrary.ControllerRegistrations.RegisterControllers(builder);
+ return builder;
+ }
+}
+```
+
+This flat, deduplicated composition guarantees that no component is registered twice, regardless
+of how the assemblies reference each other (e.g. app → LibA → LibB with components in all three).
+
+If two assemblies in the chain generate registration classes with the same fully qualified name
+(e.g. both use the global namespace default), the generator reports the warning **KOG002**
+and skips the conflicting registration instead of emitting ambiguous code. Set
+`KubeOpsGeneratorNamespace` in the conflicting projects to resolve it.
+
### Entity Metadata / Entity Definitions
-The generator creates a file in the root namespace called `EntityDefinitions.g.cs`.
-This file contains all entities that are annotated with the `KubernetesEntityAttribute`.
-The static class contains the `EntityMetadata` for the entities as well
-as a function to register all entities within the `IOperatorBuilder`.
+The generator creates a file named `EntityDefinitions.g.cs` (only when the compilation declares
+entities). This file contains all entities that are annotated with the
+`KubernetesEntityAttribute` and declared in the compilation itself - entities from referenced
+assemblies are listed by their declaring assembly. The static class contains the
+`EntityMetadata` for the entities.
#### Example
@@ -147,8 +212,8 @@ public static class EntityInitializer
### Controller Registrations
-The generator creates a file in the root namespace called `ControllerRegistrations.g.cs`.
-This file contains a function to register all found controllers
+The generator creates a file named `ControllerRegistrations.g.cs` (only when the compilation
+contains controllers). This file contains a function to register all found controllers
(i.e., classes that implement the `IResourceController` interface).
#### Example
@@ -168,8 +233,8 @@ public static class ControllerRegistrations
### Finalizer Registrations
-The generator creates a file in the root namespace called `FinalizerRegistrations.g.cs`.
-This file contains all finalizers with generated finalizer identifiers.
+The generator creates a file named `FinalizerRegistrations.g.cs` (only when the compilation
+contains finalizers). This file contains all finalizers with generated finalizer identifiers.
Further, a function to register all finalizers (i.e., classes that implement `IResourceFinalizer`) is generated.
#### Example
@@ -190,45 +255,23 @@ public static class FinalizerRegistrations
}
```
-### Webhook Registrations
-
-The generator creates a file in the root namespace called `WebhookRegistrations.g.cs`.
-This file contains a function to register all found webhooks
-(i.e., classes decorated with `[ValidationWebhook]`, `[MutationWebhook]`, or `[ConversionWebhook]`).
-
-#### Example
-
-```csharp
-using KubeOps.Abstractions.Builder;
-
-public static class WebhookRegistrations
-{
- public static IOperatorBuilder RegisterWebhooks(this IOperatorBuilder builder)
- {
- // Example assuming MyValidationWebhook and MyMutationWebhook exist
- builder.AddValidationWebhook();
- builder.AddMutationWebhook();
- return builder;
- }
-}
-```
-
### General Operator Extensions
-The generator creates a file in the root namespace called `OperatorExtensions.g.cs`.
-It contains convenience functions to register all generated sources.
+The generator creates a file named `OperatorBuilder.g.cs`. It contains the internal
+`RegisterComponents` convenience method that registers all generated sources: the components of
+the own compilation (only the parts that exist) and the components of all marked referenced
+assemblies (see [Multi-Assembly Composition](#multi-assembly-composition)).
#### Example
```csharp
using KubeOps.Abstractions.Builder;
-public static class OperatorBuilderExtensions
+[assembly: global::KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("ControllerRegistrations", "FinalizerRegistrations")]
+internal static class OperatorBuilderExtensions
{
public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
{
- builder.RegisterEntities();
- builder.RegisterWebhooks();
builder.RegisterControllers();
builder.RegisterFinalizers();
return builder;
diff --git a/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.SelectorConflict.Test.cs b/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.SelectorConflict.Test.cs
index a69cb6747..226504f89 100644
--- a/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.SelectorConflict.Test.cs
+++ b/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.SelectorConflict.Test.cs
@@ -16,7 +16,6 @@ namespace KubeOps.Generator.Test;
public sealed partial class ControllerRegistrationGeneratorTest
{
[Fact]
- [Trait("Area", "SelectorConflict")]
public void Should_Report_Error_And_Skip_Registration_When_Controller_Declares_Both_Selectors()
{
const string input =
@@ -63,12 +62,9 @@ public sealed class V1TestEntityController : IEntityController
.Should().ContainSingle(d => d.Id == "KOG001")
.Which.Severity.Should().Be(DiagnosticSeverity.Error);
- var result = output.SyntaxTrees
- .First(s => s.FilePath.Contains("ControllerRegistrations.g.cs"))
- .ToString();
-
- // The conflicting controller must not be registered (neither label- nor field-selector variant).
- result.Should().NotContain("V1TestEntityController");
+ // The conflicting controller must not be registered (neither label- nor field-selector
+ // variant); as it is the only controller, no registration class is generated at all.
+ output.SyntaxTrees.Any(s => s.FilePath.Contains("ControllerRegistrations.g.cs")).Should().BeFalse();
}
[Fact]
@@ -123,10 +119,6 @@ public partial class V1TestEntityController : IEntityController
.Should().ContainSingle(d => d.Id == "KOG001")
.Which.Severity.Should().Be(DiagnosticSeverity.Error);
- var result = output.SyntaxTrees
- .First(s => s.FilePath.Contains("ControllerRegistrations.g.cs"))
- .ToString();
-
- result.Should().NotContain("V1TestEntityController");
+ output.SyntaxTrees.Any(s => s.FilePath.Contains("ControllerRegistrations.g.cs")).Should().BeFalse();
}
}
diff --git a/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.Test.cs b/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.Test.cs
index 6536cfe5e..489155ef7 100644
--- a/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.Test.cs
+++ b/test/KubeOps.Generator.Test/ControllerRegistrationGenerator.Test.cs
@@ -15,26 +15,112 @@ namespace KubeOps.Generator.Test;
public sealed partial class ControllerRegistrationGeneratorTest
{
- [Theory]
- [InlineData(
- "",
- """
- //
- // This code was generated by a tool.
- // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
- //
- #pragma warning disable CS1591
- using KubeOps.Abstractions.Builder;
-
- public static class ControllerRegistrations
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Not_Generate_Registrations_Without_Controllers()
+ {
+ var inputCompilation = string.Empty.CreateCompilation();
+
+ var driver = CSharpGeneratorDriver.Create(new ControllerRegistrationGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ output.SyntaxTrees.Any(s => s.FilePath.Contains("ControllerRegistrations.g.cs")).Should().BeFalse();
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Generate_Into_Configured_Namespace()
+ {
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+ """.CreateCompilation();
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ namespace My.Operator_Lib;
+ public static class ControllerRegistrations
+ {
+ public static IOperatorBuilder RegisterControllers(this IOperatorBuilder builder)
{
- public static IOperatorBuilder RegisterControllers(this IOperatorBuilder builder)
- {
- return builder;
- }
+ builder.AddController();
+ return builder;
}
- """,
- TestDisplayName = "No controllers defined")]
+ }
+ """.ReplaceLineEndings();
+
+ var driver = CSharpGeneratorDriver.Create(
+ generators: [new ControllerRegistrationGenerator().AsSourceGenerator()],
+ optionsProvider: TestHelperExtensions.CreateGeneratorNamespaceOptions("My.Operator-Lib"));
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ var result = output.SyntaxTrees
+ .First(s => s.FilePath.Contains("ControllerRegistrations.g.cs"))
+ .ToString().ReplaceLineEndings();
+ result.Should().Be(expectedResult);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Sanitize_Configured_Namespace()
+ {
+ // Segments starting with a digit or matching a reserved keyword are prefixed with an
+ // underscore; invalid characters are replaced with underscores.
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+ """.CreateCompilation();
+
+ var driver = CSharpGeneratorDriver.Create(
+ generators: [new ControllerRegistrationGenerator().AsSourceGenerator()],
+ optionsProvider: TestHelperExtensions.CreateGeneratorNamespaceOptions("9my.class.lib-x"));
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ var result = output.SyntaxTrees
+ .First(s => s.FilePath.Contains("ControllerRegistrations.g.cs"))
+ .ToString().ReplaceLineEndings();
+ result.Should().Contain("namespace _9my._class.lib_x;");
+ }
+
+ [Theory]
[InlineData(
"""
using k8s;
diff --git a/test/KubeOps.Generator.Test/EntityDefinitionGenerator.ReferencedAssembly.Test.cs b/test/KubeOps.Generator.Test/EntityDefinitionGenerator.ReferencedAssembly.Test.cs
index e8b8f6fe0..9d7b6c636 100644
--- a/test/KubeOps.Generator.Test/EntityDefinitionGenerator.ReferencedAssembly.Test.cs
+++ b/test/KubeOps.Generator.Test/EntityDefinitionGenerator.ReferencedAssembly.Test.cs
@@ -17,103 +17,75 @@ namespace KubeOps.Generator.Test;
public sealed partial class EntityDefinitionGeneratorTest
{
- [Theory]
- [InlineData(
- """
- using k8s;
- using k8s.Models;
- using KubeOps.Generator.Test.Entities;
- using KubeOps.Abstractions.Reconciliation.Controller;
-
- public sealed class V1TestEntityController : IEntityController
- {
- }
- """,
- """
- //
- // This code was generated by a tool.
- // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
- //
- #pragma warning disable CS1591
- using KubeOps.Abstractions.Builder;
- using KubeOps.Abstractions.Entities;
-
- public static class EntityDefinitions
- {
- public static readonly EntityMetadata V1TestEntityFromReferencedAssemblyWithConstantValues = new("TestEntity", "v1", "testing.dev", "testentities");
- }
- """,
- TestDisplayName = "Test single entity (with controller as entity resolver reference)")]
- [InlineData(
- """
- using k8s;
- using k8s.Models;
- using KubeOps.Generator.Test.Entities;
- using KubeOps.Abstractions.Reconciliation.Controller;
- using KubeOps.Abstractions.Reconciliation.Finalizer;
-
- public sealed class V1TestEntityController : IEntityController
- {
- }
-
- public sealed class V1TestEntityFinalizer : IEntityFinalizer
- {
- }
- """,
- """
- //
- // This code was generated by a tool.
- // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
- //
- #pragma warning disable CS1591
- using KubeOps.Abstractions.Builder;
- using KubeOps.Abstractions.Entities;
-
- public static class EntityDefinitions
- {
- public static readonly EntityMetadata V1TestEntityFromReferencedAssemblyWithConstantValues = new("TestEntity", "v1", "testing.dev", "testentities");
- }
- """,
- TestDisplayName = "Test single entity (with controller and finalizer as entity resolver reference)")]
- [InlineData(
- """
- using k8s;
- using k8s.Models;
- using KubeOps.Generator.Test.Entities;
- using KubeOps.Abstractions.Reconciliation.Controller;
- using KubeOps.Abstractions.Reconciliation.Finalizer;
-
- public sealed class V1TestEntityController : IEntityController
- {
- }
-
- public sealed class V1TestEntityFinalizer : IEntityFinalizer
- {
- }
- """,
- """
- //
- // This code was generated by a tool.
- // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
- //
- #pragma warning disable CS1591
- using KubeOps.Abstractions.Builder;
- using KubeOps.Abstractions.Entities;
-
- public static class EntityDefinitions
- {
- public static readonly EntityMetadata V1TestEntityFromReferencedAssemblyWithConstantValues = new("TestEntity", "v1", "testing.dev", "testentities");
- public static readonly EntityMetadata V1TestEntityFromReferencedAssemblyInGlobalNamespace = new("TestEntity", "v1", "testing.dev", null);
- }
- """,
- TestDisplayName = "Test multiple entities (with controller and finalizer as entity resolver reference)")]
- public void Should_Generate_Correct_Code_WithEntityFromReferencedAssembly(string input, string expectedResult)
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Not_Generate_Definitions_For_Entities_From_Referenced_Assemblies()
{
- var inputCompilation = input.CreateCompilation(
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Generator.Test.Entities;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+ using KubeOps.Abstractions.Reconciliation.Finalizer;
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+
+ public sealed class V1TestEntityFinalizer : IEntityFinalizer
+ {
+ }
+ """.CreateCompilation(
additionalReferences: MetadataReference
.CreateFromFile(typeof(V1TestEntityFromReferencedAssembly)
.GetTypeInfo().Assembly.Location));
- expectedResult = expectedResult.ReplaceLineEndings();
+
+ var driver = CSharpGeneratorDriver.Create(new EntityDefinitionGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ output.SyntaxTrees.Any(s => s.FilePath.Contains("EntityDefinitions.g.cs")).Should().BeFalse();
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Only_Generate_Definitions_For_Locally_Declared_Entities()
+ {
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Generator.Test.Entities;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "LocalEntity")]
+ public sealed class V1LocalEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+ """.CreateCompilation(
+ additionalReferences: MetadataReference
+ .CreateFromFile(typeof(V1TestEntityFromReferencedAssembly)
+ .GetTypeInfo().Assembly.Location));
+ var expectedResult = """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+ using KubeOps.Abstractions.Entities;
+
+ public static class EntityDefinitions
+ {
+ public static readonly EntityMetadata V1LocalEntity = new("LocalEntity", "v1", "testing.dev", null);
+ }
+ """.ReplaceLineEndings();
var driver = CSharpGeneratorDriver.Create(new EntityDefinitionGenerator());
driver.RunGeneratorsAndUpdateCompilation(
diff --git a/test/KubeOps.Generator.Test/EntityDefinitionGenerator.Test.cs b/test/KubeOps.Generator.Test/EntityDefinitionGenerator.Test.cs
index f6e413ead..cdcd7d29d 100644
--- a/test/KubeOps.Generator.Test/EntityDefinitionGenerator.Test.cs
+++ b/test/KubeOps.Generator.Test/EntityDefinitionGenerator.Test.cs
@@ -15,23 +15,65 @@ namespace KubeOps.Generator.Test;
public sealed partial class EntityDefinitionGeneratorTest
{
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Not_Generate_Definitions_Without_Entities()
+ {
+ var inputCompilation = string.Empty.CreateCompilation();
+
+ var driver = CSharpGeneratorDriver.Create(new EntityDefinitionGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ output.SyntaxTrees.Any(s => s.FilePath.Contains("EntityDefinitions.g.cs")).Should().BeFalse();
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Generate_Into_Configured_Namespace()
+ {
+ var inputCompilation = """
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+ """.CreateCompilation();
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+ using KubeOps.Abstractions.Entities;
+
+ namespace MyOperator;
+ public static class EntityDefinitions
+ {
+ public static readonly EntityMetadata V1TestEntity = new("TestEntity", "v1", "testing.dev", null);
+ }
+ """.ReplaceLineEndings();
+
+ var driver = CSharpGeneratorDriver.Create(
+ generators: [new EntityDefinitionGenerator().AsSourceGenerator()],
+ optionsProvider: TestHelperExtensions.CreateGeneratorNamespaceOptions("MyOperator"));
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ var result = output.SyntaxTrees
+ .First(s => s.FilePath.Contains("EntityDefinitions.g.cs"))
+ .ToString().ReplaceLineEndings();
+ result.Should().Be(expectedResult);
+ }
+
[Theory]
- [InlineData(
- "",
- """
- //
- // This code was generated by a tool.
- // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
- //
- #pragma warning disable CS1591
- using KubeOps.Abstractions.Builder;
- using KubeOps.Abstractions.Entities;
-
- public static class EntityDefinitions
- {
- }
- """,
- TestDisplayName = "Test empty input")]
[InlineData(
"""
[KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
diff --git a/test/KubeOps.Generator.Test/EntityInitializerGenerator.Test.cs b/test/KubeOps.Generator.Test/EntityInitializerGenerator.Test.cs
index 9649e1d19..a3b8001dc 100644
--- a/test/KubeOps.Generator.Test/EntityInitializerGenerator.Test.cs
+++ b/test/KubeOps.Generator.Test/EntityInitializerGenerator.Test.cs
@@ -21,21 +21,52 @@ public sealed class EntityInitializerGeneratorTest
private const string EntityInitGeneratorFileName = "V1TestEntity.init.g.cs";
[Fact]
- public void Should_Generate_Empty_Initializer_Without_Input()
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Not_Generate_Initializer_Without_Input()
{
var inputCompilation = string.Empty.CreateCompilation();
+
+ var driver = CSharpGeneratorDriver.Create(new EntityInitializerGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ output.SyntaxTrees.Any(s => s.FilePath.Contains(EntityInitializerGeneratorFileName)).Should().BeFalse();
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Generate_Static_Initializer_Into_Configured_Namespace()
+ {
+ var inputCompilation = """
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+ """.CreateCompilation();
var expectedResult = """
//
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
//
#pragma warning disable CS1591
- public static class EntityInitializer
+ namespace MyOperator;
+ internal static class EntityInitializer
{
+ public static global::V1TestEntity Initialize(this global::V1TestEntity entity)
+ {
+ entity.ApiVersion = "testing.dev/v1";
+ entity.Kind = "TestEntity";
+ return entity;
+ }
}
""".ReplaceLineEndings();
- var driver = CSharpGeneratorDriver.Create(new EntityInitializerGenerator());
+ var driver = CSharpGeneratorDriver.Create(
+ generators: [new EntityInitializerGenerator().AsSourceGenerator()],
+ optionsProvider: TestHelperExtensions.CreateGeneratorNamespaceOptions("MyOperator"));
driver.RunGeneratorsAndUpdateCompilation(
inputCompilation,
out var output,
@@ -68,7 +99,7 @@ public class V2TestEntity : IKubernetesObject
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
//
#pragma warning disable CS1591
- public static class EntityInitializer
+ internal static class EntityInitializer
{
public static global::V1TestEntity Initialize(this global::V1TestEntity entity)
{
@@ -116,7 +147,7 @@ public class V1ConfigMap : IKubernetesObject
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
//
#pragma warning disable CS1591
- public static class EntityInitializer
+ internal static class EntityInitializer
{
public static global::V1ConfigMap Initialize(this global::V1ConfigMap entity)
{
@@ -158,7 +189,7 @@ public V1TestEntity(){}
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
//
#pragma warning disable CS1591
- public static class EntityInitializer
+ internal static class EntityInitializer
{
public static global::V1TestEntity Initialize(this global::V1TestEntity entity)
{
@@ -193,16 +224,6 @@ public partial class V1TestEntity : IKubernetesObject
{
}
""".CreateCompilation();
- var expectedResult = """
- //
- // This code was generated by a tool.
- // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
- //
- #pragma warning disable CS1591
- public static class EntityInitializer
- {
- }
- """.ReplaceLineEndings();
var driver = CSharpGeneratorDriver.Create(new EntityInitializerGenerator());
driver.RunGeneratorsAndUpdateCompilation(
@@ -212,10 +233,7 @@ public static class EntityInitializer
TestContext.Current.CancellationToken);
output.SyntaxTrees.Any(s => s.FilePath.Contains("V1TestEntity")).Should().BeTrue();
- var result = output.SyntaxTrees
- .First(s => s.FilePath.Contains(EntityInitializerGeneratorFileName))
- .ToString().ReplaceLineEndings();
- result.Should().Be(expectedResult);
+ output.SyntaxTrees.Any(s => s.FilePath.Contains(EntityInitializerGeneratorFileName)).Should().BeFalse();
}
[Fact]
@@ -456,7 +474,7 @@ public sealed class V1TestEntityController : IEntityController
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
//
#pragma warning disable CS1591
- public static class EntityInitializer
+ internal static class EntityInitializer
{
public static global::KubeOps.Generator.Test.Entities.V1TestEntity Initialize(this global::KubeOps.Generator.Test.Entities.V1TestEntity entity)
{
diff --git a/test/KubeOps.Generator.Test/FinalizerRegistrationGenerator.Test.cs b/test/KubeOps.Generator.Test/FinalizerRegistrationGenerator.Test.cs
index 31b200259..8a4b8e2eb 100644
--- a/test/KubeOps.Generator.Test/FinalizerRegistrationGenerator.Test.cs
+++ b/test/KubeOps.Generator.Test/FinalizerRegistrationGenerator.Test.cs
@@ -15,26 +15,77 @@ namespace KubeOps.Generator.Test;
public sealed partial class FinalizerRegistrationGeneratorTest
{
- [Theory]
- [InlineData(
- "",
- """
- //
- // This code was generated by a tool.
- // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
- //
- #pragma warning disable CS1591
- using KubeOps.Abstractions.Builder;
-
- public static class FinalizerRegistrations
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Not_Generate_Registrations_Without_Finalizers()
+ {
+ var inputCompilation = string.Empty.CreateCompilation();
+
+ var driver = CSharpGeneratorDriver.Create(new FinalizerRegistrationGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ output.SyntaxTrees.Any(s => s.FilePath.Contains("FinalizerRegistrations.g.cs")).Should().BeFalse();
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Generate_Into_Configured_Namespace()
+ {
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Finalizer;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public sealed class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityFinalizer : IEntityFinalizer
+ {
+ }
+ """.CreateCompilation();
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ namespace MyOperator;
+ public static class FinalizerRegistrations
+ {
+ public const string V1TestEntityFinalizerIdentifier = "testing.dev/v1testentityfinalizer";
+ public static IOperatorBuilder RegisterFinalizers(this IOperatorBuilder builder)
{
- public static IOperatorBuilder RegisterFinalizers(this IOperatorBuilder builder)
- {
- return builder;
- }
+ builder.AddFinalizer(V1TestEntityFinalizerIdentifier);
+ return builder;
}
- """,
- TestDisplayName = "No finalizers defined")]
+ }
+ """.ReplaceLineEndings();
+
+ var driver = CSharpGeneratorDriver.Create(
+ generators: [new FinalizerRegistrationGenerator().AsSourceGenerator()],
+ optionsProvider: TestHelperExtensions.CreateGeneratorNamespaceOptions("MyOperator"));
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ var result = output.SyntaxTrees
+ .First(s => s.FilePath.Contains("FinalizerRegistrations.g.cs"))
+ .ToString().ReplaceLineEndings();
+ result.Should().Be(expectedResult);
+ }
+
+ [Theory]
[InlineData(
"""
using k8s;
diff --git a/test/KubeOps.Generator.Test/OperatorBuilderGenerator.Test.cs b/test/KubeOps.Generator.Test/OperatorBuilderGenerator.Test.cs
index 0f9bc7122..009a1f3cb 100644
--- a/test/KubeOps.Generator.Test/OperatorBuilderGenerator.Test.cs
+++ b/test/KubeOps.Generator.Test/OperatorBuilderGenerator.Test.cs
@@ -15,10 +15,30 @@ namespace KubeOps.Generator.Test;
public sealed class OperatorBuilderGeneratorTest
{
+ private const string OperatorBuilderFileName = "OperatorBuilder.g.cs";
+
[Fact]
- public void Should_Generate_Correct_Code()
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Not_Generate_RegisterComponents_Without_Components_Or_Operator_Reference()
{
var inputCompilation = string.Empty.CreateCompilation();
+
+ var driver = CSharpGeneratorDriver.Create(new OperatorBuilderGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ output.SyntaxTrees.Any(s => s.FilePath.Contains(OperatorBuilderFileName)).Should().BeFalse();
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Generate_Empty_RegisterComponents_When_Operator_Is_Referenced()
+ {
+ var operatorReference = string.Empty.CreateCompilation("KubeOps.Operator").EmitToImageReference();
+ var inputCompilation = string.Empty.CreateCompilation(operatorReference);
var expectedResult =
"""
//
@@ -28,7 +48,52 @@ public void Should_Generate_Correct_Code()
#pragma warning disable CS1591
using KubeOps.Abstractions.Builder;
- public static class OperatorBuilderExtensions
+ internal static class OperatorBuilderExtensions
+ {
+ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
+ {
+ return builder;
+ }
+ }
+ """.ReplaceLineEndings();
+
+ RunGenerator(inputCompilation).Should().Be(expectedResult);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Generate_Own_Registrations_With_Assembly_Marker()
+ {
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+ using KubeOps.Abstractions.Reconciliation.Finalizer;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+
+ public sealed class V1TestEntityFinalizer : IEntityFinalizer
+ {
+ }
+ """.CreateCompilation();
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ [assembly: global::KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("ControllerRegistrations", "FinalizerRegistrations")]
+ internal static class OperatorBuilderExtensions
{
public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
{
@@ -39,6 +104,269 @@ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
}
""".ReplaceLineEndings();
+ RunGenerator(inputCompilation).Should().Be(expectedResult);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Only_Register_Existing_Component_Kinds()
+ {
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+ """.CreateCompilation();
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ [assembly: global::KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("ControllerRegistrations", null)]
+ internal static class OperatorBuilderExtensions
+ {
+ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
+ {
+ builder.RegisterControllers();
+ return builder;
+ }
+ }
+ """.ReplaceLineEndings();
+
+ RunGenerator(inputCompilation).Should().Be(expectedResult);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Register_Referenced_Assembly_Registrations()
+ {
+ var libCompilation = """
+ [assembly: KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("LibA.ControllerRegistrations", "LibA.FinalizerRegistrations")]
+ """.CreateCompilation("liba");
+ var inputCompilation = string.Empty.CreateCompilation(libCompilation.EmitToImageReference());
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ internal static class OperatorBuilderExtensions
+ {
+ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
+ {
+ global::LibA.ControllerRegistrations.RegisterControllers(builder);
+ global::LibA.FinalizerRegistrations.RegisterFinalizers(builder);
+ return builder;
+ }
+ }
+ """.ReplaceLineEndings();
+
+ RunGenerator(inputCompilation).Should().Be(expectedResult);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Register_Own_And_Referenced_Assembly_Registrations()
+ {
+ var libCompilation = """
+ [assembly: KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("LibA.ControllerRegistrations", null)]
+ """.CreateCompilation("liba");
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+ """.CreateCompilation(libCompilation.EmitToImageReference());
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ [assembly: global::KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("ControllerRegistrations", null)]
+ internal static class OperatorBuilderExtensions
+ {
+ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
+ {
+ builder.RegisterControllers();
+ global::LibA.ControllerRegistrations.RegisterControllers(builder);
+ return builder;
+ }
+ }
+ """.ReplaceLineEndings();
+
+ RunGenerator(inputCompilation).Should().Be(expectedResult);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Generate_Into_Configured_Namespace()
+ {
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+ """.CreateCompilation();
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ [assembly: global::KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("MyOperator.ControllerRegistrations", null)]
+ namespace MyOperator;
+ internal static class OperatorBuilderExtensions
+ {
+ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
+ {
+ builder.RegisterControllers();
+ return builder;
+ }
+ }
+ """.ReplaceLineEndings();
+
+ RunGenerator(inputCompilation, out _, "MyOperator").Should().Be(expectedResult);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Report_Diagnostic_And_Skip_Conflicting_Referenced_Registrations()
+ {
+ var libCompilation = """
+ [assembly: KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("ControllerRegistrations", null)]
+ """.CreateCompilation("liba");
+ var inputCompilation = """
+ using k8s;
+ using k8s.Models;
+ using KubeOps.Abstractions.Reconciliation.Controller;
+
+ [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
+ public class V1TestEntity : IKubernetesObject
+ {
+ }
+
+ public sealed class V1TestEntityController : IEntityController
+ {
+ }
+ """.CreateCompilation(libCompilation.EmitToImageReference());
+ var expectedResult =
+ """
+ //
+ // This code was generated by a tool.
+ // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
+ //
+ #pragma warning disable CS1591
+ using KubeOps.Abstractions.Builder;
+
+ [assembly: global::KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("ControllerRegistrations", null)]
+ internal static class OperatorBuilderExtensions
+ {
+ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
+ {
+ builder.RegisterControllers();
+ return builder;
+ }
+ }
+ """.ReplaceLineEndings();
+
+ RunGenerator(inputCompilation, out var diagnostics).Should().Be(expectedResult);
+ var diagnostic = diagnostics.Should().ContainSingle(d => d.Id == "KOG002").Subject;
+ diagnostic.GetMessage().Should().Contain("liba");
+
+ // The diagnostic is anchored at the declaration of the own component whose generated
+ // registration class name is part of the conflict.
+ diagnostic.Location.Should().NotBe(Location.None);
+ diagnostic.Location.GetLineSpan().StartLinePosition.Line.Should().Be(9);
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Skip_Platform_Signed_Referenced_Assemblies()
+ {
+ // Discovery prunes assemblies carrying a .NET platform public key token without decoding
+ // their attributes. A marked assembly that is public-signed with the runtime's key (token
+ // of System.Private.CoreLib) must therefore be ignored, even though it carries the marker.
+ var platformPublicKey = typeof(object).Assembly.GetName().GetPublicKey();
+ var libCompilation = """
+ [assembly: KubeOps.Abstractions.Builder.KubeOpsGeneratedRegistrations("LibA.ControllerRegistrations", null)]
+ """.CreateCompilation("liba");
+ libCompilation = libCompilation.WithOptions(
+ ((CSharpCompilationOptions)libCompilation.Options)
+ .WithCryptoPublicKey([.. platformPublicKey!])
+ .WithPublicSign(true));
+ var inputCompilation = string.Empty.CreateCompilation(libCompilation.EmitToImageReference());
+
+ var driver = CSharpGeneratorDriver.Create(new OperatorBuilderGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out ImmutableArray _,
+ TestContext.Current.CancellationToken);
+
+ output.SyntaxTrees.Any(s => s.FilePath.Contains(OperatorBuilderFileName)).Should().BeFalse();
+ }
+
+ [Fact]
+ [Trait("Area", "ReferencedRegistration")]
+ public void Should_Ignore_Foreign_Attribute_Without_Abstractions_Reference()
+ {
+ // Discovery only decodes attributes of assemblies that reference KubeOps.Abstractions.
+ // An assembly applying its own, same-named attribute from a different namespace (and thus
+ // not referencing KubeOps.Abstractions at all) must not be picked up.
+ var libCompilation = """
+ [assembly: Fake.KubeOpsGeneratedRegistrations("Fake.ControllerRegistrations", null)]
+
+ namespace Fake
+ {
+ [System.AttributeUsage(System.AttributeTargets.Assembly)]
+ public sealed class KubeOpsGeneratedRegistrationsAttribute : System.Attribute
+ {
+ public KubeOpsGeneratedRegistrationsAttribute(string? controllerRegistrations, string? finalizerRegistrations)
+ {
+ }
+ }
+ }
+ """.CreateCompilation("libfake");
+ var inputCompilation = string.Empty.CreateCompilation(libCompilation.EmitToImageReference());
+
var driver = CSharpGeneratorDriver.Create(new OperatorBuilderGenerator());
driver.RunGeneratorsAndUpdateCompilation(
inputCompilation,
@@ -46,9 +374,30 @@ public static IOperatorBuilder RegisterComponents(this IOperatorBuilder builder)
out ImmutableArray _,
TestContext.Current.CancellationToken);
- var result = output.SyntaxTrees
- .First(s => s.FilePath.Contains("OperatorBuilder.g.cs"))
+ output.SyntaxTrees.Any(s => s.FilePath.Contains(OperatorBuilderFileName)).Should().BeFalse();
+ }
+
+ private static string RunGenerator(Compilation inputCompilation)
+ => RunGenerator(inputCompilation, out _);
+
+ private static string RunGenerator(
+ Compilation inputCompilation,
+ out ImmutableArray diagnostics,
+ string? generatorNamespace = null)
+ {
+ var driver = CSharpGeneratorDriver.Create(
+ generators: [new OperatorBuilderGenerator().AsSourceGenerator()],
+ optionsProvider: generatorNamespace is null
+ ? null
+ : TestHelperExtensions.CreateGeneratorNamespaceOptions(generatorNamespace));
+ driver.RunGeneratorsAndUpdateCompilation(
+ inputCompilation,
+ out var output,
+ out diagnostics,
+ TestContext.Current.CancellationToken);
+
+ return output.SyntaxTrees
+ .First(s => s.FilePath.Contains(OperatorBuilderFileName))
.ToString().ReplaceLineEndings();
- result.Should().Be(expectedResult);
}
}
diff --git a/test/KubeOps.Generator.Test/TestHelperExtensions.cs b/test/KubeOps.Generator.Test/TestHelperExtensions.cs
index e7604ad91..21832cd9c 100644
--- a/test/KubeOps.Generator.Test/TestHelperExtensions.cs
+++ b/test/KubeOps.Generator.Test/TestHelperExtensions.cs
@@ -2,26 +2,71 @@
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.Diagnostics;
namespace KubeOps.Generator.Test;
internal static class TestHelperExtensions
{
public static Compilation CreateCompilation(this string source, params MetadataReference[] additionalReferences)
+ => source.CreateCompilation("compilation", additionalReferences);
+
+ public static Compilation CreateCompilation(
+ this string source,
+ string assemblyName,
+ params MetadataReference[] additionalReferences)
=> CSharpCompilation.Create(
- "compilation",
+ assemblyName,
[
CSharpSyntaxTree.ParseText(source),
],
[
MetadataReference.CreateFromFile(typeof(Binder).GetTypeInfo().Assembly.Location),
+ MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location),
MetadataReference.CreateFromFile(typeof(Abstractions.Reconciliation.Controller.IEntityController<>).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(k8s.IKubernetesObject<>).GetTypeInfo().Assembly.Location),
..additionalReferences,
],
new(OutputKind.DynamicallyLinkedLibrary));
+
+ public static MetadataReference EmitToImageReference(this Compilation compilation)
+ {
+ using var stream = new MemoryStream();
+ var result = compilation.Emit(stream);
+ if (!result.Success)
+ {
+ throw new InvalidOperationException(
+ $"Emit of test compilation failed: {string.Join(Environment.NewLine, result.Diagnostics)}");
+ }
+
+ return MetadataReference.CreateFromImage(stream.ToArray());
+ }
+
+ public static AnalyzerConfigOptionsProvider CreateGeneratorNamespaceOptions(string generatorNamespace)
+ => new TestAnalyzerConfigOptionsProvider(
+ new KeyValuePair("build_property.KubeOpsGeneratorNamespace", generatorNamespace));
+
+ private sealed class TestAnalyzerConfigOptionsProvider(params KeyValuePair[] options)
+ : AnalyzerConfigOptionsProvider
+ {
+ public override AnalyzerConfigOptions GlobalOptions { get; } = new TestAnalyzerConfigOptions(options);
+
+ public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => new TestAnalyzerConfigOptions([]);
+
+ public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) => new TestAnalyzerConfigOptions([]);
+ }
+
+ private sealed class TestAnalyzerConfigOptions(KeyValuePair[] options)
+ : AnalyzerConfigOptions
+ {
+ private readonly Dictionary _options = options.ToDictionary(o => o.Key, o => o.Value);
+
+ public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
+ => _options.TryGetValue(key, out value);
+ }
}