Skip to content

Commit 6d0bf04

Browse files
authored
Merge pull request #19 from dotnet-campus/t/walterlv/generate
如果不需要生成源代码,则不会生成 Main,否则一定编译不通过
2 parents 2817ab6 + bc4e851 commit 6d0bf04

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/dotnetCampus.Logger.Analyzer/Generators/LoggerGenerator.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,13 @@ private void Execute(SourceProductionContext context, AnalyzerConfigOptionsProvi
3030
is var result
3131
&& !result)
3232
{
33-
// 此项目是通过依赖间接引用的,没有 build 因此无法在源生成器中使用编译属性,所以只能选择引用
33+
// 此项目未设置必要的属性(通常这是不应该出现的,因为 buildTransitive 传递的编译目标会自动生成这些属性)
3434
return;
3535
}
3636

3737
if (!isGenerateSource)
3838
{
39+
// 属性设置为不生成源代码。
3940
return;
4041
}
4142

src/dotnetCampus.Logger.Analyzer/Generators/ProgramMainLogGenerator.cs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using System.Text;
22
using dotnetCampus.Logger.Assets.Templates;
3+
using dotnetCampus.Logger.Utils.CodeAnalysis;
34
using Microsoft.CodeAnalysis;
45
using Microsoft.CodeAnalysis.CSharp;
56
using Microsoft.CodeAnalysis.CSharp.Syntax;
7+
using Microsoft.CodeAnalysis.Diagnostics;
68
using Microsoft.CodeAnalysis.Text;
79
using static dotnetCampus.Logger.Utils.CodeAnalysis.ProgramMainExtensions;
810

@@ -16,7 +18,7 @@ public class ProgramMainLogGenerator : IIncrementalGenerator
1618
{
1719
public void Initialize(IncrementalGeneratorInitializationContext context)
1820
{
19-
var provider = context.SyntaxProvider.CreateSyntaxProvider((node, ct) =>
21+
var syntaxProvider = context.SyntaxProvider.CreateSyntaxProvider((node, ct) =>
2022
{
2123
if (node is not MethodDeclarationSyntax mds)
2224
{
@@ -51,11 +53,28 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
5153
return programTypeSymbol;
5254
});
5355

54-
context.RegisterSourceOutput(provider, Execute);
56+
context.RegisterSourceOutput(syntaxProvider.Combine(context.AnalyzerConfigOptionsProvider), Execute);
5557
}
5658

57-
private void Execute(SourceProductionContext context, INamedTypeSymbol programTypeSymbol)
59+
private void Execute(SourceProductionContext context, (INamedTypeSymbol programTypeSymbol, AnalyzerConfigOptionsProvider analyzerConfigOptions) tuple)
5860
{
61+
var (programTypeSymbol, provider) = tuple;
62+
63+
if (provider.GlobalOptions
64+
.TryGetValue<bool>("_DLGenerateSource", out var isGenerateSource)
65+
is var result
66+
&& !result)
67+
{
68+
// 此项目未设置必要的属性(通常这是不应该出现的,因为 buildTransitive 传递的编译目标会自动生成这些属性)。
69+
return;
70+
}
71+
72+
if (!isGenerateSource)
73+
{
74+
// 属性设置为不生成源代码。
75+
return;
76+
}
77+
5978
// 生成 Program.Logger.g.cs
6079
var partialLoggerFile = GeneratorInfo.GetEmbeddedTemplateFile<Program>();
6180
var generatedLoggerText = ConvertPartialProgramLogger(partialLoggerFile.Content, programTypeSymbol);

0 commit comments

Comments
 (0)