-
Notifications
You must be signed in to change notification settings - Fork 694
/
DependencyGraphRestoreUtility.cs
310 lines (265 loc) · 12.2 KB
/
DependencyGraphRestoreUtility.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
// 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.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.ProjectManagement;
using NuGet.ProjectManagement.Projects;
using NuGet.ProjectModel;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
namespace NuGet.PackageManagement
{
/// <summary>
/// Supporting methods for restoring sets of projects that implement <see cref="IDependencyGraphProject"/>. This
/// code is used by Visual Studio to execute restores for solutions that have mixtures of UWP project.json,
/// packages.config, and PackageReference-type projects.
/// </summary>
public static class DependencyGraphRestoreUtility
{
/// <summary>
/// Restore a solution and cache the dg spec to context.
/// </summary>
public static async Task<IReadOnlyList<RestoreSummary>> RestoreAsync(
ISolutionManager solutionManager,
DependencyGraphSpec dgSpec,
DependencyGraphCacheContext context,
RestoreCommandProvidersCache providerCache,
Action<SourceCacheContext> cacheContextModifier,
IEnumerable<SourceRepository> sources,
Guid parentId,
bool forceRestore,
bool isRestoreOriginalAction,
ILogger log,
CancellationToken token)
{
// TODO: This will flow from UI once we enable UI option to trigger reevaluation
var restoreForceEvaluate = false;
// Check if there are actual projects to restore before running.
if (dgSpec.Restore.Count > 0)
{
using (var sourceCacheContext = new SourceCacheContext())
{
// Update cache context
cacheContextModifier(sourceCacheContext);
var restoreContext = GetRestoreContext(
context,
providerCache,
sourceCacheContext,
sources,
dgSpec,
parentId,
forceRestore,
isRestoreOriginalAction,
restoreForceEvaluate);
var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, token);
RestoreSummary.Log(log, restoreSummaries);
await PersistDGSpec(dgSpec);
return restoreSummaries;
}
}
return new List<RestoreSummary>();
}
private static async Task PersistDGSpec(DependencyGraphSpec dgSpec)
{
try
{
var filePath = Path.Combine(
NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp),
"nuget-dg",
"nugetSpec.dg");
// create nuget temp folder if not exists
DirectoryUtility.CreateSharedDirectory(Path.GetDirectoryName(filePath));
// delete existing dg spec file (if exists) then replace it with new file.
await FileUtility.ReplaceWithLock(
(tempFile) => dgSpec.Save(tempFile), filePath);
}
catch (Exception)
{
//ignore any failure if it fails to write or replace dg spec file.
}
}
/// <summary>
/// Restore without writing the lock file
/// </summary>
internal static async Task<RestoreResultPair> PreviewRestoreAsync(
ISolutionManager solutionManager,
BuildIntegratedNuGetProject project,
PackageSpec packageSpec,
DependencyGraphCacheContext context,
RestoreCommandProvidersCache providerCache,
Action<SourceCacheContext> cacheContextModifier,
IEnumerable<SourceRepository> sources,
Guid parentId,
ILogger log,
CancellationToken token)
{
// Restoring packages
var logger = context.Logger;
// Add the new spec to the dg file and fill in the rest.
var dgFile = await GetSolutionRestoreSpec(solutionManager, context);
dgFile = dgFile.WithoutRestores()
.WithReplacedSpec(packageSpec);
dgFile.AddRestore(project.MSBuildProjectPath);
using (var sourceCacheContext = new SourceCacheContext())
{
// Update cache context
cacheContextModifier(sourceCacheContext);
// Settings passed here will be used to populate the restore requests.
var restoreContext = GetRestoreContext(
context,
providerCache,
sourceCacheContext,
sources,
dgFile,
parentId,
forceRestore: true,
isRestoreOriginalAction: false,
restoreForceEvaluate: true);
var requests = await RestoreRunner.GetRequests(restoreContext);
var results = await RestoreRunner.RunWithoutCommit(requests, restoreContext);
return results.Single();
}
}
/// <summary>
/// Restore a build integrated project(PackageReference and Project.Json only) and update the lock file
/// </summary>
public static async Task<RestoreResult> RestoreProjectAsync(
ISolutionManager solutionManager,
BuildIntegratedNuGetProject project,
DependencyGraphCacheContext context,
RestoreCommandProvidersCache providerCache,
Action<SourceCacheContext> cacheContextModifier,
IEnumerable<SourceRepository> sources,
Guid parentId,
ILogger log,
CancellationToken token)
{
// Restore
var specs = await project.GetPackageSpecsAsync(context);
var spec = specs.Single(e => e.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference
|| e.RestoreMetadata.ProjectStyle == ProjectStyle.ProjectJson); // Do not restore global tools Project Style in VS.
var result = await PreviewRestoreAsync(
solutionManager,
project,
spec,
context,
providerCache,
cacheContextModifier,
sources,
parentId,
log,
token);
// Throw before writing if this has been canceled
token.ThrowIfCancellationRequested();
// Write out the lock file and msbuild files
var summary = await RestoreRunner.CommitAsync(result, token);
RestoreSummary.Log(log, new[] { summary });
return result.Result;
}
public static bool IsRestoreRequired(
DependencyGraphSpec solutionDgSpec)
{
if (solutionDgSpec.Restore.Count < 1)
{
// Nothing to restore
return false;
}
// NO Op will be checked in the restore command
return true;
}
public static async Task<PackageSpec> GetProjectSpec(IDependencyGraphProject project, DependencyGraphCacheContext context)
{
var specs = await project.GetPackageSpecsAsync(context);
var projectSpec = specs.Where(e => e.RestoreMetadata.ProjectStyle != ProjectStyle.Standalone
&& e.RestoreMetadata.ProjectStyle != ProjectStyle.DotnetCliTool)
.FirstOrDefault();
return projectSpec;
}
public static async Task<DependencyGraphSpec> GetSolutionRestoreSpec(
ISolutionManager solutionManager,
DependencyGraphCacheContext context)
{
var dgSpec = new DependencyGraphSpec();
var stringComparer = PathUtility.GetStringComparerBasedOnOS();
var uniqueProjectDependencies = new HashSet<string>(stringComparer);
var projects = ((await solutionManager.GetNuGetProjectsAsync()).OfType<IDependencyGraphProject>()).ToList();
for (var i=0; i< projects.Count; i++)
{
var packageSpecs = await projects[i].GetPackageSpecsAsync(context);
foreach (var packageSpec in packageSpecs)
{
dgSpec.AddProject(packageSpec);
if (packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference ||
packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.ProjectJson ||
packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.DotnetCliTool ||
packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.Standalone) // Don't add global tools to restore specs for solutions
{
dgSpec.AddRestore(packageSpec.RestoreMetadata.ProjectUniqueName);
var projFileName = Path.GetFileName(packageSpec.RestoreMetadata.ProjectPath);
var dgFileName = DependencyGraphSpec.GetDGSpecFileName(projFileName);
var outputPath = packageSpec.RestoreMetadata.OutputPath;
if (!string.IsNullOrEmpty(outputPath))
{
var persistedDGSpecPath = Path.Combine(outputPath, dgFileName);
if (File.Exists(persistedDGSpecPath))
{
var persistedDGSpec = DependencyGraphSpec.Load(persistedDGSpecPath);
foreach (var dependentPackageSpec in persistedDGSpec.GetClosure(packageSpec.RestoreMetadata.ProjectUniqueName))
{
if (!(uniqueProjectDependencies.Contains(dependentPackageSpec.RestoreMetadata.ProjectPath) ||
projects.Any(p => stringComparer.Equals(p.MSBuildProjectPath, dependentPackageSpec.RestoreMetadata.ProjectPath))))
{
uniqueProjectDependencies.Add(dependentPackageSpec.RestoreMetadata.ProjectPath);
dgSpec.AddProject(dependentPackageSpec);
}
}
}
}
}
}
}
// Return dg file
return dgSpec;
}
/// <summary>
/// Create a restore context.
/// </summary>
private static RestoreArgs GetRestoreContext(
DependencyGraphCacheContext context,
RestoreCommandProvidersCache providerCache,
SourceCacheContext sourceCacheContext,
IEnumerable<SourceRepository> sources,
DependencyGraphSpec dgFile,
Guid parentId,
bool forceRestore,
bool isRestoreOriginalAction,
bool restoreForceEvaluate)
{
var caching = new CachingSourceProvider(new PackageSourceProvider(context.Settings));
foreach( var source in sources)
{
caching.AddSourceRepository(source);
}
var dgProvider = new DependencyGraphSpecRequestProvider(providerCache, dgFile);
var restoreContext = new RestoreArgs()
{
CacheContext = sourceCacheContext,
PreLoadedRequestProviders = new List<IPreLoadedRestoreRequestProvider>() { dgProvider },
Log = context.Logger,
AllowNoOp = !forceRestore,
CachingSourceProvider = caching,
ParentId = parentId,
IsRestoreOriginalAction = isRestoreOriginalAction,
RestoreForceEvaluate = restoreForceEvaluate
};
return restoreContext;
}
}
}