forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PreprocessPackageDependenciesDesignTime.cs
438 lines (372 loc) · 17.9 KB
/
PreprocessPackageDependenciesDesignTime.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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Microsoft.NET.Build.Tasks
{
/// <summary>
/// Task combines data returned from ResolvePackageDependencies into single items collection
/// that can be consumed by DesignTime build and contains all info needed to expand packages
/// dependency graph.
/// If any changes are made here, make sure corresponding changes are made to NuGetDependenciesSubTreeProvider
/// in roslyn-project-system repo and corresponding tests.
/// </summary>
public class PreprocessPackageDependenciesDesignTime : TaskBase
{
public const string DependenciesMetadata = "Dependencies";
public const string CompileTimeAssemblyMetadata = "CompileTimeAssembly";
public const string ResolvedMetadata = "Resolved";
[Required]
public ITaskItem[] TargetDefinitions { get; set; }
[Required]
public ITaskItem[] PackageDefinitions { get; set; }
[Required]
public ITaskItem[] FileDefinitions { get; set; }
[Required]
public ITaskItem[] PackageDependencies { get; set; }
[Required]
public ITaskItem[] FileDependencies { get; set; }
[Required]
public string DefaultImplicitPackages { get; set; }
public ITaskItem[] InputDiagnosticMessages { get; set; }
[Output]
public ITaskItem[] DependenciesDesignTime { get; set; }
private Dictionary<string, ItemMetadata> Targets { get; set; }
= new Dictionary<string, ItemMetadata>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, ItemMetadata> Packages { get; set; }
= new Dictionary<string, ItemMetadata>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, ItemMetadata> Assemblies { get; set; }
= new Dictionary<string, ItemMetadata>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, ItemMetadata> DiagnosticsMap { get; set; }
= new Dictionary<string, ItemMetadata>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, ItemMetadata> DependenciesWorld { get; set; }
= new Dictionary<string, ItemMetadata>(StringComparer.OrdinalIgnoreCase);
private HashSet<string> ImplicitPackageReferences { get; set; }
protected override void ExecuteCore()
{
ImplicitPackageReferences = GetImplicitPackageReferences(DefaultImplicitPackages);
PopulateTargets();
PopulatePackages();
PopulateAssemblies();
InputDiagnosticMessages = InputDiagnosticMessages ?? Array.Empty<ITaskItem>();
PopulateDiagnosticsMap();
AddDependenciesToTheWorld(Packages, PackageDependencies);
AddDependenciesToTheWorld(Assemblies, FileDependencies, (item) =>
{
// We keep analyzers and assemblies with CompileTimeAssembly metadata; skip everything else.
ItemMetadata itemMetadata = null;
if (Assemblies.TryGetValue(item.ItemSpec, out itemMetadata) &&
itemMetadata.Type == DependencyType.AnalyzerAssembly)
{
return false;
}
var fileGroup = item.GetMetadata(MetadataKeys.FileGroup);
return string.IsNullOrEmpty(fileGroup) || !fileGroup.Equals(CompileTimeAssemblyMetadata);
});
AddDependenciesToTheWorld(DiagnosticsMap, InputDiagnosticMessages);
// prepare output collection: add corresponding metadata to ITaskItem based in item type
DependenciesDesignTime = DependenciesWorld.Select(itemKvp =>
{
var newTaskItem = new TaskItem(itemKvp.Key);
foreach(var metadataKvp in itemKvp.Value.ToDictionary())
{
newTaskItem.SetMetadata(metadataKvp.Key, metadataKvp.Value);
}
return newTaskItem;
}).ToArray();
}
/// <summary>
/// Adds targets from TargetDefinitions to dependencies world dictionary
/// </summary>
private void PopulateTargets()
{
foreach (var targetDef in TargetDefinitions)
{
if (string.IsNullOrEmpty(targetDef.ItemSpec) || targetDef.ItemSpec.Contains("/"))
{
// skip "target/rid"s and only consume actual targets
continue;
}
var dependencyType = GetDependencyType(targetDef.GetMetadata(MetadataKeys.Type));
if (dependencyType != DependencyType.Target)
{
// keep only targets here
continue;
}
var target = new TargetMetadata(targetDef);
Targets[targetDef.ItemSpec] = target;
// add target to the world now, since it does not have parents
DependenciesWorld[targetDef.ItemSpec] = target;
}
}
/// <summary>
/// Adds packages from PackageDefinitions to the dependencies world dictionary.
/// </summary>
private void PopulatePackages()
{
foreach (var packageDef in PackageDefinitions)
{
var dependencyType = GetDependencyType(packageDef.GetMetadata(MetadataKeys.Type));
if (dependencyType != DependencyType.Package &&
dependencyType != DependencyType.Unresolved)
{
// we ignore all other dependency types since
// - assemblies we handle separatelly below
// - projects we don't care here, since they are sent to project system via other route
continue;
}
var dependency = new PackageMetadata(packageDef);
dependency.IsImplicitlyDefined = ImplicitPackageReferences.Contains(dependency.Name);
Packages[packageDef.ItemSpec] = dependency;
}
}
/// <summary>
/// Adds assemblies, analyzers and framework assemblies from FileDefinitons to dependencies world dictionary.
/// </summary>
private void PopulateAssemblies()
{
foreach (var fileDef in FileDefinitions)
{
var dependencyType = GetDependencyType(fileDef.GetMetadata(MetadataKeys.Type));
if (dependencyType != DependencyType.Assembly &&
dependencyType != DependencyType.FrameworkAssembly &&
dependencyType != DependencyType.AnalyzerAssembly)
{
continue;
}
var name = Path.GetFileName(fileDef.ItemSpec);
var assembly = new AssemblyMetadata(dependencyType, fileDef, name);
Assemblies[fileDef.ItemSpec] = assembly;
}
}
private void PopulateDiagnosticsMap()
{
foreach (var diagnostic in InputDiagnosticMessages)
{
var metadata = new DiagnosticMetadata(diagnostic);
DiagnosticsMap[diagnostic.ItemSpec] = metadata;
}
}
private DependencyType GetDependencyType(string dependencyTypeString)
{
var dependencyType = DependencyType.Unknown;
if (!string.IsNullOrEmpty(dependencyTypeString))
{
Enum.TryParse(dependencyTypeString, /* ignoreCase */ true, out dependencyType);
}
return dependencyType;
}
private void AddDependenciesToTheWorld(Dictionary<string, ItemMetadata> items,
ITaskItem[] itemDependencies,
Func<ITaskItem, bool> shouldSkipItemCheck = null)
{
foreach (var dependency in itemDependencies)
{
var currentItemId = dependency.ItemSpec;
if (!items.Keys.Contains(currentItemId))
{
// if this package definition does not even exist - skip it
continue;
}
if (shouldSkipItemCheck != null && shouldSkipItemCheck(dependency))
{
continue;
}
var parentTargetId = dependency.GetMetadata(MetadataKeys.ParentTarget) ?? string.Empty;
if (parentTargetId.Contains("/") || !Targets.Keys.Contains(parentTargetId))
{
// skip "target/rid"s and only consume actual targets and ignore non-existent parent targets
continue;
}
var parentPackageId = dependency.GetMetadata(MetadataKeys.ParentPackage) ?? string.Empty;
if (!string.IsNullOrEmpty(parentPackageId) && !Packages.Keys.Contains(parentPackageId))
{
// ignore non-existent parent packages
continue;
}
var currentPackageUniqueId = $"{parentTargetId}/{currentItemId}";
// add current package to dependencies world
var currentItem = items[currentItemId];
DependenciesWorld[currentPackageUniqueId] = currentItem;
// update parent
var parentDependencyId = $"{parentTargetId}/{parentPackageId}".Trim('/');
ItemMetadata parentDependency = null;
if (DependenciesWorld.TryGetValue(parentDependencyId, out parentDependency))
{
parentDependency.Dependencies.Add(currentItemId);
if (parentDependency.Type == DependencyType.Target)
{
currentItem.IsTopLevelDependency = true;
}
}
else
{
// Update parent's Dependencies count and make sure parent is in the dependencies world
if (!string.IsNullOrEmpty(parentPackageId))
{
parentDependency = Packages[parentPackageId];
}
else
{
parentDependency = Targets[parentTargetId];
currentItem.IsTopLevelDependency = true;
}
parentDependency.Dependencies.Add(currentItemId);
DependenciesWorld[parentDependencyId] = parentDependency;
}
}
}
private abstract class ItemMetadata
{
public ItemMetadata(DependencyType type)
{
Type = type;
Dependencies = new List<string>();
}
public DependencyType Type { get; protected set; }
public bool IsTopLevelDependency { get; set; }
/// <summary>
/// A list of name/version strings to specify dependency identities.
/// Note: identity here is just a "name/version" and does not have TFM part in front.
/// </summary>
public IList<string> Dependencies { get; }
/// <summary>
/// Returns name/value pairs for metadata specific to given item type's implementation.
/// </summary>
/// <returns></returns>
public abstract IDictionary<string, string> ToDictionary();
}
private class TargetMetadata : ItemMetadata
{
public TargetMetadata(ITaskItem item)
:base(DependencyType.Target)
{
RuntimeIdentifier = item.GetMetadata(MetadataKeys.RuntimeIdentifier) ?? string.Empty;
TargetFrameworkMoniker = item.GetMetadata(MetadataKeys.TargetFrameworkMoniker) ?? string.Empty;
FrameworkName = item.GetMetadata(MetadataKeys.FrameworkName) ?? string.Empty;
FrameworkVersion = item.GetMetadata(MetadataKeys.FrameworkVersion) ?? string.Empty;
}
public string RuntimeIdentifier { get; }
public string TargetFrameworkMoniker { get; }
public string FrameworkName { get; }
public string FrameworkVersion { get; }
public override IDictionary<string, string> ToDictionary()
{
return new Dictionary<string, string>
{
{ MetadataKeys.RuntimeIdentifier, RuntimeIdentifier },
{ MetadataKeys.TargetFrameworkMoniker, TargetFrameworkMoniker },
{ MetadataKeys.FrameworkName, FrameworkName },
{ MetadataKeys.FrameworkVersion, FrameworkVersion },
{ MetadataKeys.Type, Type.ToString() },
{ DependenciesMetadata, string.Join(";", Dependencies) }
};
}
}
private class PackageMetadata : ItemMetadata
{
public PackageMetadata(ITaskItem item)
: base(DependencyType.Package)
{
Name = item.GetMetadata(MetadataKeys.Name) ?? string.Empty;
Version = item.GetMetadata(MetadataKeys.Version) ?? string.Empty;
Resolved = Type != DependencyType.Unknown && !string.IsNullOrEmpty(item.GetMetadata(MetadataKeys.ResolvedPath));
Path = (Resolved
? item.GetMetadata(MetadataKeys.ResolvedPath)
: item.GetMetadata(MetadataKeys.Path)) ?? string.Empty;
}
public string Name { get; protected set; }
public string Version { get; }
public string Path { get; }
public bool Resolved { get; }
public bool IsImplicitlyDefined { get; set; }
public override IDictionary<string, string> ToDictionary()
{
return new Dictionary<string, string>
{
{ MetadataKeys.Name, Name },
{ MetadataKeys.Version, Version },
{ MetadataKeys.Path, Path },
{ MetadataKeys.Type, Type.ToString() },
{ MetadataKeys.IsImplicitlyDefined, IsImplicitlyDefined.ToString() },
{ MetadataKeys.IsTopLevelDependency, IsTopLevelDependency.ToString() },
{ ResolvedMetadata, Resolved.ToString() },
{ DependenciesMetadata, string.Join(";", Dependencies) }
};
}
}
private class AssemblyMetadata : PackageMetadata
{
public AssemblyMetadata(DependencyType type,
ITaskItem item,
string name)
: base(item)
{
Name = name ?? string.Empty;
Type = type;
}
}
private sealed class DiagnosticMetadata : ItemMetadata
{
public DiagnosticMetadata(ITaskItem item)
: base(DependencyType.Diagnostic)
{
DiagnosticCode = item.GetMetadata(MetadataKeys.DiagnosticCode) ?? string.Empty;
Message = item.GetMetadata(MetadataKeys.Message) ?? string.Empty;
FilePath = item.GetMetadata(MetadataKeys.FilePath) ?? string.Empty;
Severity = item.GetMetadata(MetadataKeys.Severity) ?? string.Empty;
StartLine = item.GetMetadata(MetadataKeys.StartLine) ?? string.Empty;
StartColumn = item.GetMetadata(MetadataKeys.StartColumn) ?? string.Empty;
EndLine = item.GetMetadata(MetadataKeys.EndLine) ?? string.Empty;
EndColumn = item.GetMetadata(MetadataKeys.EndColumn) ?? string.Empty;
}
public string DiagnosticCode { get; }
public string Message { get; }
public string FilePath { get; }
public string Severity { get; }
public string StartLine { get; }
public string StartColumn { get; }
public string EndLine { get; }
public string EndColumn { get; }
public override IDictionary<string, string> ToDictionary()
{
return new Dictionary<string, string>
{
{ MetadataKeys.Name, Message },
{ MetadataKeys.DiagnosticCode, DiagnosticCode },
{ MetadataKeys.Message, Message },
{ MetadataKeys.FilePath, FilePath },
{ MetadataKeys.Severity, Severity },
{ MetadataKeys.StartLine, StartLine },
{ MetadataKeys.StartColumn, StartColumn },
{ MetadataKeys.EndLine, EndLine },
{ MetadataKeys.EndColumn, EndColumn },
{ MetadataKeys.Type, Type.ToString() },
{ DependenciesMetadata, string.Join(";", Dependencies) }
};
}
}
internal static HashSet<string> GetImplicitPackageReferences(string defaultImplicitPackages)
{
var implicitPackageReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(defaultImplicitPackages))
{
return implicitPackageReferences;
}
var packageNames = defaultImplicitPackages.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (packageNames == null || packageNames.Length <= 0)
{
return implicitPackageReferences;
}
foreach (var packageReference in packageNames)
{
implicitPackageReferences.Add(packageReference);
}
return implicitPackageReferences;
}
}
}