forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResolveTargetingPackAssets.cs
297 lines (242 loc) · 13.6 KB
/
ResolveTargetingPackAssets.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Microsoft.NET.Build.Tasks
{
public class ResolveTargetingPackAssets : TaskBase
{
public ITaskItem[] FrameworkReferences { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] ResolvedTargetingPacks { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] RuntimeFrameworks { get; set; } = Array.Empty<ITaskItem>();
public bool GenerateErrorForMissingTargetingPacks { get; set; }
public bool NuGetRestoreSupported { get; set; } = true;
public string NetCoreTargetingPackRoot { get; set; }
[Output]
public ITaskItem[] ReferencesToAdd { get; set; }
[Output]
public ITaskItem[] PlatformManifests { get; set; }
[Output]
public string PackageConflictPreferredPackages { get; set; }
[Output]
public ITaskItem[] PackageConflictOverrides { get; set; }
[Output]
public ITaskItem[] UsedRuntimeFrameworks { get; set; }
public ResolveTargetingPackAssets()
{
}
protected override void ExecuteCore()
{
List<TaskItem> referencesToAdd = new List<TaskItem>();
List<TaskItem> platformManifests = new List<TaskItem>();
PackageConflictPreferredPackages = string.Empty;
List<TaskItem> packageConflictOverrides = new List<TaskItem>();
List<string> preferredPackages = new List<string>();
var resolvedTargetingPacks = ResolvedTargetingPacks.ToDictionary(item => item.ItemSpec, StringComparer.OrdinalIgnoreCase);
foreach (var frameworkReference in FrameworkReferences)
{
ITaskItem targetingPack;
resolvedTargetingPacks.TryGetValue(frameworkReference.ItemSpec, out targetingPack);
string targetingPackRoot = targetingPack?.GetMetadata(MetadataKeys.Path);
if (string.IsNullOrEmpty(targetingPackRoot) || !Directory.Exists(targetingPackRoot))
{
if (GenerateErrorForMissingTargetingPacks)
{
if (targetingPack == null)
{
Log.LogError(Strings.UnknownFrameworkReference, frameworkReference.ItemSpec);
}
else
{
if (NuGetRestoreSupported)
{
Log.LogError(Strings.TargetingPackNeedsRestore, frameworkReference.ItemSpec);
}
else
{
Log.LogError(
Strings.TargetingApphostPackMissingCannotRestore,
"Targeting",
$"{NetCoreTargetingPackRoot}\\{targetingPack.GetMetadata("NuGetPackageId") ?? ""}",
targetingPack.GetMetadata("TargetFramework") ?? "",
targetingPack.GetMetadata("NuGetPackageId") ?? "",
targetingPack.GetMetadata("NuGetPackageVersion") ?? ""
);
}
}
}
}
else
{
string targetingPackFormat = targetingPack.GetMetadata("TargetingPackFormat");
if (targetingPackFormat.Equals("NETStandardLegacy", StringComparison.OrdinalIgnoreCase))
{
AddNetStandardTargetingPackAssets(targetingPack, targetingPackRoot, referencesToAdd);
}
else
{
string targetingPackTargetFramework = targetingPack.GetMetadata("TargetFramework");
if (string.IsNullOrEmpty(targetingPackTargetFramework))
{
targetingPackTargetFramework = "netcoreapp3.0";
}
string targetingPackDataPath = Path.Combine(targetingPackRoot, "data");
string targetingPackDllFolder = Path.Combine(targetingPackRoot, "ref", targetingPackTargetFramework);
// Fall back to netcoreapp5.0 folder if looking for net5.0 and it's not found
if (!Directory.Exists(targetingPackDllFolder) &&
targetingPackTargetFramework.Equals("net5.0", StringComparison.OrdinalIgnoreCase))
{
targetingPackTargetFramework = "netcoreapp5.0";
targetingPackDllFolder = Path.Combine(targetingPackRoot, "ref", targetingPackTargetFramework);
}
string platformManifestPath = Path.Combine(targetingPackDataPath, "PlatformManifest.txt");
string packageOverridesPath = Path.Combine(targetingPackDataPath, "PackageOverrides.txt");
string frameworkListPath = Path.Combine(targetingPackDataPath, "FrameworkList.xml");
AddReferencesFromFrameworkList(frameworkListPath, targetingPackRoot, targetingPackDllFolder,
targetingPack, referencesToAdd);
if (File.Exists(platformManifestPath))
{
platformManifests.Add(new TaskItem(platformManifestPath));
}
if (File.Exists(packageOverridesPath))
{
packageConflictOverrides.Add(CreatePackageOverride(targetingPack.GetMetadata(MetadataKeys.NuGetPackageId), packageOverridesPath));
}
preferredPackages.AddRange(targetingPack.GetMetadata(MetadataKeys.PackageConflictPreferredPackages).Split(';'));
}
}
}
// Calculate which RuntimeFramework items should actually be used based on framework references
HashSet<string> frameworkReferenceNames = new HashSet<string>(FrameworkReferences.Select(fr => fr.ItemSpec), StringComparer.OrdinalIgnoreCase);
UsedRuntimeFrameworks = RuntimeFrameworks.Where(rf => frameworkReferenceNames.Contains(rf.GetMetadata(MetadataKeys.FrameworkName)))
.ToArray();
// Filter out duplicate references (which can happen when referencing two different profiles that overlap)
List<TaskItem> deduplicatedReferences = DeduplicateItems(referencesToAdd);
ReferencesToAdd = deduplicatedReferences.Distinct() .ToArray();
PlatformManifests = platformManifests.ToArray();
PackageConflictOverrides = packageConflictOverrides.ToArray();
PackageConflictPreferredPackages = string.Join(";", preferredPackages);
}
// Get distinct items based on case-insensitive ItemSpec comparison
private static List<TaskItem> DeduplicateItems(List<TaskItem> items)
{
HashSet<string> seenItemSpecs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
List<TaskItem> deduplicatedItems = new List<TaskItem>(items.Count);
foreach (var item in items)
{
if (seenItemSpecs.Add(item.ItemSpec))
{
deduplicatedItems.Add(item);
}
}
return deduplicatedItems;
}
private TaskItem CreatePackageOverride(string runtimeFrameworkName, string packageOverridesPath)
{
TaskItem packageOverride = new TaskItem(runtimeFrameworkName);
packageOverride.SetMetadata("OverriddenPackages", File.ReadAllText(packageOverridesPath));
return packageOverride;
}
private void AddNetStandardTargetingPackAssets(ITaskItem targetingPack, string targetingPackRoot, List<TaskItem> referencesToAdd)
{
string targetingPackTargetFramework = targetingPack.GetMetadata("TargetFramework");
string targetingPackAssetPath = Path.Combine(targetingPackRoot, "build", targetingPackTargetFramework, "ref");
foreach (var dll in Directory.GetFiles(targetingPackAssetPath, "*.dll"))
{
var reference = CreateReferenceItem(dll, targetingPack);
if (!Path.GetFileName(dll).Equals("netstandard.dll", StringComparison.OrdinalIgnoreCase))
{
reference.SetMetadata("Facade", "true");
}
referencesToAdd.Add(reference);
}
}
private void AddReferencesFromFrameworkList(string frameworkListPath, string targetingPackRoot,
string targetingPackDllFolder,
ITaskItem targetingPack, List<TaskItem> referenceItems)
{
XDocument frameworkListDoc = XDocument.Load(frameworkListPath);
string profile = targetingPack.GetMetadata("Profile");
bool usePathElementsInFrameworkListAsFallBack =
TestFirstFileInFrameworkListUsingAssemblyNameConvention(targetingPackDllFolder, frameworkListDoc);
foreach (var fileElement in frameworkListDoc.Root.Elements("File"))
{
if (!string.IsNullOrEmpty(profile))
{
var profileAttributeValue = fileElement.Attribute("Profile")?.Value;
if (profileAttributeValue == null)
{
// If profile was specified but this assembly doesn't belong to any profiles, don't reference it
continue;
}
var assemblyProfiles = profileAttributeValue.Split(';');
if (!assemblyProfiles.Contains(profile, StringComparer.OrdinalIgnoreCase))
{
// Assembly wasn't in profile specified, so don't reference it
continue;
}
}
string referencedByDefaultAttributeValue = fileElement.Attribute("ReferencedByDefault")?.Value;
if (referencedByDefaultAttributeValue != null &&
referencedByDefaultAttributeValue.Equals("false", StringComparison.OrdinalIgnoreCase))
{
// Don't automatically reference this assembly if it has ReferencedByDefault="false"
continue;
}
string dllPath = usePathElementsInFrameworkListAsFallBack ?
Path.Combine(targetingPackRoot, fileElement.Attribute("Path").Value) :
GetDllPathViaAssemblyName(targetingPackDllFolder, fileElement);
var referenceItem = CreateReferenceItem(dllPath, targetingPack);
referenceItem.SetMetadata("AssemblyVersion", fileElement.Attribute("AssemblyVersion").Value);
referenceItem.SetMetadata("FileVersion", fileElement.Attribute("FileVersion").Value);
referenceItem.SetMetadata("PublicKeyToken", fileElement.Attribute("PublicKeyToken").Value);
referenceItems.Add(referenceItem);
}
}
/// <summary>
/// Due to https://github.com/dotnet/sdk/issues/12098 we fall back to use "Path" when "AssemblyName" will
/// not resolve the actual dll.
/// </summary>
/// <returns>if use we should use "Path" element in frameworkList as a fallback</returns>
private static bool TestFirstFileInFrameworkListUsingAssemblyNameConvention(string targetingPackDllFolder,
XDocument frameworkListDoc)
{
bool usePathElementsInFrameworkListPathAsFallBack;
var firstFileElement = frameworkListDoc.Root.Elements("File").FirstOrDefault();
if (firstFileElement == null)
{
usePathElementsInFrameworkListPathAsFallBack = false;
}
else
{
string dllPath = GetDllPathViaAssemblyName(targetingPackDllFolder, firstFileElement);
usePathElementsInFrameworkListPathAsFallBack = !File.Exists(dllPath);
}
return usePathElementsInFrameworkListPathAsFallBack;
}
private static string GetDllPathViaAssemblyName(string targetingPackDllFolder, XElement fileElement)
{
string assemblyName = fileElement.Attribute("AssemblyName").Value;
var dllPath = Path.Combine(targetingPackDllFolder, assemblyName + ".dll");
return dllPath;
}
private TaskItem CreateReferenceItem(string dll, ITaskItem targetingPack)
{
var reference = new TaskItem(dll);
reference.SetMetadata(MetadataKeys.ExternallyResolved, "true");
reference.SetMetadata(MetadataKeys.Private, "false");
reference.SetMetadata(MetadataKeys.NuGetPackageId, targetingPack.GetMetadata(MetadataKeys.NuGetPackageId));
reference.SetMetadata(MetadataKeys.NuGetPackageVersion, targetingPack.GetMetadata(MetadataKeys.NuGetPackageVersion));
reference.SetMetadata("FrameworkReferenceName", targetingPack.ItemSpec);
reference.SetMetadata("FrameworkReferenceVersion", targetingPack.GetMetadata(MetadataKeys.NuGetPackageVersion));
return reference;
}
}
}