forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DependencyContextBuilder.cs
648 lines (568 loc) · 25.2 KB
/
DependencyContextBuilder.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// 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 System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.DependencyModel;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
using NuGet.Versioning;
namespace Microsoft.NET.Build.Tasks
{
internal class DependencyContextBuilder
{
private readonly VersionFolderPathResolver _versionFolderPathResolver;
private readonly SingleProjectInfo _mainProjectInfo;
private readonly ProjectContext _projectContext;
private IEnumerable<ReferenceInfo> _referenceAssemblies;
private IEnumerable<ReferenceInfo> _directReferences;
private Dictionary<string, SingleProjectInfo> _referenceProjectInfos;
private IEnumerable<string> _excludeFromPublishPackageIds;
private CompilationOptions _compilationOptions;
private string _referenceAssembliesPath;
private Dictionary<PackageIdentity, string> _filteredPackages;
private bool _includeMainProjectInDepsFile = true;
private HashSet<string> _usedLibraryNames;
private Dictionary<ReferenceInfo, string> _referenceLibraryNames;
public DependencyContextBuilder(SingleProjectInfo mainProjectInfo, ProjectContext projectContext)
{
_mainProjectInfo = mainProjectInfo;
_projectContext = projectContext;
// This resolver is only used for building file names, so that base path is not required.
_versionFolderPathResolver = new VersionFolderPathResolver(rootPath: null);
}
/// <summary>
/// Keeps track of the Library names being used in the DependencyContext.
/// </summary>
/// <remarks>
/// Since `Reference` and `PackageReference` names can conflict, we need to ensure
/// each separate Library has a unique name. Since PackageReference names are guaranteed
/// to be unique amongst other PackageReferences, start with that set, and ensure
/// Reference names are unique amongst all.
/// </remarks>
private HashSet<string> UsedLibraryNames
{
get
{
if (_usedLibraryNames == null)
{
_usedLibraryNames = new HashSet<string>(
_projectContext.LockFile.Libraries.Select(l => l.Name),
StringComparer.OrdinalIgnoreCase);
}
return _usedLibraryNames;
}
}
private Dictionary<ReferenceInfo, string> ReferenceLibraryNames
{
get
{
if (_referenceLibraryNames == null)
{
_referenceLibraryNames = new Dictionary<ReferenceInfo, string>();
}
return _referenceLibraryNames;
}
}
public DependencyContextBuilder WithMainProjectInDepsFile(bool includeMainProjectInDepsFile)
{
_includeMainProjectInDepsFile = includeMainProjectInDepsFile;
return this;
}
public DependencyContextBuilder WithReferenceAssemblies(IEnumerable<ReferenceInfo> referenceAssemblies)
{
// note: ReferenceAssembly libraries only export compile-time stuff
// since they assume the runtime library is present already
_referenceAssemblies = referenceAssemblies;
return this;
}
public DependencyContextBuilder WithDirectReferences(IEnumerable<ReferenceInfo> directReferences)
{
_directReferences = directReferences;
return this;
}
public DependencyContextBuilder WithReferenceProjectInfos(Dictionary<string, SingleProjectInfo> referenceProjectInfos)
{
_referenceProjectInfos = referenceProjectInfos;
return this;
}
public DependencyContextBuilder WithExcludeFromPublishAssets(IEnumerable<string> excludeFromPublishPackageIds)
{
_excludeFromPublishPackageIds = excludeFromPublishPackageIds;
return this;
}
public DependencyContextBuilder WithCompilationOptions(CompilationOptions compilationOptions)
{
_compilationOptions = compilationOptions;
return this;
}
public DependencyContextBuilder WithReferenceAssembliesPath(string referenceAssembliesPath)
{
_referenceAssembliesPath = EnsureTrailingSlash(referenceAssembliesPath);
return this;
}
public DependencyContextBuilder WithPackagesThatWhereFiltered(Dictionary<PackageIdentity, string> packagesThatWhereFiltered)
{
_filteredPackages = packagesThatWhereFiltered;
return this;
}
public DependencyContext Build()
{
bool includeCompilationLibraries = _compilationOptions != null;
IEnumerable<LockFileTargetLibrary> runtimeExports = _projectContext.GetRuntimeLibraries(_excludeFromPublishPackageIds);
IEnumerable<LockFileTargetLibrary> compilationExports =
includeCompilationLibraries ?
_projectContext.GetCompileLibraries(_excludeFromPublishPackageIds) :
Enumerable.Empty<LockFileTargetLibrary>();
var dependencyLookup = compilationExports
.Concat(runtimeExports)
.Distinct()
.Select(library => new Dependency(library.Name, library.Version.ToString()))
.ToDictionary(dependency => dependency.Name, StringComparer.OrdinalIgnoreCase);
var libraryLookup = new LockFileLookup(_projectContext.LockFile);
var runtimeSignature = GenerateRuntimeSignature(runtimeExports);
IEnumerable<RuntimeLibrary> runtimeLibraries = Enumerable.Empty<RuntimeLibrary>();
if (_includeMainProjectInDepsFile)
{
runtimeLibraries = runtimeLibraries.Concat(new[]
{
GetProjectRuntimeLibrary(
_mainProjectInfo,
_projectContext,
dependencyLookup,
includeCompilationLibraries)
});
}
runtimeLibraries = runtimeLibraries
.Concat(GetLibraries(runtimeExports, libraryLookup, dependencyLookup, runtime: true).Cast<RuntimeLibrary>())
.Concat(GetDirectReferenceRuntimeLibraries());
IEnumerable<CompilationLibrary> compilationLibraries = Enumerable.Empty<CompilationLibrary>();
if (includeCompilationLibraries)
{
if (_includeMainProjectInDepsFile)
{
compilationLibraries = compilationLibraries.Concat(new[]
{
GetProjectCompilationLibrary(
_mainProjectInfo,
_projectContext,
dependencyLookup,
includeCompilationLibraries)
});
}
compilationLibraries = compilationLibraries
.Concat(GetReferenceAssemblyLibraries())
.Concat(GetLibraries(compilationExports, libraryLookup, dependencyLookup, runtime: false).Cast<CompilationLibrary>())
.Concat(GetDirectReferenceCompilationLibraries());
}
var targetInfo = new TargetInfo(
_projectContext.LockFileTarget.TargetFramework.DotNetFrameworkName,
_projectContext.LockFileTarget.RuntimeIdentifier,
runtimeSignature,
_projectContext.IsPortable);
return new DependencyContext(
targetInfo,
_compilationOptions ?? CompilationOptions.Default,
compilationLibraries,
runtimeLibraries,
new RuntimeFallbacks[] { });
}
private static string GenerateRuntimeSignature(IEnumerable<LockFileTargetLibrary> runtimeExports)
{
var sha1 = SHA1.Create();
var builder = new StringBuilder();
var packages = runtimeExports
.Where(libraryExport => libraryExport.Type == "package");
var separator = "|";
foreach (var libraryExport in packages)
{
builder.Append(libraryExport.Name);
builder.Append(separator);
builder.Append(libraryExport.Version.ToString());
builder.Append(separator);
}
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString()));
builder.Clear();
foreach (var hashByte in hash)
{
builder.AppendFormat("{0:x2}", hashByte);
}
return builder.ToString();
}
private List<Dependency> GetProjectDependencies(
ProjectContext projectContext,
Dictionary<string, Dependency> dependencyLookup,
bool includeCompilationLibraries)
{
List<Dependency> dependencies = new List<Dependency>();
foreach (string dependencyName in projectContext.GetTopLevelDependencies())
{
Dependency dependency;
if (dependencyLookup.TryGetValue(dependencyName, out dependency))
{
dependencies.Add(dependency);
}
}
var referenceInfos = Enumerable.Concat(
includeCompilationLibraries && _referenceAssemblies != null ?
_referenceAssemblies :
Enumerable.Empty<ReferenceInfo>(),
_directReferences ?? Enumerable.Empty<ReferenceInfo>());
foreach (ReferenceInfo referenceInfo in referenceInfos)
{
dependencies.Add(
new Dependency(
GetReferenceLibraryName(referenceInfo),
referenceInfo.Version));
}
return dependencies;
}
private RuntimeLibrary CreateRuntimeLibrary(
string type,
string name,
string version,
string hash,
IReadOnlyList<RuntimeAssetGroup> runtimeAssemblyGroups,
IReadOnlyList<RuntimeAssetGroup> nativeLibraryGroups,
IEnumerable<ResourceAssembly> resourceAssemblies,
IEnumerable<Dependency> dependencies,
bool serviceable,
string path = null,
string hashPath = null)
{
string runtimeStoreManifestName = null;
var pkg = new PackageIdentity(name, NuGetVersion.Parse(version));
_filteredPackages?.TryGetValue(pkg, out runtimeStoreManifestName);
return new RuntimeLibrary(
type,
name: name,
version: version,
hash: hash,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: nativeLibraryGroups,
resourceAssemblies: resourceAssemblies,
dependencies: dependencies,
path: path,
hashPath: hashPath,
runtimeStoreManifestName: runtimeStoreManifestName,
serviceable: serviceable);
}
private RuntimeLibrary GetProjectRuntimeLibrary(
SingleProjectInfo projectInfo,
ProjectContext projectContext,
Dictionary<string, Dependency> dependencyLookup,
bool includeCompilationLibraries)
{
RuntimeAssetGroup[] runtimeAssemblyGroups = new[] { new RuntimeAssetGroup(string.Empty, projectInfo.OutputName) };
List<Dependency> dependencies = GetProjectDependencies(projectContext, dependencyLookup, includeCompilationLibraries);
return CreateRuntimeLibrary(
type: "project",
name: projectInfo.Name,
version: projectInfo.Version,
hash: string.Empty,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: new RuntimeAssetGroup[] { },
resourceAssemblies: CreateResourceAssemblies(projectInfo.ResourceAssemblies),
dependencies: dependencies.ToArray(),
serviceable: false);
}
private CompilationLibrary GetProjectCompilationLibrary(
SingleProjectInfo projectInfo,
ProjectContext projectContext,
Dictionary<string, Dependency> dependencyLookup,
bool includeCompilationLibraries)
{
List<Dependency> dependencies = GetProjectDependencies(projectContext, dependencyLookup, includeCompilationLibraries);
return new CompilationLibrary(
type: "project",
name: projectInfo.Name,
version: projectInfo.Version,
hash: string.Empty,
assemblies: new[] { projectInfo.OutputName },
dependencies: dependencies.ToArray(),
serviceable: false);
}
private IEnumerable<Library> GetLibraries(
IEnumerable<LockFileTargetLibrary> exports,
LockFileLookup libraryLookup,
IDictionary<string, Dependency> dependencyLookup,
bool runtime)
{
return exports.Select(export => GetLibrary(export, libraryLookup, dependencyLookup, runtime));
}
private Library GetLibrary(
LockFileTargetLibrary export,
LockFileLookup libraryLookup,
IDictionary<string, Dependency> dependencyLookup,
bool runtime)
{
var type = export.Type;
bool isPackage = type == "package";
// TEMPORARY: All packages are serviceable in RC2
// See https://github.com/dotnet/cli/issues/2569
var serviceable = isPackage;
var libraryDependencies = new HashSet<Dependency>();
foreach (PackageDependency libraryDependency in export.Dependencies)
{
Dependency dependency;
if (dependencyLookup.TryGetValue(libraryDependency.Id, out dependency))
{
libraryDependencies.Add(dependency);
}
}
string hash = string.Empty;
string path = null;
string hashPath = null;
LockFileLibrary library;
SingleProjectInfo referenceProjectInfo = null;
if (libraryLookup.TryGetLibrary(export, out library))
{
if (isPackage)
{
if (!string.IsNullOrEmpty(library.Sha512))
{
hash = "sha512-" + library.Sha512;
hashPath = _versionFolderPathResolver.GetHashFileName(export.Name, export.Version);
}
path = library.Path;
}
else if (type == "project")
{
referenceProjectInfo = GetProjectInfo(library);
}
}
if (runtime)
{
return CreateRuntimeLibrary(
type.ToLowerInvariant(),
export.Name,
export.Version.ToString(),
hash,
CreateRuntimeAssemblyGroups(export, referenceProjectInfo),
CreateNativeLibraryGroups(export),
CreateResourceAssemblyGroups(export, referenceProjectInfo),
libraryDependencies,
serviceable,
path,
hashPath);
}
else
{
IEnumerable<string> assemblies = GetCompileTimeAssemblies(export, referenceProjectInfo);
return new CompilationLibrary(
type.ToLowerInvariant(),
export.Name,
export.Version.ToString(),
hash,
assemblies,
libraryDependencies,
serviceable,
path,
hashPath);
}
}
private IReadOnlyList<RuntimeAssetGroup> CreateRuntimeAssemblyGroups(LockFileTargetLibrary targetLibrary, SingleProjectInfo referenceProjectInfo)
{
if (targetLibrary.Type == "project")
{
EnsureProjectInfo(referenceProjectInfo, targetLibrary.Name);
return new[] { new RuntimeAssetGroup(string.Empty, referenceProjectInfo.OutputName) };
}
else
{
List<RuntimeAssetGroup> assemblyGroups = new List<RuntimeAssetGroup>();
assemblyGroups.Add(
new RuntimeAssetGroup(
string.Empty,
targetLibrary.RuntimeAssemblies.FilterPlaceHolderFiles().Select(a => a.Path)));
foreach (var runtimeTargetsGroup in targetLibrary.GetRuntimeTargetsGroups("runtime"))
{
assemblyGroups.Add(
new RuntimeAssetGroup(
runtimeTargetsGroup.Key,
runtimeTargetsGroup.Select(t => t.Path)));
}
return assemblyGroups;
}
}
private IReadOnlyList<RuntimeAssetGroup> CreateNativeLibraryGroups(LockFileTargetLibrary export)
{
List<RuntimeAssetGroup> nativeGroups = new List<RuntimeAssetGroup>();
nativeGroups.Add(
new RuntimeAssetGroup(
string.Empty,
export.NativeLibraries.FilterPlaceHolderFiles().Select(a => a.Path)));
foreach (var runtimeTargetsGroup in export.GetRuntimeTargetsGroups("native"))
{
nativeGroups.Add(
new RuntimeAssetGroup(
runtimeTargetsGroup.Key,
runtimeTargetsGroup.Select(t => t.Path)));
}
return nativeGroups;
}
private IEnumerable<ResourceAssembly> CreateResourceAssemblyGroups(LockFileTargetLibrary targetLibrary, SingleProjectInfo referenceProjectInfo)
{
if (targetLibrary.Type == "project")
{
EnsureProjectInfo(referenceProjectInfo, targetLibrary.Name);
return CreateResourceAssemblies(referenceProjectInfo.ResourceAssemblies);
}
else
{
return targetLibrary.ResourceAssemblies.FilterPlaceHolderFiles().Select(CreateResourceAssembly);
}
}
private ResourceAssembly CreateResourceAssembly(LockFileItem resourceAssembly)
{
string locale;
if (!resourceAssembly.Properties.TryGetValue("locale", out locale))
{
locale = null;
}
return new ResourceAssembly(resourceAssembly.Path, locale);
}
private IEnumerable<string> GetCompileTimeAssemblies(LockFileTargetLibrary targetLibrary, SingleProjectInfo referenceProjectInfo)
{
if (targetLibrary.Type == "project")
{
EnsureProjectInfo(referenceProjectInfo, targetLibrary.Name);
return new[] { referenceProjectInfo.OutputName };
}
else
{
return targetLibrary
.CompileTimeAssemblies
.FilterPlaceHolderFiles()
.Select(libraryAsset => libraryAsset.Path);
}
}
private IEnumerable<CompilationLibrary> GetReferenceAssemblyLibraries()
{
return _referenceAssemblies
?.Select(r => new CompilationLibrary(
type: "referenceassembly",
name: GetReferenceLibraryName(r),
version: r.Version,
hash: string.Empty,
assemblies: new[] { ResolveFrameworkReferencePath(r.FullPath) },
dependencies: Enumerable.Empty<Dependency>(),
serviceable: false))
??
Enumerable.Empty<CompilationLibrary>();
}
private string ResolveFrameworkReferencePath(string fullPath)
{
// If resolved path is under ReferenceAssembliesPath store it as a relative to it
// if not, save only assembly name and try to find it somehow later
if (!string.IsNullOrEmpty(_referenceAssembliesPath) &&
fullPath?.StartsWith(_referenceAssembliesPath) == true)
{
return fullPath.Substring(_referenceAssembliesPath.Length);
}
return Path.GetFileName(fullPath);
}
private IEnumerable<RuntimeLibrary> GetDirectReferenceRuntimeLibraries()
{
return _directReferences
?.Select(r => CreateRuntimeLibrary(
type: "reference",
name: GetReferenceLibraryName(r),
version: r.Version,
hash: string.Empty,
runtimeAssemblyGroups: new[] { new RuntimeAssetGroup(string.Empty, r.FileName) },
nativeLibraryGroups: new RuntimeAssetGroup[] { },
resourceAssemblies: CreateResourceAssemblies(r.ResourceAssemblies),
dependencies: Enumerable.Empty<Dependency>(),
serviceable: false))
??
Enumerable.Empty<RuntimeLibrary>();
}
private IEnumerable<CompilationLibrary> GetDirectReferenceCompilationLibraries()
{
return _directReferences
?.Select(r => new CompilationLibrary(
type: "reference",
name: GetReferenceLibraryName(r),
version: r.Version,
hash: string.Empty,
assemblies: new[] { r.FileName },
dependencies: Enumerable.Empty<Dependency>(),
serviceable: false))
??
Enumerable.Empty<CompilationLibrary>();
}
private string GetReferenceLibraryName(ReferenceInfo reference)
{
if (!ReferenceLibraryNames.TryGetValue(reference, out string name))
{
// Reference names can conflict with PackageReference names, so
// ensure that the Reference names are unique when creating libraries
name = GetUniqueReferenceName(reference.Name);
ReferenceLibraryNames.Add(reference, name);
UsedLibraryNames.Add(name);
}
return name;
}
private string GetUniqueReferenceName(string name)
{
if (UsedLibraryNames.Contains(name))
{
string startingName = $"{name}.Reference";
name = startingName;
int suffix = 1;
while (UsedLibraryNames.Contains(name))
{
name = $"{startingName}{suffix++}";
}
}
return name;
}
private static IEnumerable<ResourceAssembly> CreateResourceAssemblies(IEnumerable<ResourceAssemblyInfo> resourceAssemblyInfos)
{
return resourceAssemblyInfos
.Select(r => new ResourceAssembly(r.RelativePath, r.Culture));
}
private static void EnsureProjectInfo(SingleProjectInfo referenceProjectInfo, string libraryName)
{
if (referenceProjectInfo == null)
{
throw new BuildErrorException(Strings.CannotFindProjectInfo, libraryName);
}
}
private SingleProjectInfo GetProjectInfo(LockFileLibrary library)
{
string projectPath = library.MSBuildProject;
if (string.IsNullOrEmpty(projectPath))
{
throw new BuildErrorException(Strings.CannotFindProjectInfo, library.Name);
}
string mainProjectDirectory = Path.GetDirectoryName(_mainProjectInfo.ProjectPath);
string fullProjectPath = Path.GetFullPath(Path.Combine(mainProjectDirectory, projectPath));
SingleProjectInfo referenceProjectInfo = null;
if (_referenceProjectInfos?.TryGetValue(fullProjectPath, out referenceProjectInfo) != true ||
referenceProjectInfo == null)
{
throw new BuildErrorException(Strings.CannotFindProjectInfo, fullProjectPath);
}
return referenceProjectInfo;
}
private static string EnsureTrailingSlash(string path)
{
return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar);
}
private static string EnsureTrailingCharacter(string path, char trailingCharacter)
{
// if the path is empty, we want to return the original string instead of a single trailing character.
if (string.IsNullOrEmpty(path) || path[path.Length - 1] == trailingCharacter)
{
return path;
}
return path + trailingCharacter;
}
}
}