-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathProject.cs
231 lines (198 loc) · 9.45 KB
/
Project.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// <copyright file="Project.cs" company="David Federman">
// Copyright (c) David Federman. All rights reserved.
// </copyright>
namespace ReferenceTrimmer
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Buildalyzer;
using Buildalyzer.Environment;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
internal sealed class Project
{
private static readonly Dictionary<string, Project> Projects = new Dictionary<string, Project>(StringComparer.OrdinalIgnoreCase);
private Project()
{
}
public string Name { get; private set; }
public string AssemblyName { get; private set; }
public HashSet<string> AssemblyReferences { get; private set; }
public List<string> References { get; private set; }
public List<Project> ProjectReferences { get; private set; }
public List<string> PackageReferences { get; private set; }
public Dictionary<string, List<string>> PackageAssemblies { get; private set; }
public static Project GetProject(
AnalyzerManager manager,
BuildEnvironment buildEnvironment,
string projectFile,
bool useBinlog)
{
if (!Projects.TryGetValue(projectFile, out var project))
{
project = Create(manager, buildEnvironment, projectFile, useBinlog);
Projects.Add(projectFile, project);
}
return project;
}
private static Project Create(
AnalyzerManager manager,
BuildEnvironment buildEnvironment,
string projectFile,
bool useBinlog)
{
var oldCurrentDirectory = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(Path.GetDirectoryName(projectFile));
try
{
var analyzer = buildEnvironment == null
? manager.GetProject(projectFile)
: manager.GetProject(projectFile, buildEnvironment);
var msBuildProject = analyzer.Load();
var assemblyFile = msBuildProject.GetItems("IntermediateAssembly").FirstOrDefault()?.EvaluatedInclude;
if (string.IsNullOrEmpty(assemblyFile))
{
// Not all projects may produce an assembly
return null;
}
var projectDirectory = Path.GetDirectoryName(projectFile);
var assemblyFileFullPath = Path.GetFullPath(Path.Combine(projectDirectory, assemblyFile));
if (!File.Exists(assemblyFileFullPath))
{
// Can't analyze this project since it hasn't been built
Console.WriteLine($"Assembly did not exist. Ensure you've previously built it. Assembly: {assemblyFileFullPath}");
return null;
}
var assembly = LoadAssembly(assemblyFileFullPath);
if (assembly == null)
{
// Can't analyze this project since we couldn't load its assembly
Console.WriteLine($"Assembly could not be loaded. Assembly: {assemblyFileFullPath}");
return null;
}
var assemblyReferences = assembly
.GetReferencedAssemblies()
.Select(name => name.Name)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var references = msBuildProject
.GetItems("Reference")
.Select(reference => reference.EvaluatedInclude)
.ToList();
var projectReferences = msBuildProject
.GetItems("ProjectReference")
.Select(reference => reference.EvaluatedInclude)
.Select(projectReference => GetProject(manager, buildEnvironment, Path.GetFullPath(Path.Combine(projectDirectory, projectReference)), useBinlog))
.Where(dependency => dependency != null)
.ToList();
var packageReferences = msBuildProject
.GetItems("PackageReference")
.Select(reference => reference.EvaluatedInclude)
.ToList();
// Certain project types may require references simply to copy them to the output folder to satisfy transitive dependencies.
if (NeedsTransitiveAssemblyReferences(msBuildProject))
{
projectReferences.ForEach(projectReference => assemblyReferences.UnionWith(projectReference.AssemblyReferences));
}
// Only bother doing a design-time build if there is a reason to
var packageAssemblies = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
if (packageReferences.Count > 0)
{
if (useBinlog)
{
analyzer.WithBinaryLog();
}
var msBuildCompiledProject = analyzer.Compile();
var packageParents = msBuildCompiledProject.GetItems("_ActiveTFMPackageDependencies")
.Where(package => !string.IsNullOrEmpty(package.GetMetadataValue("ParentPackage")))
.GroupBy(
package =>
{
var packageIdentity = package.EvaluatedInclude;
return packageIdentity.Substring(0, packageIdentity.IndexOf('/'));
},
package =>
{
var parentPackageIdentity = package.GetMetadataValue("ParentPackage");
return parentPackageIdentity.Substring(0, parentPackageIdentity.IndexOf('/'));
},
StringComparer.OrdinalIgnoreCase)
.ToDictionary(group => group.Key, group => group.ToList());
var resolvedPackageReferences = msBuildCompiledProject.GetItems("Reference")
.Where(reference => reference.GetMetadataValue("NuGetSourceType").Equals("Package", StringComparison.OrdinalIgnoreCase));
foreach (var resolvedPackageReference in resolvedPackageReferences)
{
var assemblyName = Path.GetFileNameWithoutExtension(resolvedPackageReference.EvaluatedInclude);
// Add the assembly to the containing package and all parent packages.
var seenParents = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var queue = new Queue<string>();
queue.Enqueue(resolvedPackageReference.GetMetadataValue("NuGetPackageId"));
while (queue.Count > 0)
{
var packageId = queue.Dequeue();
if (!packageAssemblies.TryGetValue(packageId, out var assemblies))
{
assemblies = new List<string>();
packageAssemblies.Add(packageId, assemblies);
}
assemblies.Add(assemblyName);
if (packageParents.TryGetValue(packageId, out var parents))
{
foreach (var parent in parents)
{
if (seenParents.Add(parent))
{
queue.Enqueue(parent);
}
}
}
}
}
}
return new Project
{
Name = projectFile,
AssemblyName = assembly.GetName().Name,
AssemblyReferences = assemblyReferences,
References = references,
ProjectReferences = projectReferences,
PackageReferences = packageReferences,
PackageAssemblies = packageAssemblies,
};
}
catch (Exception e)
{
Console.WriteLine($"Exception while trying to load: {projectFile}. Exception: {e}");
return null;
}
finally
{
Directory.SetCurrentDirectory(oldCurrentDirectory);
}
}
private static Assembly LoadAssembly(string assemblyFile)
{
try
{
return Assembly.LoadFile(assemblyFile);
}
catch (Exception e)
{
Console.WriteLine(assemblyFile);
Console.WriteLine(e);
Console.WriteLine();
return null;
}
}
private static bool NeedsTransitiveAssemblyReferences(MsBuildProject msBuildProject)
{
var outputType = msBuildProject.GetPropertyValue("OutputType");
if (outputType.Equals("Exe", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
}
}