Skip to content

Commit

Permalink
fix(source-generator): error reporting
Browse files Browse the repository at this point in the history
  • Loading branch information
jwfx authored and matkoch committed Aug 14, 2023
1 parent 797a073 commit 33ea8ec
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions source/Nuke.SourceGenerators/StronglyTypedSolutionGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,29 @@ public void Initialize(GeneratorInitializationContext context)

public void Execute(GeneratorExecutionContext context)
{
var compilation = context.Compilation;
try
{
if (GenerateSolutionSource(context.Compilation) is { Length: > 0 } generatedSource)
{
context.AddSource(nameof(StronglyTypedSolutionGenerator), generatedSource);
}
}
catch (Exception exception)
{
var diagnostic = Diagnostic.Create(
"NUKE001",
nameof(StronglyTypedSolutionGenerator),
exception.Message,
DiagnosticSeverity.Error,
DiagnosticSeverity.Error,
isEnabledByDefault: true,
warningLevel: 0);
context.ReportDiagnostic(diagnostic);
}
}

private string GenerateSolutionSource(Compilation compilation)
{
var allTypes = compilation.Assembly.GlobalNamespace.GetAllTypes();
var members = allTypes.SelectMany(x => x.GetMembers())
.Where(x => x is IPropertySymbol or IFieldSymbol)
Expand All @@ -37,7 +59,7 @@ public void Execute(GeneratorExecutionContext context)
.ToList();

if (members.Count == 0)
return;
return null;

var rootDirectory = GetRootDirectoryFrom(compilation);
var compilationUnit = CompilationUnit()
Expand All @@ -59,11 +81,10 @@ public void Execute(GeneratorExecutionContext context)
: classDeclaration);
}

var source = compilationUnit
return compilationUnit
.WithLeadingTrivia(ParseLeadingTrivia($"/// <auto-generated/>{Environment.NewLine}"))
.NormalizeWhitespace()
.ToFullString();
context.AddSource(nameof(StronglyTypedSolutionGenerator), source);
}

[CanBeNull]
Expand Down

0 comments on commit 33ea8ec

Please sign in to comment.