From 013b7a752715face9eb340a1de5ddf3c18c7b876 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Tue, 3 Sep 2024 10:39:28 -0300 Subject: [PATCH] Add an easy way to check for design-time builds --- .../Analyzer/StatusReportingGenerator.cs | 9 ++++++++- .../SponsorLink/AnalyzerOptionsExtensions.cs | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 samples/dotnet/SponsorLink/AnalyzerOptionsExtensions.cs diff --git a/samples/dotnet/Analyzer/StatusReportingGenerator.cs b/samples/dotnet/Analyzer/StatusReportingGenerator.cs index a1437f9d..964a2fd8 100644 --- a/samples/dotnet/Analyzer/StatusReportingGenerator.cs +++ b/samples/dotnet/Analyzer/StatusReportingGenerator.cs @@ -17,7 +17,14 @@ public void Initialize(IncrementalGeneratorInitializationContext context) { var (manifests, options) = source; var status = Diagnostics.GetOrSetStatus(manifests, options); - spc.AddSource("StatusReporting.cs", $"// Status: {status}"); + spc.AddSource("StatusReporting.cs", + $""" + // Status: {status} + // DesignTimeBuild: {options.IsDesignTimeBuild()} + """); + spc.ReportDiagnostic(Diagnostic.Create("SL200", "Compiler", "Don't disable me!", + DiagnosticSeverity.Warning, + DiagnosticSeverity.Warning, true, 1)); }); } } diff --git a/samples/dotnet/SponsorLink/AnalyzerOptionsExtensions.cs b/samples/dotnet/SponsorLink/AnalyzerOptionsExtensions.cs new file mode 100644 index 00000000..d8c29c6b --- /dev/null +++ b/samples/dotnet/SponsorLink/AnalyzerOptionsExtensions.cs @@ -0,0 +1,18 @@ +using Microsoft.CodeAnalysis.Diagnostics; + +static class AnalyzerOptionsExtensions +{ + /// + /// Gets whether the current build is a design-time build. + /// + public static bool IsDesignTimeBuild(this AnalyzerConfigOptionsProvider options) => + options.GlobalOptions.TryGetValue("build_property.DesignTimeBuild", out var value) && + bool.TryParse(value, out var isDesignTime) && isDesignTime; + + /// + /// Gets whether the current build is a design-time build. + /// + public static bool IsDesignTimeBuild(this AnalyzerConfigOptions options) => + options.TryGetValue("build_property.DesignTimeBuild", out var value) && + bool.TryParse(value, out var isDesignTime) && isDesignTime; +} \ No newline at end of file