forked from NuGet/NuGet.Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestoreCommand.cs
1047 lines (880 loc) · 43.4 KB
/
RestoreCommand.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
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Remoting;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.PackageManagement;
using NuGet.PackageManagement.Utility;
using NuGet.Packaging;
using NuGet.Packaging.PackageExtraction;
using NuGet.Packaging.Signing;
using NuGet.ProjectManagement;
using NuGet.ProjectModel;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Shared;
namespace NuGet.CommandLine
{
[Command(typeof(NuGetCommand), "restore", "RestoreCommandDescription",
MinArgs = 0, MaxArgs = 1, UsageSummaryResourceName = "RestoreCommandUsageSummary",
UsageDescriptionResourceName = "RestoreCommandUsageDescription",
UsageExampleResourceName = "RestoreCommandUsageExamples")]
public class RestoreCommand : DownloadCommandBase
{
[Option(typeof(NuGetCommand), "RestoreCommandRequireConsent")]
public bool RequireConsent { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandP2PTimeOut")]
public int Project2ProjectTimeOut { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandPackagesDirectory", AltName = "OutputDirectory")]
public string PackagesDirectory { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandSolutionDirectory")]
public string SolutionDirectory { get; set; }
[Option(typeof(NuGetCommand), "CommandMSBuildVersion")]
public string MSBuildVersion { get; set; }
[Option(typeof(NuGetCommand), "CommandMSBuildPath")]
public string MSBuildPath { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandRecursive")]
public bool Recursive { get; set; }
[Option(typeof(NuGetCommand), "ForceRestoreCommand")]
public bool Force { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandUseLockFile")]
public bool UseLockFile { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandLockedMode")]
public bool LockedMode { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandLockFilePath")]
public string LockFilePath { get; set; }
[Option(typeof(NuGetCommand), "RestoreCommandForceEvaluate")]
public bool ForceEvaluate { get; set; }
[ImportingConstructor]
public RestoreCommand()
{
}
// The directory that contains msbuild
private Lazy<MsBuildToolset> _msbuildDirectory;
private Lazy<MsBuildToolset> MsBuildDirectory
{
get
{
if (_msbuildDirectory == null)
{
_msbuildDirectory = MsBuildUtility.GetMsBuildDirectoryFromMsBuildPath(MSBuildPath, MSBuildVersion, Console);
}
return _msbuildDirectory;
}
}
public override async Task ExecuteCommandAsync()
{
if (DisableParallelProcessing)
{
HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
}
CalculateEffectivePackageSaveMode();
var restoreSummaries = new List<RestoreSummary>();
if (!string.IsNullOrEmpty(SolutionDirectory))
{
SolutionDirectory = Path.GetFullPath(SolutionDirectory);
}
var restoreInputs = await DetermineRestoreInputsAsync();
var hasPackagesConfigFiles = restoreInputs.PackagesConfigFiles.Count > 0;
var hasProjectJsonOrPackageReferences = restoreInputs.RestoreV3Context.Inputs.Any();
if (!hasPackagesConfigFiles && !hasProjectJsonOrPackageReferences)
{
Console.LogMinimal(LocalizedResourceManager.GetString(restoreInputs.RestoringWithSolutionFile
? "SolutionRestoreCommandNoPackagesConfigOrProjectJson"
: "ProjectRestoreCommandNoPackagesConfigOrProjectJson"));
return;
}
// packages.config
if (hasPackagesConfigFiles)
{
var v2RestoreResults = await PerformNuGetV2RestoreAsync(restoreInputs);
restoreSummaries.AddRange(v2RestoreResults);
foreach (var restoreResult in v2RestoreResults.Where(r => !r.Success))
{
restoreResult
.Errors
.Where(l => l.Level == LogLevel.Warning)
.ForEach(l => Console.LogWarning(l.FormatWithCode()));
}
}
// project.json and PackageReference
if (hasProjectJsonOrPackageReferences)
{
// Read the settings outside of parallel loops.
ReadSettings(restoreInputs);
// Check if we can restore based on the nuget.config settings
CheckRequireConsent();
using (var cacheContext = new SourceCacheContext())
{
cacheContext.NoCache = NoCache || NoHttpCache;
cacheContext.DirectDownload = DirectDownload;
var restoreContext = restoreInputs.RestoreV3Context;
var providerCache = new RestoreCommandProvidersCache();
// Add restore args to the restore context
restoreContext.CacheContext = cacheContext;
restoreContext.DisableParallel = DisableParallelProcessing;
restoreContext.AllowNoOp = !Force; // if force, no-op is not allowed
restoreContext.ConfigFile = ConfigFile;
restoreContext.MachineWideSettings = MachineWideSettings;
restoreContext.Log = Console;
restoreContext.CachingSourceProvider = GetSourceRepositoryProvider();
restoreContext.RestoreForceEvaluate = ForceEvaluate;
var packageSaveMode = EffectivePackageSaveMode;
if (packageSaveMode != Packaging.PackageSaveMode.None)
{
restoreContext.PackageSaveMode = EffectivePackageSaveMode;
}
// Providers
// Use the settings loaded above in ReadSettings(restoreInputs)
if (restoreInputs.ProjectReferenceLookup.Restore.Count > 0)
{
// Remove input list, everything has been loaded already
restoreContext.Inputs.Clear();
restoreContext.PreLoadedRequestProviders.Add(new DependencyGraphSpecRequestProvider(
providerCache,
restoreInputs.ProjectReferenceLookup));
}
else
{
// Allow an external .dg file
restoreContext.RequestProviders.Add(new DependencyGraphFileRequestProvider(providerCache));
}
// Run restore
var v3Summaries = await RestoreRunner.RunAsync(restoreContext);
restoreSummaries.AddRange(v3Summaries);
}
}
// Summaries
RestoreSummary.Log(Console, restoreSummaries, logErrors: true);
if (restoreSummaries.Any(x => !x.Success))
{
throw new ExitCodeException(exitCode: 1);
}
}
private static CachingSourceProvider _sourceProvider;
private CachingSourceProvider GetSourceRepositoryProvider()
{
if (_sourceProvider == null)
{
_sourceProvider = new CachingSourceProvider(SourceProvider);
}
return _sourceProvider;
}
private bool IsSolutionRestore(PackageRestoreInputs packageRestoreInputs)
{
return !string.IsNullOrEmpty(SolutionDirectory) || packageRestoreInputs.RestoringWithSolutionFile;
}
private string GetSolutionDirectory(PackageRestoreInputs packageRestoreInputs)
{
var solutionDirectory = packageRestoreInputs.RestoringWithSolutionFile ?
packageRestoreInputs.DirectoryOfSolutionFile :
SolutionDirectory;
return solutionDirectory != null ? PathUtility.EnsureTrailingSlash(solutionDirectory) : null;
}
private void ReadSettings(PackageRestoreInputs packageRestoreInputs)
{
if (IsSolutionRestore(packageRestoreInputs))
{
var solutionDirectory = GetSolutionDirectory(packageRestoreInputs);
// Read the solution-level settings
var solutionSettingsFile = Path.Combine(
solutionDirectory,
NuGetConstants.NuGetSolutionSettingsFolder);
if (ConfigFile != null)
{
ConfigFile = Path.GetFullPath(ConfigFile);
}
Settings = Configuration.Settings.LoadDefaultSettings(
solutionSettingsFile,
configFileName: ConfigFile,
machineWideSettings: MachineWideSettings);
// Recreate the source provider and credential provider
SourceProvider = PackageSourceBuilder.CreateSourceProvider(Settings);
SetDefaultCredentialProvider();
}
}
protected override void SetDefaultCredentialProvider()
{
SetDefaultCredentialProvider(MsBuildDirectory);
}
private async Task<IReadOnlyList<RestoreSummary>> PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
{
ReadSettings(packageRestoreInputs);
var packagesFolderPath = Path.GetFullPath(GetPackagesFolder(packageRestoreInputs));
var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);
// EffectivePackageSaveMode is None when -PackageSaveMode is not provided by the user. None is treated as
// Defaultv3 for V3 restore and should be treated as Defaultv2 for V2 restore. This is the case in the
// actual V2 restore flow and should match in this preliminary missing packages check.
var packageSaveMode = EffectivePackageSaveMode == Packaging.PackageSaveMode.None ?
Packaging.PackageSaveMode.Defaultv2 :
EffectivePackageSaveMode;
List<PackageRestoreData> packageRestoreData = new();
bool areAnyPackagesMissing = false;
if (packageRestoreInputs.RestoringWithSolutionFile)
{
Dictionary<string, string> configToProjectPath = GetPackagesConfigToProjectPath(packageRestoreInputs);
Dictionary<PackageReference, List<string>> packageReferenceToProjects = new(PackageReferenceComparer.Instance);
foreach (string configFile in packageRestoreInputs.PackagesConfigFiles)
{
foreach (PackageReference packageReference in GetInstalledPackageReferences(configFile))
{
if (configToProjectPath.TryGetValue(configFile, out string projectPath))
{
projectPath = configFile;
}
if (!packageReferenceToProjects.TryGetValue(packageReference, out List<string> value))
{
value ??= new();
packageReferenceToProjects.Add(packageReference, value);
}
value.Add(projectPath);
}
}
foreach (KeyValuePair<PackageReference, List<string>> package in packageReferenceToProjects)
{
var exists = nuGetPackageManager.PackageExistsInPackagesFolder(package.Key.PackageIdentity, packageSaveMode);
packageRestoreData.Add(new PackageRestoreData(package.Key, package.Value, !exists));
areAnyPackagesMissing |= !exists;
}
}
else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
{
// By default the PackageReferenceFile does not throw
// if the file does not exist at the specified path.
// So we'll need to verify that the file exists.
Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
"Only one packages.config file is allowed to be specified " +
"at a time when not performing solution restore.");
var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
if (!File.Exists(packageReferenceFile))
{
var message = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
packageReferenceFile);
throw new InvalidOperationException(message);
}
foreach (PackageReference packageReference in GetInstalledPackageReferences(packageReferenceFile))
{
bool exists = nuGetPackageManager.PackageExistsInPackagesFolder(packageReference.PackageIdentity, packageSaveMode);
packageRestoreData.Add(new PackageRestoreData(packageReference, [packageReferenceFile], !exists));
areAnyPackagesMissing |= !exists;
}
}
if (!areAnyPackagesMissing)
{
var message = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
"packages.config");
Console.LogMinimal(message);
var restoreSummaries = new List<RestoreSummary>();
ValidatePackagesConfigLockFiles(
packageRestoreInputs.PackagesConfigFiles,
packageRestoreInputs.ProjectReferenceLookup.Projects,
packagesFolderPath,
restoreSummaries);
if (restoreSummaries.Count == 0)
{
restoreSummaries.Add(new RestoreSummary(success: true));
}
return restoreSummaries;
}
var packageSources = GetPackageSources(Settings);
var repositories = packageSources
.Select(sourceRepositoryProvider.CreateRepository)
.ToArray();
var installCount = 0;
var failedEvents = new ConcurrentQueue<PackageRestoreFailedEventArgs>();
var collectorLogger = new RestoreCollectorLogger(Console);
var packageRestoreContext = new PackageRestoreContext(
nuGetPackageManager,
packageRestoreData,
CancellationToken.None,
packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
sourceRepositories: repositories,
maxNumberOfParallelTasks: DisableParallelProcessing
? 1
: PackageManagementConstants.DefaultMaxDegreeOfParallelism,
logger: collectorLogger);
CheckRequireConsent();
var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, collectorLogger);
var projectContext = new ConsoleProjectContext(collectorLogger)
{
PackageExtractionContext = new PackageExtractionContext(
Packaging.PackageSaveMode.Defaultv2,
PackageExtractionBehavior.XmlDocFileSaveMode,
clientPolicyContext,
collectorLogger)
};
if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
{
projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
}
using (var cacheContext = new SourceCacheContext())
{
cacheContext.NoCache = NoCache || NoHttpCache;
cacheContext.DirectDownload = DirectDownload;
var packageSourceMapping = PackageSourceMapping.GetPackageSourceMapping(Settings);
var downloadContext = new PackageDownloadContext(cacheContext, packagesFolderPath, DirectDownload, packageSourceMapping)
{
ClientPolicyContext = clientPolicyContext
};
var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
packageRestoreContext,
projectContext,
downloadContext);
if (downloadContext.DirectDownload)
{
GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
}
IReadOnlyList<IRestoreLogMessage> errors = collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToList();
var restoreSummaries = new List<RestoreSummary>()
{
new RestoreSummary(
result.Restored,
"packages.config projects",
Settings.GetConfigFilePaths().ToList().AsReadOnly(),
packageSources.Select(x => x.Source).ToList().AsReadOnly(),
installCount,
errors)
};
if (result.Restored)
{
ValidatePackagesConfigLockFiles(
packageRestoreInputs.PackagesConfigFiles,
packageRestoreInputs.ProjectReferenceLookup.Projects,
packagesFolderPath,
restoreSummaries);
}
return restoreSummaries;
}
}
private static Dictionary<string, string> GetPackagesConfigToProjectPath(PackageRestoreInputs packageRestoreInputs)
{
Dictionary<string, string> configToProjectPath = new();
foreach (PackageSpec project in packageRestoreInputs.ProjectReferenceLookup.Projects)
{
if (project.RestoreMetadata?.ProjectStyle == ProjectStyle.PackagesConfig)
{
configToProjectPath.Add(((PackagesConfigProjectRestoreMetadata)project.RestoreMetadata).PackagesConfigPath, project.FilePath);
}
}
return configToProjectPath;
}
/// <summary>
/// Processes List of PackageRestoreFailedEventArgs into a List of RestoreLogMessages.
/// </summary>
/// <param name="failedEvents">List of PackageRestoreFailedEventArgs.</param>
/// <returns>List of RestoreLogMessages.</returns>
private static IEnumerable<RestoreLogMessage> ProcessFailedEventsIntoRestoreLogs(ConcurrentQueue<PackageRestoreFailedEventArgs> failedEvents)
{
var result = new List<RestoreLogMessage>();
foreach (var failedEvent in failedEvents)
{
if (failedEvent.Exception is SignatureException)
{
var signatureException = failedEvent.Exception as SignatureException;
var errorsAndWarnings = signatureException
.Results.SelectMany(r => r.Issues)
.Where(i => i.Level == LogLevel.Error || i.Level == LogLevel.Warning)
.Select(i => i.AsRestoreLogMessage());
result.AddRange(errorsAndWarnings);
}
else
{
result.Add(new RestoreLogMessage(LogLevel.Error, NuGetLogCode.Undefined, failedEvent.Exception.Message));
}
}
return result;
}
private void CheckRequireConsent()
{
if (RequireConsent)
{
var packageRestoreConsent = new PackageRestoreConsent(Settings);
if (packageRestoreConsent.IsGranted)
{
var message = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("RestoreCommandPackageRestoreOptOutMessage"),
NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
Console.LogInformation(message);
}
else
{
var message = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("InstallCommandPackageRestoreConsentNotFound"),
NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
throw new CommandException(message);
}
}
}
/// <summary>
/// Discover all restore inputs, this checks for both v2 and v3
/// </summary>
private async Task<PackageRestoreInputs> DetermineRestoreInputsAsync()
{
var packageRestoreInputs = new PackageRestoreInputs();
if (Arguments.Count == 0)
{
// If no arguments were provided use the current directory
GetInputsFromDirectory(Directory.GetCurrentDirectory(), packageRestoreInputs);
}
else
{
// Restore takes multiple arguments, each could be a file or directory
var argument = Arguments.Single();
string fullPath;
try
{
fullPath = Path.GetFullPath(argument);
}
catch (ArgumentException)
{
// Treat "invalid characters in path" like a file not found.
// Afterall, a filename with invalid characters can't exist.
var message = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
argument);
throw new InvalidOperationException(message);
}
if (Directory.Exists(fullPath))
{
// Dir
GetInputsFromDirectory(fullPath, packageRestoreInputs);
}
else if (File.Exists(fullPath))
{
// File
GetInputsFromFile(fullPath, packageRestoreInputs);
}
else
{
// Not found
var message = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
argument);
throw new InvalidOperationException(message);
}
}
// Run inputs through msbuild to determine the
// correct type and find dependencies as needed.
await DetermineInputsFromMSBuildAsync(packageRestoreInputs);
return packageRestoreInputs;
}
/// <summary>
/// Read project inputs using MSBuild
/// </summary>
private async Task DetermineInputsFromMSBuildAsync(PackageRestoreInputs packageRestoreInputs)
{
// Find P2P graph for v3 inputs.
// Ignore xproj files as top level inputs
var projectsWithPotentialP2PReferences = packageRestoreInputs
.ProjectFiles
.Where(path => !path.EndsWith(".xproj", StringComparison.OrdinalIgnoreCase))
.ToArray();
if (projectsWithPotentialP2PReferences.Length > 0)
{
DependencyGraphSpec dgFileOutput = null;
try
{
dgFileOutput = await GetDependencyGraphSpecAsync(projectsWithPotentialP2PReferences,
GetSolutionDirectory(packageRestoreInputs),
packageRestoreInputs.NameOfSolutionFile,
ConfigFile);
}
catch (Exception ex)
{
// At this point reading the project has failed, to keep backwards
// compatibility this should warn instead of error if
// packages.config files exist, but no project.json files.
// This will skip NETCore projects which is a problem, but there is
// not a good way to know if they exist, or if this is an old type of
// project that the targets file cannot handle.
// Log exception for debug
Console.LogDebug(ex.ToString());
// Check for packages.config but no project.json files
if (projectsWithPotentialP2PReferences.Where(HasPackagesConfigFile).Any()
&& !projectsWithPotentialP2PReferences.Where(HasProjectJsonFile).Any())
{
// warn to let the user know that NETCore will be skipped
Console.LogWarning(LocalizedResourceManager.GetString("Warning_ReadingProjectsFailed"));
// Add packages.config
packageRestoreInputs.PackagesConfigFiles
.AddRange(projectsWithPotentialP2PReferences
.Select(GetPackagesConfigFile)
.Where(path => path != null));
}
else
{
// If there are project.json files or no packages.config files
// continue to fail
throw;
}
}
// Process the DG file and add both v2 and v3 inputs
if (dgFileOutput != null)
{
AddInputsFromDependencyGraphSpec(packageRestoreInputs, dgFileOutput);
}
}
}
private void AddInputsFromDependencyGraphSpec(PackageRestoreInputs packageRestoreInputs, DependencyGraphSpec dgFileOutput)
{
packageRestoreInputs.ProjectReferenceLookup = dgFileOutput;
// Get top level entries
var entryPointProjects = dgFileOutput
.Projects
.Where(project => dgFileOutput.Restore.Contains(project.RestoreMetadata.ProjectUniqueName, StringComparer.Ordinal))
.ToList();
// possible packages.config
// Compare paths case-insenstive here since we do not know how msbuild modified them
// find all projects that are not part of the v3 group
var v2RestoreProjects =
packageRestoreInputs.ProjectFiles
.Where(path => !entryPointProjects.Any(project => path.Equals(project.RestoreMetadata.ProjectPath, StringComparison.OrdinalIgnoreCase)));
packageRestoreInputs.PackagesConfigFiles
.AddRange(v2RestoreProjects
.Select(GetPackagesConfigFile)
.Where(path => path != null));
// Filter down to just the requested projects in the file
// that support transitive references.
var v3RestoreProjects = entryPointProjects
.Where(project => project.RestoreMetadata.ProjectStyle is ProjectStyle.PackageReference or ProjectStyle.ProjectJson);
packageRestoreInputs.RestoreV3Context.Inputs.AddRange(v3RestoreProjects
.Select(project => project.RestoreMetadata.ProjectPath));
}
private string GetPackagesConfigFile(string projectFilePath)
{
// Get possible packages.config path
var packagesConfigPath = GetPackageReferenceFile(projectFilePath);
if (File.Exists(packagesConfigPath))
{
return packagesConfigPath;
}
return null;
}
private bool HasPackagesConfigFile(string projectFilePath)
{
// Get possible packages.config path
return GetPackagesConfigFile(projectFilePath) != null;
}
private bool HasProjectJsonFile(string projectFilePath)
{
// Get possible project.json path
var projectFileName = Path.GetFileName(projectFilePath);
var projectName = Path.GetFileNameWithoutExtension(projectFileName);
var dir = Path.GetDirectoryName(projectFilePath);
var projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName);
return File.Exists(projectJsonPath);
}
/// <summary>
/// Create a dg v2 file using msbuild.
/// </summary>
private async Task<DependencyGraphSpec> GetDependencyGraphSpecAsync(string[] projectsWithPotentialP2PReferences, string solutionDirectory, string solutionName, string configFile)
{
// Create requests based on the solution directory if a solution was used read settings for the solution.
// If the solution directory is null, then use config file if present
// Then use restore directory last
// If all 3 are null, then the directory of the project will be used to evaluate the settings
int scaleTimeout;
if (Project2ProjectTimeOut > 0)
{
scaleTimeout = Project2ProjectTimeOut * 1000;
}
else
{
scaleTimeout = MsBuildUtility.MsBuildWaitTime *
Math.Max(10, projectsWithPotentialP2PReferences.Length / 2) / 10;
}
Console.LogVerbose($"MSBuild P2P timeout [ms]: {scaleTimeout}");
string restorePackagesWithLockFile = UseLockFile ? bool.TrueString : null;
var restoreLockProperties = new RestoreLockProperties(restorePackagesWithLockFile, LockFilePath, LockedMode);
// Call MSBuild to resolve P2P references.
return await MsBuildUtility.GetProjectReferencesAsync(
MsBuildDirectory.Value,
projectsWithPotentialP2PReferences,
scaleTimeout,
Console,
Recursive,
solutionDirectory,
solutionName,
configFile,
Source.ToArray(),
PackagesDirectory,
restoreLockProperties
);
}
/// <summary>
/// Determine if a file is v2 or v3
/// </summary>
private void GetInputsFromFile(string projectFilePath, PackageRestoreInputs packageRestoreInputs)
{
// An argument was passed in. It might be a solution file or directory,
// project file, or packages.config file
var projectFileName = Path.GetFileName(projectFilePath);
if (IsPackagesConfig(projectFileName))
{
// restoring from packages.config or packages.projectname.config file
packageRestoreInputs.PackagesConfigFiles.Add(projectFilePath);
}
else if (projectFileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
{
packageRestoreInputs.ProjectFiles.Add(projectFilePath);
}
else if (projectFileName.EndsWith(".dg", StringComparison.OrdinalIgnoreCase))
{
packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
}
else if (projectFileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase)
|| projectFileName.EndsWith(".slnf", StringComparison.OrdinalIgnoreCase))
{
ProcessSolutionFile(projectFilePath, packageRestoreInputs);
}
else if (ProjectJsonPathUtilities.IsProjectConfig(projectFileName))
{
// project.json is no longer allowed
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("Error_ProjectJsonNotAllowed"), projectFileName));
}
else
{
// Not a file we know about. Try to be helpful without response.
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, RestoreRunner.GetInvalidInputErrorMessage(projectFileName), projectFileName));
}
}
/// <summary>
/// Search a directory for v2 or v3 inputs, only the first type is taken.
/// </summary>
private void GetInputsFromDirectory(string directory, PackageRestoreInputs packageRestoreInputs)
{
var topLevelFiles = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly);
// Solution files
var solutionFiles = topLevelFiles.Where(file =>
file.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
.ToArray();
if (solutionFiles.Length > 0)
{
if (solutionFiles.Length != 1)
{
throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_MultipleSolutions"));
}
var file = solutionFiles[0];
if (Verbosity == Verbosity.Detailed)
{
Console.WriteLine(
LocalizedResourceManager.GetString("RestoreCommandRestoringPackagesForSolution"),
file);
}
ProcessSolutionFile(file, packageRestoreInputs);
return;
}
// Packages.config
var packagesConfigFile = Path.Combine(directory, Constants.PackageReferenceFile);
if (File.Exists(packagesConfigFile))
{
if (Verbosity == Verbosity.Detailed)
{
Console.WriteLine(
LocalizedResourceManager.GetString(
"RestoreCommandRestoringPackagesFromPackagesConfigFile"));
}
// packages.confg with no solution file
packageRestoreInputs.PackagesConfigFiles.Add(packagesConfigFile);
return;
}
// The directory did not contain a valid target, fail!
var noInputs = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString(
"Error_UnableToLocateRestoreTarget"),
directory);
throw new InvalidOperationException(noInputs);
}
private static bool IsSolutionOrProjectFile(string fileName)
{
if (!string.IsNullOrEmpty(fileName))
{
var extension = Path.GetExtension(fileName);
var lastFourCharacters = string.Empty;
var length = extension.Length;
if (length >= 4)
{
lastFourCharacters = extension.Substring(length - 4);
}
return (string.Equals(extension, ".sln", StringComparison.OrdinalIgnoreCase)
|| string.Equals(lastFourCharacters, "proj", StringComparison.OrdinalIgnoreCase));
}
return false;
}
/// <summary>
/// True if the filename is a packages.config file
/// </summary>
private static bool IsPackagesConfig(string projectFileName)
{
return string.Equals(projectFileName, Constants.PackageReferenceFile, PathUtility.GetStringComparisonBasedOnOS())
|| (projectFileName.StartsWith("packages.", StringComparison.OrdinalIgnoreCase)
&& string.Equals(
Path.GetExtension(projectFileName),
Path.GetExtension(Constants.PackageReferenceFile), StringComparison.OrdinalIgnoreCase));
}
private string GetPackagesFolder(PackageRestoreInputs packageRestoreInputs)
{
if (!string.IsNullOrEmpty(PackagesDirectory))
{
return PackagesDirectory;
}
var repositoryPath = SettingsUtility.GetRepositoryPath(Settings);
if (!string.IsNullOrEmpty(repositoryPath))
{
return repositoryPath;
}
if (!string.IsNullOrEmpty(SolutionDirectory))
{
return Path.Combine(SolutionDirectory, CommandLineConstants.PackagesDirectoryName);
}
if (packageRestoreInputs.RestoringWithSolutionFile)
{
return Path.Combine(
packageRestoreInputs.DirectoryOfSolutionFile,
CommandLineConstants.PackagesDirectoryName);
}
throw new InvalidOperationException(
LocalizedResourceManager.GetString("RestoreCommandCannotDeterminePackagesFolder"));
}
private static string ConstructPackagesConfigFromProjectName(string projectName)
{
// we look for packages.<project name>.config file
// but we don't want any space in the file name, so convert it to underscore.
return "packages." + projectName.Replace(' ', '_') + ".config";
}
// returns the package reference file associated with the project
private string GetPackageReferenceFile(string projectFile)
{
var projectName = Path.GetFileNameWithoutExtension(projectFile);
var pathWithProjectName = Path.Combine(
Path.GetDirectoryName(projectFile),
ConstructPackagesConfigFromProjectName(projectName));
if (File.Exists(pathWithProjectName))
{
return pathWithProjectName;
}
return Path.Combine(
Path.GetDirectoryName(projectFile),
Constants.PackageReferenceFile);
}
private void ProcessSolutionFile(string solutionFileFullPath, PackageRestoreInputs restoreInputs)
{
restoreInputs.DirectoryOfSolutionFile = Path.GetDirectoryName(solutionFileFullPath);
restoreInputs.NameOfSolutionFile = Path.GetFileNameWithoutExtension(solutionFileFullPath);
// restore packages for the solution
string solutionLevelPackagesConfig;
try
{
solutionLevelPackagesConfig = Path.Combine(
restoreInputs.DirectoryOfSolutionFile,
NuGetConstants.NuGetSolutionSettingsFolder,
Constants.PackageReferenceFile);
}
catch (ArgumentException e)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("Error_InvalidSolutionDirectory"),
restoreInputs.DirectoryOfSolutionFile),
e);
}
if (File.Exists(solutionLevelPackagesConfig))
{
restoreInputs.PackagesConfigFiles.Add(solutionLevelPackagesConfig);
}
var projectFiles = MsBuildUtility.GetAllProjectFileNames(solutionFileFullPath, MsBuildDirectory.Value.Path);
foreach (var projectFile in projectFiles)
{
if (!File.Exists(projectFile))
{
var message = string.Format(CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"),
projectFile);
Console.LogWarning(message);
continue;
}
var normalizedProjectFile = Path.GetFullPath(projectFile);
// Add everything
restoreInputs.ProjectFiles.Add(normalizedProjectFile);
}
}
private void ValidatePackagesConfigLockFiles(IReadOnlyList<string> packagesConfigFiles, IReadOnlyList<PackageSpec> projects, string packagesFolderPath, List<RestoreSummary> restoreSummaries)
{
foreach (var pcFile in packagesConfigFiles)
{
var dgSpec = projects?.FirstOrDefault(p =>
{
if (p.RestoreMetadata is PackagesConfigProjectRestoreMetadata pcRestoreMetadata)
{
return StringComparer.OrdinalIgnoreCase.Equals(pcRestoreMetadata.PackagesConfigPath, pcFile);
}
return false;
});
var projectFile = dgSpec?.FilePath ?? pcFile;
var projectTfm = dgSpec?.TargetFrameworks.SingleOrDefault()?.FrameworkName ?? NuGetFramework.AnyFramework;
var restoreLockedMode = LockedMode || (dgSpec?.RestoreMetadata?.RestoreLockProperties?.RestoreLockedMode ?? false);
var lockFilePath = LockFilePath ?? dgSpec?.RestoreMetadata?.RestoreLockProperties?.NuGetLockFilePath;
var useLockFile = UseLockFile ? bool.TrueString : dgSpec?.RestoreMetadata?.RestoreLockProperties?.RestorePackagesWithLockFile;
IReadOnlyList<IRestoreLogMessage> result = PackagesConfigLockFileUtility.ValidatePackagesConfigLockFiles(
projectFile,
pcFile,