-
-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathBuildPropertySourceGenerator.cs
More file actions
97 lines (82 loc) · 2.94 KB
/
BuildPropertySourceGenerator.cs
File metadata and controls
97 lines (82 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace Sentry.SourceGenerators;
/// <summary>
/// Generates the necessary msbuild variables
/// </summary>
[Generator(LanguageNames.CSharp)]
public sealed class BuildPropertySourceGenerator : ISourceGenerator
{
/// <summary>
/// Initialize the source gen
/// </summary>
public void Initialize(GeneratorInitializationContext context)
{
}
/// <summary>
/// Execute the source gen
/// </summary>
public void Execute(GeneratorExecutionContext context)
{
const string tabString = " ";
var opts = context.AnalyzerConfigOptions.GlobalOptions;
var properties = opts.Keys.Where(x => x.StartsWith("build_property.")).ToList();
if (properties.Count == 0)
{
return;
}
if (opts.TryGetValue("build_property.SentryDisableSourceGenerator", out var disable) &&
disable.Equals("true", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
// we only want to generate code where host setup takes place
if (!context.Compilation.Options.OutputKind.IsExe())
{
return;
}
var sb = new StringBuilder();
sb
.Append(
$$"""
// <auto-generated>
// This code was generated by Sentry.SourceGenerators.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// </auto-generated>
#if NET5_0_OR_GREATER
#nullable enable
namespace Sentry.Generated
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{GeneratedCodeText.Tool}}", "{{GeneratedCodeText.Version}}")]
internal static class BuildPropertyInitializer
{
[global::System.Runtime.CompilerServices.ModuleInitializerAttribute]
internal static void Initialize()
{
global::Sentry.CompilerServices.BuildProperties.Initialize(new global::System.Collections.Generic.Dictionary<string, string>(global::System.StringComparer.OrdinalIgnoreCase)
{
"""
);
foreach (var property in properties)
{
if (opts.TryGetValue(property, out var value))
{
var pn = EscapeString(property.Replace("build_property.", ""));
var ev = EscapeString(value);
sb
.Append($"{tabString}{tabString}{tabString}{tabString}{{")
.Append($"\"{pn}\", \"{ev}\"")
.AppendLine("},");
}
}
sb
.AppendLine($"{tabString}{tabString}{tabString}}});") // close dictionary
.AppendLine($"{tabString}{tabString}}}")
.AppendLine($"{tabString}}}")
.AppendLine("}")
.AppendLine("#endif");
context.AddSource("Sentry.Generated.BuildPropertyInitializer.g.cs", sb.ToString());
}
private static string EscapeString(string value) => value.Replace("\\", "\\\\");
}