-
Notifications
You must be signed in to change notification settings - Fork 743
Expand file tree
/
Copy pathRestoreTask.cs
More file actions
289 lines (243 loc) · 10.5 KB
/
RestoreTask.cs
File metadata and controls
289 lines (243 loc) · 10.5 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
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.Commands;
using NuGet.Common;
using NuGet.ProjectModel;
namespace NuGet.Build.Tasks
{
/// <summary>
/// .NET Core compatible restore task for PackageReference and UWP project.json projects.
/// </summary>
public class RestoreTask : Microsoft.Build.Utilities.Task, ICancelableTask, IDisposable
{
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private readonly IEnvironmentVariableReader _environmentVariableReader;
private bool _disposed = false;
public RestoreTask()
: this(EnvironmentVariableWrapper.Instance)
{
}
internal RestoreTask(IEnvironmentVariableReader environmentVariableReader)
{
_environmentVariableReader = environmentVariableReader ?? throw new ArgumentNullException(nameof(environmentVariableReader));
}
/// <summary>
/// DG file entries
/// </summary>
[Required]
public ITaskItem[] RestoreGraphItems { get; set; }
/// <summary>
/// Disable parallel project restores and downloads
/// </summary>
public bool RestoreDisableParallel { get; set; }
/// <summary>
/// Disable the web cache
/// </summary>
public bool RestoreNoCache { get; set; }
/// <summary>
/// Disable the web cache
/// </summary>
public bool RestoreNoHttpCache { get; set; }
/// <summary>
/// Ignore errors from package sources
/// </summary>
public bool RestoreIgnoreFailedSources { get; set; }
/// <summary>
/// Restore all projects.
/// </summary>
public bool RestoreRecursive { get; set; }
/// <summary>
/// Force restore, skip no op
/// </summary>
public bool RestoreForce { get; set; }
/// <summary>
/// Do not display Errors and Warnings to the user.
/// The Warnings and Errors are written into the assets file and will be read by an sdk target.
/// </summary>
public bool HideWarningsAndErrors { get; set; }
/// <summary>
/// Set this property if you want to get an interactive restore
/// </summary>
public bool Interactive { get; set; }
/// <summary>
/// Reevaluate resotre graph even with a lock file, skip no op as well.
/// </summary>
public bool RestoreForceEvaluate { get; set; }
/// <summary>
/// Restore projects using packages.config for dependencies.
/// </summary>
/// <returns></returns>
public bool RestorePackagesConfig { get; set; }
/// <summary>
/// Gets or sets the paths for files to embed in the binary log.
/// </summary>
[Output]
public ITaskItem[] EmbedInBinlog { get; set; }
/// <summary>
/// Gets or sets the number of projects that were considered for this restore operation.
/// </summary>
/// <remarks>
/// Projects that no-op (were already up to date) are included.
/// </remarks>
[Output]
public int ProjectsRestored { get; set; }
/// <summary>
/// Gets or sets the number of projects that were already up to date.
/// </summary>
[Output]
public int ProjectsAlreadyUpToDate { get; set; }
/// <summary>
/// Gets or sets the number of projects that NuGetAudit scanned.
/// </summary>
/// <remarks>
/// NuGetAudit does not run on no-op restores, or when no vulnerability database can be downloaded.
/// </remarks>
[Output]
public int ProjectsAudited { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to embed files produced by restore in the MSBuild binary logger.
/// 0 = Nothing
/// 1 = Assets file, g.props, and g.targets
/// 2 = dgspec, assets file, g.props, and g.targets
/// </summary>
public string EmbedFilesInBinlog { get; set; }
public override bool Execute()
{
var debugRestoreTask = _environmentVariableReader.GetEnvironmentVariable("DEBUG_RESTORE_TASK");
if (!string.IsNullOrEmpty(debugRestoreTask) &&
(debugRestoreTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase) || debugRestoreTask == "1"))
{
Debugger.Launch();
}
var log = new MSBuildLogger(Log);
NuGet.Common.Migrations.MigrationRunner.Run();
try
{
return ExecuteAsync(log).Result;
}
catch (AggregateException ex) when (_cts.Token.IsCancellationRequested && ex.InnerException is OperationCanceledException)
{
// Canceled by user
log.LogError(Strings.RestoreCanceled);
return false;
}
catch (Exception e)
{
ExceptionUtilities.LogException(e, log);
return false;
}
}
private async Task<bool> ExecuteAsync(Common.ILogger log)
{
if (RestoreGraphItems.Length < 1 && !HideWarningsAndErrors)
{
log.LogWarning(Strings.NoProjectsProvidedToTask);
return true;
}
// Convert to the internal wrapper
var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);
var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems, readOnly: true);
EmbedInBinlog = GetFilesToEmbedInBinlog(dgFile);
if (RestoreNoCache)
{
//Inform users that NoCache option is just for disabling HttpCache and
//suggest them to use NoHttpCache instead, which does the same thing.
log.LogInformation(Strings.Log_RestoreNoCacheInformation);
}
var restoreSummaries = await BuildTasksUtility.RestoreAsync(
dependencyGraphSpec: dgFile,
interactive: Interactive,
recursive: RestoreRecursive,
noCache: RestoreNoCache || RestoreNoHttpCache,
ignoreFailedSources: RestoreIgnoreFailedSources,
disableParallel: RestoreDisableParallel,
force: RestoreForce,
forceEvaluate: RestoreForceEvaluate,
hideWarningsAndErrors: HideWarningsAndErrors,
restorePC: RestorePackagesConfig,
log: log,
cancellationToken: _cts.Token);
int upToDate = 0;
int audited = 0;
foreach (var summary in restoreSummaries)
{
if (summary.NoOpRestore) { upToDate++; }
if (summary.AuditRan) { audited++; }
}
ProjectsRestored = restoreSummaries.Count;
ProjectsAlreadyUpToDate = upToDate;
ProjectsAudited = audited;
return restoreSummaries.All(s => s.Success);
}
public void Cancel()
{
_cts.Cancel();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_cts.Dispose();
}
_disposed = true;
}
/// <summary>
/// Gets the list of files to embed in the MSBuild binary log.
/// </summary>
/// <param name="dependencyGraphSpec"></param>
/// <returns>If the MSBuildBinaryLoggerEnabled environment variable is set, returns the paths to NuGet files to embed in the binlog, otherwise returns <see cref="Array.Empty{T}" />.</returns>
private ITaskItem[] GetFilesToEmbedInBinlog(DependencyGraphSpec dependencyGraphSpec)
{
// Determines what the user wants embedded in the binary log where 0 or false disables embedding anything, 2 embeds everything, and 1 or true embeds just the assets file, g.props, and g.targets.
int embedInBinlogSelection = BuildTasksUtility.GetFilesToEmbedInBinlogValue(EmbedFilesInBinlog);
if (embedInBinlogSelection == 0)
{
return Array.Empty<ITaskItem>();
}
IReadOnlyList<PackageSpec> projects = dependencyGraphSpec.Projects;
List<ITaskItem> restoredProjectOutputPaths = new List<ITaskItem>(projects.Count);
foreach (PackageSpec project in projects)
{
if (project.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference)
{
restoredProjectOutputPaths.Add(new TaskItem(Path.Combine(project.RestoreMetadata.OutputPath, LockFileFormat.AssetsFileName)));
restoredProjectOutputPaths.Add(new TaskItem(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.PropsExtension)));
restoredProjectOutputPaths.Add(new TaskItem(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.TargetsExtension)));
// Only include the dgspec if the user wants everything embedded in the binlog.
if (embedInBinlogSelection == 2)
{
restoredProjectOutputPaths.Add(new TaskItem(Path.Combine(project.RestoreMetadata.OutputPath, DependencyGraphSpec.GetDGSpecFileName(Path.GetFileName(project.RestoreMetadata.ProjectPath)))));
}
}
else if (project.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig)
{
string packagesConfigPath = BuildTasksUtility.GetPackagesConfigFilePath(project.RestoreMetadata.ProjectPath);
if (packagesConfigPath != null)
{
restoredProjectOutputPaths.Add(new TaskItem(packagesConfigPath));
}
}
}
return restoredProjectOutputPaths.ToArray();
}
}
}