forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResolvePackageDependencies.cs
452 lines (373 loc) · 17 KB
/
ResolvePackageDependencies.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.Frameworks;
using NuGet.ProjectModel;
namespace Microsoft.NET.Build.Tasks
{
/// <summary>
/// Raises Nuget LockFile representation to MSBuild items and resolves
/// assets specified in the lock file.
/// </summary>
/// <remarks>
/// Only called for backwards compatability, when <c>ResolvePackageDependencies</c> is true.
/// </remarks>
public sealed class ResolvePackageDependencies : TaskBase
{
private readonly Dictionary<string, string> _fileTypes = new(StringComparer.OrdinalIgnoreCase);
private HashSet<string> _projectFileDependencies;
private IPackageResolver _packageResolver;
private LockFile _lockFile;
#region Output Items
private readonly List<ITaskItem> _targetDefinitions = new();
private readonly List<ITaskItem> _packageDefinitions = new();
private readonly List<ITaskItem> _fileDefinitions = new();
private readonly List<ITaskItem> _packageDependencies = new();
private readonly List<ITaskItem> _fileDependencies = new();
/// <summary>
/// All the targets in the lock file.
/// </summary>
[Output]
public ITaskItem[] TargetDefinitions
{
get { return _targetDefinitions.ToArray(); }
}
/// <summary>
/// All the libraries/packages in the lock file.
/// </summary>
[Output]
public ITaskItem[] PackageDefinitions
{
get { return _packageDefinitions.ToArray(); }
}
/// <summary>
/// All the files in the lock file.
/// </summary>
[Output]
public ITaskItem[] FileDefinitions
{
get { return _fileDefinitions.ToArray(); }
}
/// <summary>
/// All the dependencies between packages. Each package has metadata 'ParentPackage'
/// to refer to the package that depends on it. For top level packages this value is blank.
/// </summary>
[Output]
public ITaskItem[] PackageDependencies
{
get { return _packageDependencies.ToArray(); }
}
/// <summary>
/// All the dependencies between files and packages, labeled by the group containing
/// the file (e.g. CompileTimeAssembly, RuntimeAssembly, etc.).
/// </summary>
[Output]
public ITaskItem[] FileDependencies
{
get { return _fileDependencies.ToArray(); }
}
#endregion
#region Inputs
/// <summary>
/// The path to the current project.
/// </summary>
[Required]
public string ProjectPath
{
get; set;
}
/// <summary>
/// The assets file to process
/// </summary>
public string ProjectAssetsFile
{
get; set;
}
/// <summary>
/// Optional the Project Language (E.g. C#, VB)
/// </summary>
public string ProjectLanguage
{
get; set;
}
public string TargetFramework { get; set; }
#endregion
public ResolvePackageDependencies()
{
}
#region Test Support
internal ResolvePackageDependencies(LockFile lockFile, IPackageResolver packageResolver)
: this()
{
_lockFile = lockFile;
_packageResolver = packageResolver;
}
#endregion
private IPackageResolver PackageResolver => _packageResolver ??= NuGetPackageResolver.CreateResolver(LockFile);
private LockFile LockFile => _lockFile ??= new LockFileCache(this).GetLockFile(ProjectAssetsFile);
private Dictionary<string, string> _targetNameToAliasMap;
/// <summary>
/// Raise Nuget LockFile representation to MSBuild items
/// </summary>
protected override void ExecuteCore()
{
_targetNameToAliasMap = LockFile.Targets.ToDictionary(t => t.Name, t =>
{
var alias = LockFile.GetLockFileTargetAlias(t);
if (string.IsNullOrEmpty(t.RuntimeIdentifier))
{
return alias;
}
else
{
return alias + "/" + t.RuntimeIdentifier;
}
});
ReadProjectFileDependencies(string.IsNullOrEmpty(TargetFramework) || !_targetNameToAliasMap.ContainsKey(TargetFramework) ? null : _targetNameToAliasMap[TargetFramework]);
RaiseLockFileTargets();
GetPackageAndFileDefinitions();
}
private void ReadProjectFileDependencies(string frameworkAlias)
{
_projectFileDependencies = LockFile.GetProjectFileDependencySet(frameworkAlias);
}
// get library and file definitions
private void GetPackageAndFileDefinitions()
{
foreach (var package in LockFile.Libraries)
{
var packageName = package.Name;
var packageVersion = package.Version.ToNormalizedString();
string packageId = $"{packageName}/{packageVersion}";
var item = new TaskItem(packageId);
item.SetMetadata(MetadataKeys.Name, packageName);
item.SetMetadata(MetadataKeys.Type, package.Type);
item.SetMetadata(MetadataKeys.Version, packageVersion);
item.SetMetadata(MetadataKeys.Path, package.Path ?? string.Empty);
string resolvedPackagePath = ResolvePackagePath(package);
item.SetMetadata(MetadataKeys.ResolvedPath, resolvedPackagePath ?? string.Empty);
item.SetMetadata(MetadataKeys.DiagnosticLevel, GetPackageDiagnosticLevel(package));
_packageDefinitions.Add(item);
foreach (var file in package.Files)
{
if (NuGetUtils.IsPlaceholderFile(file))
{
continue;
}
var fileKey = $"{packageId}/{file}";
var fileItem = new TaskItem(fileKey);
fileItem.SetMetadata(MetadataKeys.Path, file);
fileItem.SetMetadata(MetadataKeys.NuGetPackageId, packageName);
fileItem.SetMetadata(MetadataKeys.NuGetPackageVersion, packageVersion);
string resolvedPath = ResolveFilePath(file, resolvedPackagePath);
fileItem.SetMetadata(MetadataKeys.ResolvedPath, resolvedPath ?? string.Empty);
if (NuGetUtils.IsApplicableAnalyzer(file, ProjectLanguage))
{
fileItem.SetMetadata(MetadataKeys.Analyzer, "true");
fileItem.SetMetadata(MetadataKeys.Type, "AnalyzerAssembly");
// get targets that contain this package
var parentTargets = LockFile.Targets
.Where(t => t.Libraries.Any(lib => lib.Name == package.Name));
foreach (var target in parentTargets)
{
string frameworkAlias = _targetNameToAliasMap[target.Name];
var fileDepsItem = new TaskItem(fileKey);
fileDepsItem.SetMetadata(MetadataKeys.ParentTarget, frameworkAlias); // Foreign Key
fileDepsItem.SetMetadata(MetadataKeys.ParentPackage, packageId); // Foreign Key
_fileDependencies.Add(fileDepsItem);
}
}
else
{
// get a type for the file if one is available
if (!_fileTypes.TryGetValue(fileKey, out string fileType))
{
fileType = "unknown";
}
fileItem.SetMetadata(MetadataKeys.Type, fileType);
}
_fileDefinitions.Add(fileItem);
}
}
string GetPackageDiagnosticLevel(LockFileLibrary package)
{
string target = TargetFramework ?? "";
var messages = LockFile.LogMessages.Where(log => log.LibraryId == package.Name && log.TargetGraphs
.Select(tg =>
{
var parsedTargetGraph = NuGetFramework.Parse(tg);
var alias = _lockFile.PackageSpec.TargetFrameworks.FirstOrDefault(tf => tf.FrameworkName == parsedTargetGraph)?.TargetAlias;
return alias ?? tg;
}).Contains(target));
if (!messages.Any())
{
return string.Empty;
}
return messages.Max(log => log.Level).ToString();
}
}
// get target definitions and package and file dependencies
private void RaiseLockFileTargets()
{
foreach (var target in LockFile.Targets)
{
TaskItem item = new(target.Name);
item.SetMetadata(MetadataKeys.RuntimeIdentifier, target.RuntimeIdentifier ?? string.Empty);
item.SetMetadata(MetadataKeys.TargetFramework, TargetFramework);
item.SetMetadata(MetadataKeys.TargetFrameworkMoniker, target.TargetFramework.DotNetFrameworkName);
item.SetMetadata(MetadataKeys.FrameworkName, target.TargetFramework.Framework);
item.SetMetadata(MetadataKeys.FrameworkVersion, target.TargetFramework.Version.ToString());
item.SetMetadata(MetadataKeys.Type, "target");
_targetDefinitions.Add(item);
// raise each library in the target
GetPackageAndFileDependencies(target);
}
}
private void GetPackageAndFileDependencies(LockFileTarget target)
{
var resolvedPackageVersions = target.Libraries
.ToDictionary(pkg => pkg.Name, pkg => pkg.Version.ToNormalizedString(), StringComparer.OrdinalIgnoreCase);
string frameworkAlias = _targetNameToAliasMap[target.Name];
var transitiveProjectRefs = new HashSet<string>(
target.Libraries
.Where(lib => lib.IsTransitiveProjectReference(LockFile, ref _projectFileDependencies, frameworkAlias))
.Select(pkg => pkg.Name),
StringComparer.OrdinalIgnoreCase);
foreach (var package in target.Libraries)
{
string packageId = $"{package.Name}/{package.Version.ToNormalizedString()}";
if (_projectFileDependencies.Contains(package.Name))
{
TaskItem item = new(packageId);
item.SetMetadata(MetadataKeys.ParentTarget, frameworkAlias); // Foreign Key
item.SetMetadata(MetadataKeys.ParentPackage, string.Empty); // Foreign Key
_packageDependencies.Add(item);
}
// get sub package dependencies
GetPackageDependencies(package, target.Name, resolvedPackageVersions, transitiveProjectRefs);
// get file dependencies on this package
GetFileDependencies(package, target.Name);
}
}
private void GetPackageDependencies(
LockFileTargetLibrary package,
string targetName,
Dictionary<string, string> resolvedPackageVersions,
HashSet<string> transitiveProjectRefs)
{
string packageId = $"{package.Name}/{package.Version.ToNormalizedString()}";
string frameworkAlias = _targetNameToAliasMap[targetName];
foreach (var deps in package.Dependencies)
{
if (!resolvedPackageVersions.TryGetValue(deps.Id, out string version))
{
continue;
}
string depsName = $"{deps.Id}/{version}";
TaskItem item = new(depsName);
item.SetMetadata(MetadataKeys.ParentTarget, frameworkAlias); // Foreign Key
item.SetMetadata(MetadataKeys.ParentPackage, packageId); // Foreign Key
if (transitiveProjectRefs.Contains(deps.Id))
{
item.SetMetadata(MetadataKeys.TransitiveProjectReference, "true");
}
_packageDependencies.Add(item);
}
}
private void GetFileDependencies(LockFileTargetLibrary package, string targetName)
{
string packageId = $"{package.Name}/{package.Version.ToNormalizedString()}";
string frameworkAlias = _targetNameToAliasMap[targetName];
// for each type of file group
foreach (var fileGroup in (FileGroup[])Enum.GetValues(typeof(FileGroup)))
{
var filePathList = fileGroup.GetFilePathAndProperties(package);
foreach (var entry in filePathList)
{
string filePath = entry.Item1;
IDictionary<string, string> properties = entry.Item2;
if (NuGetUtils.IsPlaceholderFile(filePath))
{
continue;
}
var fileKey = $"{packageId}/{filePath}";
var item = new TaskItem(fileKey);
item.SetMetadata(MetadataKeys.FileGroup, fileGroup.ToString());
item.SetMetadata(MetadataKeys.ParentTarget, frameworkAlias); // Foreign Key
item.SetMetadata(MetadataKeys.ParentPackage, packageId); // Foreign Key
if (fileGroup == FileGroup.FrameworkAssembly)
{
// NOTE: the path provided for framework assemblies is the name of the framework reference
item.SetMetadata("FrameworkAssembly", filePath);
item.SetMetadata(MetadataKeys.NuGetPackageId, package.Name);
item.SetMetadata(MetadataKeys.NuGetPackageVersion, package.Version.ToNormalizedString());
}
foreach (var property in properties)
{
item.SetMetadata(property.Key, property.Value);
}
_fileDependencies.Add(item);
// map each file key to a Type metadata value
SaveFileKeyType(fileKey, fileGroup);
}
}
}
// save file type metadata based on the group the file appears in
private void SaveFileKeyType(string fileKey, FileGroup fileGroup)
{
string fileType = fileGroup.GetTypeMetadata();
if (fileType != null)
{
if (!_fileTypes.TryGetValue(fileKey, out string currentFileType))
{
_fileTypes.Add(fileKey, fileType);
}
else if (currentFileType != fileType)
{
throw new BuildErrorException(Strings.UnexpectedFileType, fileKey, fileType, currentFileType);
}
}
}
private string ResolvePackagePath(LockFileLibrary package)
{
if (package.IsProject())
{
var relativeMSBuildProjectPath = package.MSBuildProject;
if (string.IsNullOrEmpty(relativeMSBuildProjectPath))
{
throw new BuildErrorException(Strings.ProjectAssetsConsumedWithoutMSBuildProjectPath, package.Name, ProjectAssetsFile);
}
return GetAbsolutePathFromProjectRelativePath(relativeMSBuildProjectPath);
}
else
{
return PackageResolver.GetPackageDirectory(package.Name, package.Version);
}
}
private static string ResolveFilePath(string relativePath, string resolvedPackagePath)
{
if (NuGetUtils.IsPlaceholderFile(relativePath))
{
return null;
}
if (resolvedPackagePath == null)
{
return string.Empty;
}
if (Path.DirectorySeparatorChar != '/')
{
relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar);
}
if (Path.DirectorySeparatorChar != '\\')
{
relativePath = relativePath.Replace('\\', Path.DirectorySeparatorChar);
}
return Path.Combine(resolvedPackagePath, relativePath);
}
private string GetAbsolutePathFromProjectRelativePath(string path)
{
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(ProjectPath), path));
}
}
}