Skip to content

Commit

Permalink
Merge pull request #19 from dotnet-campus/t/walterlv/generate
Browse files Browse the repository at this point in the history
如果不需要生成源代码,则不会生成 Main,否则一定编译不通过
  • Loading branch information
lindexi authored Aug 16, 2024
2 parents 2817ab6 + bc4e851 commit 6d0bf04
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,13 @@ private void Execute(SourceProductionContext context, AnalyzerConfigOptionsProvi
is var result
&& !result)
{
// 此项目是通过依赖间接引用的,没有 build 因此无法在源生成器中使用编译属性,所以只能选择引用
// 此项目未设置必要的属性(通常这是不应该出现的,因为 buildTransitive 传递的编译目标会自动生成这些属性)
return;
}

if (!isGenerateSource)
{
// 属性设置为不生成源代码。
return;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System.Text;
using dotnetCampus.Logger.Assets.Templates;
using dotnetCampus.Logger.Utils.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using static dotnetCampus.Logger.Utils.CodeAnalysis.ProgramMainExtensions;

Expand All @@ -16,7 +18,7 @@ public class ProgramMainLogGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var provider = context.SyntaxProvider.CreateSyntaxProvider((node, ct) =>
var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider((node, ct) =>
{
if (node is not MethodDeclarationSyntax mds)
{
Expand Down Expand Up @@ -51,11 +53,28 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
return programTypeSymbol;
});

context.RegisterSourceOutput(provider, Execute);
context.RegisterSourceOutput(syntaxProvider.Combine(context.AnalyzerConfigOptionsProvider), Execute);
}

private void Execute(SourceProductionContext context, INamedTypeSymbol programTypeSymbol)
private void Execute(SourceProductionContext context, (INamedTypeSymbol programTypeSymbol, AnalyzerConfigOptionsProvider analyzerConfigOptions) tuple)
{
var (programTypeSymbol, provider) = tuple;

if (provider.GlobalOptions
.TryGetValue<bool>("_DLGenerateSource", out var isGenerateSource)
is var result
&& !result)
{
// 此项目未设置必要的属性(通常这是不应该出现的,因为 buildTransitive 传递的编译目标会自动生成这些属性)。
return;
}

if (!isGenerateSource)
{
// 属性设置为不生成源代码。
return;
}

// 生成 Program.Logger.g.cs
var partialLoggerFile = GeneratorInfo.GetEmbeddedTemplateFile<Program>();
var generatedLoggerText = ConvertPartialProgramLogger(partialLoggerFile.Content, programTypeSymbol);
Expand Down

0 comments on commit 6d0bf04

Please sign in to comment.