-
Notifications
You must be signed in to change notification settings - Fork 0
/
SourceGeneratorResolver.cs
156 lines (129 loc) · 6.74 KB
/
SourceGeneratorResolver.cs
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
using System;
using System.Collections.Immutable;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Tbc.Host.Components.Abstractions;
using Tbc.Host.Components.SourceGeneratorResolver.Models;
namespace Tbc.Host.Components.SourceGeneratorResolver;
public class SourceGeneratorResolver : ComponentBase<SourceGeneratorResolver>, ISourceGeneratorResolver
{
private readonly IFileSystem _fileSystem;
private string GetNugetPackageCachePath
=> NuGet.Configuration.SettingsUtility.GetGlobalPackagesFolder(NuGet.Configuration.Settings.LoadDefaultSettings(null));
private static readonly ImmutableHashSet<Type> SourceGeneratorTypes
= new[] { typeof(IIncrementalGenerator), typeof(ISourceGenerator) }.ToImmutableHashSet();
public SourceGeneratorResolver(ILogger<SourceGeneratorResolver> logger, IFileSystem fileSystem) : base(logger)
{
_fileSystem = fileSystem;
}
public Task<ResolveSourceGeneratorsResponse> ResolveSourceGenerators(ResolveSourceGeneratorsRequest request,
CancellationToken canceller = default)
{
var (req, (kind, reference, context)) = (request.Reference, request.Reference);
var (srcs, incs, diags) = kind switch
{
SourceGeneratorReferenceKind.AssemblyPath => GetGeneratorsFromAssembly(reference),
SourceGeneratorReferenceKind.NuGetPackageReference => GetGeneratorsFromNugetPackageReference(reference, context),
SourceGeneratorReferenceKind.Csproj => GetGeneratorsFromCsproj(reference),
_ => throw new NotImplementedException()
};
// remove any dups
srcs = srcs.GroupBy(x => x.GetType()).Select(x => x.First()).ToImmutableList();
incs = incs.GroupBy(x => x.GetType()).Select(x => x.First()).ToImmutableList();
return Task.FromResult(new ResolveSourceGeneratorsResponse(req, srcs, incs, diags));
}
private (ImmutableList<ISourceGenerator> Srcs, ImmutableList<IIncrementalGenerator> Incs, ImmutableDictionary<string, object> Diags)
GetGeneratorsFromNugetPackageReference(string package, string? maybeVersion)
{
var version = maybeVersion
?? _fileSystem.Directory.GetDirectories(_fileSystem.Path.Combine(GetNugetPackageCachePath, package))
.OrderByDescending(x => x)
.FirstOrDefault();
if (String.IsNullOrWhiteSpace(version))
{
Logger.LogWarning("No version provided for source generator package {Package} and none could be inferred",
package);
return (Srcs: ImmutableList.Create<ISourceGenerator>(),
Incs: ImmutableList.Create<IIncrementalGenerator>(),
Diags: ImmutableDictionary.Create<string, object>());
}
var searches = new[] { "roslyn4.0/cs", "roslyn4.0\\cs", "analyzers/dotnet/cs", "analyzers\\dotnet\\cs" };
var nugetPath = _fileSystem.Path.Combine(GetNugetPackageCachePath, package, version);
var dllPaths = _fileSystem.Directory.GetFiles(nugetPath, "*.dll", SearchOption.AllDirectories)
.Where(x => searches.Any(s => x.Contains(s, StringComparison.InvariantCultureIgnoreCase)));
return Enumerable.Aggregate(
dllPaths,
( Srcs: ImmutableList.Create<ISourceGenerator>(),
Incs: ImmutableList.Create<IIncrementalGenerator>(),
Diags: ImmutableDictionary.Create<string, object>()),
(curr, path) =>
{
var (newSrc, newInc, newDiagnostics) = GetGeneratorsFromAssembly(path);
return (curr.Srcs.AddRange(newSrc), curr.Incs.AddRange(newInc), curr.Diags.AddRange(newDiagnostics));
});
}
private (ImmutableList<ISourceGenerator>, ImmutableList<IIncrementalGenerator>, ImmutableDictionary<string, object>)
GetGeneratorsFromAssembly(string path)
{
var diagnostics = ImmutableDictionary.Create<string, object>();
Assembly asm = null!;
try { asm = Assembly.LoadFile(path); }
catch (Exception ex)
{
return (ImmutableList<ISourceGenerator>.Empty, ImmutableList<IIncrementalGenerator>.Empty,
diagnostics.Add($"load-assembly {path}", ex));
}
var generatorTypes = asm.GetTypes()
.Where(x => x.GetInterfaces().Any(SourceGeneratorTypes.Contains))
.Where(x => !x.IsAbstract)
.ToList();
var instances = generatorTypes.Select(x =>
{
try { return Activator.CreateInstance(x); }
catch (Exception ex) {
diagnostics = diagnostics.Add($"instantiate {x.FullName}", ex);
return null;
}
})
.Where(x => x != null)
.ToList();
var srcs = instances.OfType<ISourceGenerator>().ToImmutableList();
var incs = instances.OfType<IIncrementalGenerator>().ToImmutableList();
return (srcs, incs, diagnostics);
}
private (ImmutableList<ISourceGenerator> Srcs, ImmutableList<IIncrementalGenerator> Incs, ImmutableDictionary<string, object> Diags)
GetGeneratorsFromCsproj(string csProjPath)
{
var xml = _fileSystem.File.ReadAllText(csProjPath);
var doc = XDocument.Parse(xml);
var packageReferences =
doc.DescendantNodes()
.OfType<XElement>()
.Where(x => x.Name.LocalName == "PackageReference")
.Select(pr => new { Include = pr.Attribute("Include")?.Value, Version = pr.Attribute("Version")?.Value })
.Where(x => x.Include is not null && x.Version is not null)
.Select(pr => new PackageReference(pr.Include!, pr.Version!))
.ToList();
foreach (var packageReference in packageReferences)
Logger.LogDebug("Found nuget ref in {CsProjName}: {PackageIdentifier}, version {PackageVersion}",
Path.GetFileName(csProjPath), packageReference.Include, packageReference.Version);
return Enumerable.Aggregate(
packageReferences,
( Srcs: ImmutableList.Create<ISourceGenerator>(),
Incs: ImmutableList.Create<IIncrementalGenerator>(),
Diags: ImmutableDictionary.Create<string, object>()),
(curr, packageRef) =>
{
var (newSrc, newInc, newDiagnostics) =
GetGeneratorsFromNugetPackageReference(packageRef.Include, packageRef.Version.ToString());
return (curr.Srcs.AddRange(newSrc), curr.Incs.AddRange(newInc), curr.Diags.AddRange(newDiagnostics));
});
}
}