-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathLegacyPackageReferenceProject.cs
More file actions
744 lines (621 loc) · 34 KB
/
LegacyPackageReferenceProject.cs
File metadata and controls
744 lines (621 loc) · 34 KB
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Threading;
using NuGet.Commands;
using NuGet.Commands.Restore;
using NuGet.Commands.Restore.Utility;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.PackageManagement.VisualStudio.Projects;
using NuGet.PackageManagement.VisualStudio.Utility;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectManagement;
using NuGet.ProjectModel;
using NuGet.RuntimeModel;
using NuGet.Shared;
using NuGet.Versioning;
using NuGet.VisualStudio;
using Task = System.Threading.Tasks.Task;
namespace NuGet.PackageManagement.VisualStudio
{
/// <summary>
/// An implementation of <see cref="NuGetProject"/> that interfaces with VS project APIs to coordinate
/// packages in a legacy CSProj with package references.
/// </summary>
public sealed class LegacyPackageReferenceProject : PackageReferenceProject<Dictionary<string, ProjectInstalledPackage>, KeyValuePair<string, ProjectInstalledPackage>>
{
private readonly IVsProjectAdapter _vsProjectAdapter;
private readonly IVsProjectThreadingService _threadingService;
private readonly bool _usePackageSpecFactory;
private readonly ILegacyPackageReferenceProjectServices _projectServices;
public NuGetFramework TargetFramework { get; }
public LegacyPackageReferenceProject(
IVsProjectAdapter vsProjectAdapter,
string projectId,
ILegacyPackageReferenceProjectServices projectServices,
IVsProjectThreadingService threadingService,
bool usePackageSpecFactory)
: base(vsProjectAdapter.ProjectName,
vsProjectAdapter.UniqueName,
vsProjectAdapter.FullProjectPath)
{
Assumes.Present(vsProjectAdapter);
Assumes.NotNullOrEmpty(projectId);
Assumes.Present(projectServices);
Assumes.Present(threadingService);
_vsProjectAdapter = vsProjectAdapter;
_threadingService = threadingService;
ProjectStyle = ProjectStyle.PackageReference;
InternalMetadata.Add(NuGetProjectMetadataKeys.Name, ProjectName);
InternalMetadata.Add(NuGetProjectMetadataKeys.UniqueName, ProjectUniqueName);
InternalMetadata.Add(NuGetProjectMetadataKeys.FullPath, ProjectFullPath);
InternalMetadata.Add(NuGetProjectMetadataKeys.ProjectId, projectId);
ProjectServices = projectServices;
_projectServices = projectServices;
_usePackageSpecFactory = usePackageSpecFactory;
}
public LegacyPackageReferenceProject(
IVsProjectAdapter vsProjectAdapter,
string projectId,
ILegacyPackageReferenceProjectServices projectServices,
IVsProjectThreadingService threadingService,
NuGetFramework targetFramework,
bool usePackageSpecFactory)
: this(vsProjectAdapter,
projectId,
projectServices,
threadingService,
usePackageSpecFactory)
{
Assumes.NotNull(targetFramework);
TargetFramework = targetFramework;
}
#region BuildIntegratedNuGetProject
public override async Task<string> GetCacheFilePathAsync()
{
return GetCacheFilePath(await GetMSBuildProjectExtensionsPathAsync());
}
private static string GetCacheFilePath(string msbuildProjectExtensionsPath)
{
return NoOpRestoreUtilities.GetProjectCacheFilePath(cacheRoot: msbuildProjectExtensionsPath);
}
protected override async Task<string> GetAssetsFilePathAsync(bool shouldThrow)
{
var msbuildProjectExtensionsPath = await GetMSBuildProjectExtensionsPathAsync(shouldThrow);
if (msbuildProjectExtensionsPath == null)
{
return null;
}
return Path.Combine(msbuildProjectExtensionsPath, LockFileFormat.AssetsFileName);
}
#endregion BuildIntegratedNuGetProject
#region IDependencyGraphProject
public override string MSBuildProjectPath => ProjectFullPath;
public override async Task<(IReadOnlyList<PackageSpec> dgSpecs, IReadOnlyList<IAssetsLogMessage> additionalMessages)> GetPackageSpecsAndAdditionalMessagesAsync(DependencyGraphCacheContext context)
{
PackageSpec packageSpec;
if (context == null || !context.PackageSpecCache.TryGetValue(MSBuildProjectPath, out packageSpec))
{
packageSpec = await GetPackageSpecAsync(context.Settings);
if (packageSpec == null)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, Strings.ProjectNotLoaded_RestoreFailed, ProjectName));
}
context?.PackageSpecCache.Add(ProjectFullPath, packageSpec);
}
return (new[] { packageSpec }, null);
}
private IReadOnlyDictionary<string, CentralPackageVersion> GetCentralPackageVersions()
{
ThreadHelper.ThrowIfNotOnUIThread();
IEnumerable<(string PackageId, string Version)> packageVersions =
_vsProjectAdapter.GetBuildItemInformation(ProjectItems.PackageVersion, ProjectBuildProperties.Version)
.Select(item => (PackageId: item.ItemId, Version: item.ItemMetadata.FirstOrDefault()));
return packageVersions
.Select(item => ToCentralPackageVersion(item.PackageId, item.Version))
.Distinct(CentralPackageVersionNameComparer.Default)
.ToDictionary(cpv => cpv.Name, StringComparer.OrdinalIgnoreCase);
}
private CentralPackageVersion ToCentralPackageVersion(string packageId, string version)
{
if (string.IsNullOrEmpty(packageId))
{
throw new ArgumentNullException(nameof(packageId));
}
if (string.IsNullOrEmpty(version))
{
return new CentralPackageVersion(packageId, VersionRange.All);
}
return new CentralPackageVersion(packageId, VersionRange.Parse(version));
}
private IReadOnlyDictionary<string, PrunePackageReference> GetPackagesToPrune()
{
ThreadHelper.ThrowIfNotOnUIThread();
IEnumerable<(string PackageId, string Version)> packageVersions =
_vsProjectAdapter.GetBuildItemInformation(ProjectItems.PrunePackageReference, ProjectBuildProperties.Version)
.Select(item => (PackageId: item.ItemId, Version: item.ItemMetadata.FirstOrDefault()));
return packageVersions
.Select(item => PrunePackageReference.Create(item.PackageId, item.Version))
.ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
}
private RestoreAuditProperties GetRestoreAuditProperties()
{
ThreadHelper.ThrowIfNotOnUIThread();
string enableAudit = _vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.NuGetAudit);
string auditLevel = _vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.NuGetAuditLevel);
string auditMode = _vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.NuGetAuditMode);
HashSet<string> suppressedAdvisories = GetSuppressedAdvisories();
return new RestoreAuditProperties()
{
EnableAudit = enableAudit,
AuditLevel = auditLevel,
AuditMode = auditMode,
SuppressedAdvisories = suppressedAdvisories,
};
}
private HashSet<string> GetSuppressedAdvisories()
{
ThreadHelper.ThrowIfNotOnUIThread();
IEnumerable<(string ItemId, string[] ItemMetadata)> buildItems = _vsProjectAdapter.GetBuildItemInformation(ProjectItems.NuGetAuditSuppress);
if (buildItems is null)
{
return null;
}
else if (buildItems is ICollection<(string, string[])> collection)
{
if (collection.Count == 0) return null;
var suppressedAdvisories = new HashSet<string>(collection.Count, StringComparer.OrdinalIgnoreCase);
foreach ((string itemId, _) in buildItems.NoAllocEnumerate())
{
suppressedAdvisories.Add(itemId);
}
return suppressedAdvisories;
}
else
{
var suppressedAdvisories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach ((string itemId, _) in buildItems.NoAllocEnumerate())
{
suppressedAdvisories.Add(itemId);
}
return suppressedAdvisories.Count == 0 ? null : suppressedAdvisories;
}
}
#endregion
#region NuGetProject
public override async Task<bool> InstallPackageAsync(
string packageId,
VersionRange range,
INuGetProjectContext _,
BuildIntegratedInstallationContext context,
CancellationToken token)
{
if (string.IsNullOrEmpty(packageId)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Argument_Cannot_Be_Null_Or_Empty, nameof(packageId)));
if (range == null) throw new ArgumentNullException(nameof(range));
if (context == null) throw new ArgumentNullException(nameof(context));
var dependency = new LibraryDependency()
{
LibraryRange = new LibraryRange(
name: packageId,
versionRange: range,
typeConstraint: LibraryDependencyTarget.Package),
SuppressParent = context.SuppressParent,
IncludeType = context.IncludeType
};
await ProjectServices.References.AddOrUpdatePackageReferenceAsync(dependency, token);
return true;
}
public override async Task AddFileToProjectAsync(string filePath)
{
await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();
EnvDTEProjectUtility.EnsureCheckedOutIfExists(_vsProjectAdapter.Project, _vsProjectAdapter.ProjectDirectory, filePath);
var isFileExistsInProject = await EnvDTEProjectUtility.ContainsFileAsync(_vsProjectAdapter.Project, filePath);
if (!isFileExistsInProject)
{
await AddProjectItemAsync(filePath);
}
}
private async Task AddProjectItemAsync(string filePath)
{
var folderPath = Path.GetDirectoryName(filePath);
var fullPath = filePath;
string projectDirectory = _vsProjectAdapter.ProjectDirectory;
if (filePath.Contains(projectDirectory))
{
// folderPath should always be relative to ProjectDirectory so if filePath already contains
// ProjectDirectory then get a relative path and construct folderPath to get the appropriate
// ProjectItems from dte where you have to add this file.
var relativeLockFilePath = FileSystemUtility.GetRelativePath(projectDirectory, filePath);
folderPath = Path.GetDirectoryName(relativeLockFilePath);
}
else
{
// get the fullPath wrt ProjectDirectory
fullPath = FileSystemUtility.GetFullPath(projectDirectory, filePath);
}
var container = await EnvDTEProjectUtility.GetProjectItemsAsync(_vsProjectAdapter.Project, folderPath, createIfNotExists: true);
await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();
container.AddFromFileCopy(fullPath);
}
public override Task<bool> UninstallPackageAsync(
PackageIdentity packageIdentity, INuGetProjectContext _, CancellationToken token)
{
return UninstallPackageAsync(packageIdentity.Id);
}
private async Task<bool> UninstallPackageAsync(string id)
{
await ProjectServices.References.RemovePackageReferenceAsync(id);
return true;
}
#endregion
private async Task<string> GetMSBuildProjectExtensionsPathAsync(bool shouldThrow = true)
{
await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();
var msbuildProjectExtensionsPath = _vsProjectAdapter.GetMSBuildProjectExtensionsPath();
if (string.IsNullOrEmpty(msbuildProjectExtensionsPath))
{
if (shouldThrow)
{
throw new InvalidDataException(string.Format(
CultureInfo.CurrentCulture,
Strings.MSBuildPropertyNotFound,
ProjectBuildProperties.MSBuildProjectExtensionsPath,
_vsProjectAdapter.ProjectDirectory));
}
return null;
}
return msbuildProjectExtensionsPath;
}
[Obsolete("New properties should use IVsProjectBuildProperties.GetPropertyValue instead. Ideally we should migrate existing properties to stop using DTE as well.")]
private static string GetPropertySafe(IVsProjectBuildProperties projectBuildProperties, string propertyName)
{
ThreadHelper.ThrowIfNotOnUIThread();
var value = projectBuildProperties.GetPropertyValueWithDteFallback(propertyName);
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
return value;
}
private string GetPackagesPath(ISettings settings)
{
ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
var packagePath = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RestorePackagesPath);
#pragma warning restore CS0618 // Type or member is obsolete
if (string.IsNullOrWhiteSpace(packagePath))
{
return SettingsUtility.GetGlobalPackagesFolder(settings);
}
return UriUtility.GetAbsolutePathFromFile(ProjectFullPath, packagePath);
}
private IList<PackageSource> GetSources(ISettings settings)
{
ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
var sources = MSBuildStringUtility.Split(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RestoreSources)).AsEnumerable();
#pragma warning restore CS0618 // Type or member is obsolete
if (ShouldReadFromSettings(sources))
{
sources = SettingsUtility.GetEnabledSources(settings).Select(e => e.Source);
}
else
{
sources = VSRestoreSettingsUtilities.HandleClear(sources);
}
// Add additional sources
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
sources = sources.Concat(MSBuildStringUtility.Split(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RestoreAdditionalProjectSources)));
#pragma warning restore CS0618 // Type or member is obsolete
return sources.Select(e => new PackageSource(UriUtility.GetAbsolutePathFromFile(ProjectFullPath, e))).ToList();
}
private IList<string> GetFallbackFolders(ISettings settings)
{
ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
var fallbackFolders = MSBuildStringUtility.Split(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RestoreFallbackFolders)).AsEnumerable();
#pragma warning restore CS0618 // Type or member is obsolete
if (ShouldReadFromSettings(fallbackFolders))
{
fallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings);
}
else
{
fallbackFolders = VSRestoreSettingsUtilities.HandleClear(fallbackFolders);
}
// Add additional fallback folders
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
fallbackFolders = fallbackFolders.Concat(MSBuildStringUtility.Split(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RestoreAdditionalProjectFallbackFolders)));
#pragma warning restore CS0618 // Type or member is obsolete
return fallbackFolders.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectFullPath, e)).ToList();
}
private static bool ShouldReadFromSettings(IEnumerable<string> values)
{
return !values.Any();
}
private IList<string> GetConfigFilePaths(ISettings settings)
{
return settings.GetConfigFilePaths();
}
/// <summary>
/// Emulates a JSON deserialization from project.json to PackageSpec in a post-project.json world
/// </summary>
private async Task<PackageSpec> GetPackageSpecAsync(ISettings settings)
{
if (_usePackageSpecFactory)
{
return await GetPackageSpecWithFactoryAsync(settings);
}
else
{
return await GetPackageSpecClassicAsync(settings);
}
}
private async Task<PackageSpec> GetPackageSpecClassicAsync(ISettings settings)
{
await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();
var projectReferences = await ProjectServices
.ReferencesReader
.GetProjectReferencesAsync(NullLogger.Instance, CancellationToken.None);
var targetFramework = _vsProjectAdapter.GetTargetFramework();
var packageReferences = (await ProjectServices
.ReferencesReader
.GetPackageReferencesAsync(targetFramework, CancellationToken.None))
.ToImmutableArray();
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
var packageTargetFallback = MSBuildStringUtility.Split(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.PackageTargetFallback))
.Select(NuGetFramework.Parse)
.ToList();
var assetTargetFallbackList = MSBuildStringUtility.Split(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.AssetTargetFallback))
.Select(NuGetFramework.Parse)
.ToList();
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
bool isCpvmEnabled = MSBuildStringUtility.IsTrue(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.ManagePackageVersionsCentrally));
#pragma warning restore CS0618 // Type or member is obsolete
IReadOnlyDictionary<string, CentralPackageVersion> centralPackageVersions = null;
if (isCpvmEnabled)
{
// Add the central versionString information and merge the information to the package reference dependencies
centralPackageVersions = GetCentralPackageVersions();
packageReferences = ApplyCentralVersionInformation(packageReferences, centralPackageVersions);
}
IReadOnlyDictionary<string, PrunePackageReference> packagesToPrune = MSBuildStringUtility.IsTrue(_vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.RestoreEnablePackagePruning))
? GetPackagesToPrune()
: ImmutableDictionary<string, PrunePackageReference>.Empty;
// Get fallback settings
(targetFramework, var imports, var assetTargetFallback, var warn) = AssetTargetFallbackUtility.GetFallbackFrameworkInformation(targetFramework, packageTargetFallback, assetTargetFallbackList);
var projectTfi = new TargetFrameworkInformation
{
AssetTargetFallback = assetTargetFallback,
CentralPackageVersions = centralPackageVersions,
Dependencies = packageReferences,
Imports = imports,
FrameworkName = targetFramework,
Warn = warn,
PackagesToPrune = packagesToPrune,
};
// Build up runtime information.
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
var runtimes = GetRuntimeIdentifiers(
GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RuntimeIdentifier),
GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RuntimeIdentifiers));
var supports = GetRuntimeSupports(GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RuntimeSupports));
#pragma warning restore CS0618 // Type or member is obsolete
var runtimeGraph = new RuntimeGraph(runtimes, supports);
// In legacy CSProj, we only have one target framework per project
var tfis = new TargetFrameworkInformation[] { projectTfi };
var projectName = ProjectName ?? ProjectUniqueName;
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
string specifiedPackageId = _vsProjectAdapter.BuildProperties.GetPropertyValueWithDteFallback(ProjectBuildProperties.PackageId);
#pragma warning restore CS0618 // Type or member is obsolete
if (!string.IsNullOrWhiteSpace(specifiedPackageId))
{
projectName = specifiedPackageId;
}
else
{
#pragma warning disable CS0618 // Type or member is obsolete
// Need to validate no project systems get this property via DTE, and if so, switch to GetPropertyValue
string specifiedAssemblyName = _vsProjectAdapter.BuildProperties.GetPropertyValueWithDteFallback(ProjectBuildProperties.AssemblyName);
#pragma warning restore CS0618 // Type or member is obsolete
if (!string.IsNullOrWhiteSpace(specifiedAssemblyName))
{
projectName = specifiedAssemblyName;
}
}
RestoreAuditProperties auditProperties = GetRestoreAuditProperties();
var msbuildProjectExtensionsPath = await GetMSBuildProjectExtensionsPathAsync();
#pragma warning disable CS0618 // Type or member is obsolete
// Do not add new properties here. Use BuildProperties.GetPropertyValue instead, without DTE fallback.
string treatWarningsAsErrors = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.TreatWarningsAsErrors);
string noWarn = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.NoWarn);
string warningsAsErrors = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.WarningsAsErrors);
string warningsNotAsErrors = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.WarningsNotAsErrors);
string restorePackagesWithLockFile = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RestorePackagesWithLockFile);
string nugetLockFilePath = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.NuGetLockFilePath);
string restoreLockedMode = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.RestoreLockedMode);
string centralPackageVersionOverrideDisabled = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.CentralPackageVersionOverrideEnabled);
string centralPackageTransitivePinningEnabled = GetPropertySafe(_vsProjectAdapter.BuildProperties, ProjectBuildProperties.CentralPackageTransitivePinningEnabled);
// Do not add new properties here. Use BuildProperties.GetPropertyValue instead, without DTE fallback.
#pragma warning restore CS0618 // Type or member is obsolete
string skdAnalysisLevelString = _vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.SdkAnalysisLevel);
string usingNetSdk = _vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.UsingMicrosoftNETSdk);
return new PackageSpec(tfis)
{
Name = projectName,
Version = new NuGetVersion(_vsProjectAdapter.Version),
FilePath = ProjectFullPath,
RuntimeGraph = runtimeGraph,
RestoreMetadata = new ProjectRestoreMetadata
{
ProjectStyle = ProjectStyle.PackageReference,
OutputPath = msbuildProjectExtensionsPath,
ProjectPath = ProjectFullPath,
ProjectName = projectName,
ProjectUniqueName = ProjectFullPath,
OriginalTargetFrameworks = tfis
.Select(tfi => tfi.FrameworkName.GetShortFolderName())
.ToList(),
TargetFrameworks = new List<ProjectRestoreMetadataFrameworkInfo>
{
new ProjectRestoreMetadataFrameworkInfo(tfis[0].FrameworkName)
{
ProjectReferences = projectReferences?.ToList()
}
},
SkipContentFileWrite = true,
CacheFilePath = GetCacheFilePath(msbuildProjectExtensionsPath),
PackagesPath = GetPackagesPath(settings),
Sources = GetSources(settings),
FallbackFolders = GetFallbackFolders(settings),
ConfigFilePaths = GetConfigFilePaths(settings),
ProjectWideWarningProperties = WarningProperties.GetWarningProperties(
treatWarningsAsErrors,
warningsAsErrors,
noWarn,
warningsNotAsErrors),
RestoreLockProperties = new RestoreLockProperties(
restorePackagesWithLockFile,
nugetLockFilePath,
MSBuildStringUtility.IsTrue(restoreLockedMode)),
CentralPackageVersionsEnabled = isCpvmEnabled,
CentralPackageVersionOverrideDisabled = centralPackageVersionOverrideDisabled.EqualsFalse(),
CentralPackageFloatingVersionsEnabled = MSBuildStringUtility.IsTrue(_vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.CentralPackageFloatingVersionsEnabled)),
CentralPackageTransitivePinningEnabled = MSBuildStringUtility.IsTrue(centralPackageTransitivePinningEnabled),
RestoreAuditProperties = auditProperties,
SdkAnalysisLevel = MSBuildRestoreUtility.GetSdkAnalysisLevel(skdAnalysisLevelString),
UsingMicrosoftNETSdk = MSBuildRestoreUtility.GetUsingMicrosoftNETSdk(usingNetSdk),
UseLegacyDependencyResolver = MSBuildStringUtility.IsTrue(_vsProjectAdapter.BuildProperties.GetPropertyValue(ProjectBuildProperties.RestoreUseLegacyDependencyResolver)),
}
};
}
private async Task<PackageSpec> GetPackageSpecWithFactoryAsync(ISettings settings)
{
await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();
IProject project = new LegacyProjectAdapter(_vsProjectAdapter, _projectServices.Project4);
PackageSpec packageSpec = PackageSpecFactory.GetPackageSpec(project, settings);
return packageSpec;
}
internal static ImmutableArray<LibraryDependency> ApplyCentralVersionInformation(ImmutableArray<LibraryDependency> packageReferences, IReadOnlyDictionary<string, CentralPackageVersion> centralPackageVersions)
{
if (packageReferences.IsDefault)
{
throw new ArgumentNullException(nameof(packageReferences));
}
if (centralPackageVersions == null)
{
throw new ArgumentNullException(nameof(centralPackageVersions));
}
if (centralPackageVersions.Count == 0)
{
return packageReferences;
}
LibraryDependency[] result = new LibraryDependency[packageReferences.Length];
for (int i = 0; i < packageReferences.Length; i++)
{
LibraryDependency d = packageReferences[i];
if (!d.AutoReferenced && d.LibraryRange.VersionRange == null)
{
var libraryRange = d.LibraryRange;
var versionCentrallyManaged = d.VersionCentrallyManaged;
if (d.VersionOverride != null)
{
libraryRange = new LibraryRange(d.LibraryRange) { VersionRange = d.VersionOverride };
}
else
{
if (centralPackageVersions.TryGetValue(d.Name, out CentralPackageVersion centralPackageVersion))
{
libraryRange = new LibraryRange(d.LibraryRange) { VersionRange = centralPackageVersion.VersionRange };
}
versionCentrallyManaged = true;
}
d = new LibraryDependency(d)
{
LibraryRange = libraryRange,
VersionCentrallyManaged = versionCentrallyManaged
};
}
result[i] = d;
}
return ImmutableCollectionsMarshal.AsImmutableArray(result);
}
internal static IEnumerable<RuntimeDescription> GetRuntimeIdentifiers(string unparsedRuntimeIdentifer, string unparsedRuntimeIdentifers)
{
var runtimes = Enumerable.Empty<string>();
if (unparsedRuntimeIdentifer != null)
{
runtimes = runtimes.Concat(new[] { unparsedRuntimeIdentifer });
}
if (unparsedRuntimeIdentifers != null)
{
runtimes = runtimes.Concat(unparsedRuntimeIdentifers.Split(';'));
}
runtimes = runtimes
.Select(x => x.Trim())
.Distinct(StringComparer.Ordinal)
.Where(x => !string.IsNullOrEmpty(x));
return runtimes
.Select(runtime => new RuntimeDescription(runtime));
}
internal static IEnumerable<CompatibilityProfile> GetRuntimeSupports(string unparsedRuntimeSupports)
{
if (unparsedRuntimeSupports == null)
{
return Enumerable.Empty<CompatibilityProfile>();
}
return unparsedRuntimeSupports
.Split(';')
.Select(x => x.Trim())
.Where(x => !string.IsNullOrEmpty(x))
.Select(support => new CompatibilityProfile(support));
}
/// <inheritdoc/>
protected override Task<PackageSpec> GetPackageSpecAsync(CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
return GetPackageSpecAsync(NullSettings.Instance);
}
protected override IEnumerable<PackageReference> ResolvedInstalledPackagesList(IEnumerable<LibraryDependency> libraries, NuGetFramework targetFramework, IList<LockFileTarget> targets, Dictionary<string, ProjectInstalledPackage> installedPackages)
{
return GetPackageReferences(libraries, targetFramework, installedPackages, targets);
}
protected override IReadOnlyList<PackageReference> ResolvedTransitivePackagesList(NuGetFramework targetFramework, IList<LockFileTarget> targets, Dictionary<string, ProjectInstalledPackage> installedPackages, Dictionary<string, ProjectInstalledPackage> transitivePackages)
{
return GetTransitivePackageReferences(targetFramework, installedPackages, transitivePackages, targets);
}
/// <inheritdoc/>
protected override Dictionary<string, ProjectInstalledPackage> GetCollectionCopy(Dictionary<string, ProjectInstalledPackage> collection) => new(collection);
public override Task<bool> UninstallPackageAsync(string packageId, BuildIntegratedInstallationContext _, CancellationToken token)
{
if (string.IsNullOrEmpty(packageId)) throw new ArgumentException(string.Format(Strings.Argument_Cannot_Be_Null_Or_Empty, nameof(packageId)));
return UninstallPackageAsync(packageId);
}
}
}