Skip to content

Commit 990015a

Browse files
[main] Source code updates from nuget/nuget.client (#10379)
[main] Source code updates from nuget/nuget.client
1 parent 172c55a commit 990015a

18 files changed

Lines changed: 345 additions & 99 deletions

File tree

‎src/nuget-client/src/NuGet.Core/Microsoft.Build.NuGetSdkResolver/RestoreRunnerEx.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using System.IO;
77
using System.Linq;
88
using System.Threading.Tasks;
9-
using NuGet.Common;
109
using NuGet.Configuration;
1110
using NuGet.Frameworks;
1211
using NuGet.LibraryModel;
@@ -45,7 +44,9 @@ public static Task<IReadOnlyList<RestoreResultPair>> RunWithoutCommit(LibraryIde
4544
IgnoreFailedSources = true,
4645
})
4746
{
48-
var projectDirectory = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), Guid.NewGuid().ToString("N", null));
47+
#pragma warning disable RS0030 // This is only a synthetic project path; no directory is created or files written here.
48+
var projectDirectory = Path.Combine(Path.GetTempPath(), $"NuGet-{Guid.NewGuid():N}");
49+
#pragma warning restore RS0030
4950

5051
var projectName = Guid.NewGuid().ToString("N", null);
5152

‎src/nuget-client/src/NuGet.Core/NuGet.Commands/CommandRunners/PackCommandRunner.cs‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -224,19 +224,22 @@ private void WriteResolvedNuSpecToPackageOutputDirectory(PackageBuilder builder)
224224
_packArgs.Path));
225225
}
226226

227-
// We must use the Path.GetTempPath() which NuGetFolderPath.Temp uses as a root because writing temp files
228-
// to the package directory with a guid would break some build tools caching
229227
var manifest = new Manifest(new ManifestMetadata(builder), files: null);
230-
string tempOutputPath = Path.Combine(
231-
NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp),
232-
Path.GetRandomFileName());
228+
// Keep staging files outside the package directory to avoid breaking build tools' caching.
229+
string tempOutputPath = Path.GetTempFileName();
230+
try
231+
{
232+
using (var stream = new FileStream(tempOutputPath, FileMode.Create))
233+
{
234+
manifest.Save(stream);
235+
}
233236

234-
using (var stream = new FileStream(tempOutputPath, FileMode.Create))
237+
FileUtility.Replace(tempOutputPath, resolvedNuSpecOutputPath);
238+
}
239+
finally
235240
{
236-
manifest.Save(stream);
241+
File.Delete(tempOutputPath);
237242
}
238-
239-
FileUtility.Replace(tempOutputPath, resolvedNuSpecOutputPath);
240243
}
241244

242245
/// <summary>
@@ -251,12 +254,6 @@ private void WriteSHA512PackageHash(PackageBuilder builder)
251254

252255
string sha512OutputPath = Path.Combine(outputPath + ".sha512");
253256

254-
// We must use the Path.GetTempPath() which NuGetFolderPath.Temp uses as a root because writing temp files
255-
// to the package directory with a guid would break some build tools caching
256-
string tempOutputPath = Path.Combine(
257-
NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp),
258-
Path.GetRandomFileName());
259-
260257
_packArgs.Logger.Log(
261258
PackagingLogMessage.CreateMessage(
262259
string.Format(
@@ -274,8 +271,17 @@ private void WriteSHA512PackageHash(PackageBuilder builder)
274271
sha512hash = cryptoHashProvider.CalculateHash(fileStream);
275272
}
276273

277-
File.WriteAllText(tempOutputPath, Convert.ToBase64String(sha512hash));
278-
FileUtility.Replace(tempOutputPath, sha512OutputPath);
274+
// Keep staging files outside the package directory to avoid breaking build tools' caching.
275+
string tempOutputPath = Path.GetTempFileName();
276+
try
277+
{
278+
File.WriteAllText(tempOutputPath, Convert.ToBase64String(sha512hash));
279+
FileUtility.Replace(tempOutputPath, sha512OutputPath);
280+
}
281+
finally
282+
{
283+
File.Delete(tempOutputPath);
284+
}
279285
}
280286

281287
private void InitCommonPackageBuilderProperties(PackageBuilder builder)

‎src/nuget-client/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/AuditUtility.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ private void ReplayErrors(AggregateException exceptions)
248248
{
249249
foreach (Exception exception in exceptions.InnerExceptions)
250250
{
251-
var messageText = string.Format(Strings.Error_VulnerabilityDataFetch, exception.Message);
251+
var messageText = string.Format(Strings.Error_VulnerabilityDataFetch, ExceptionUtilities.DisplayMessage(exception));
252252
RestoreLogMessage logMessage = RestoreLogMessage.CreateWarning(NuGetLogCode.NU1900, messageText);
253253
_logger.Log(logMessage);
254254
}

‎src/nuget-client/src/NuGet.Core/NuGet.Common/ConcurrencyUtilities.cs‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,6 @@ public static class ConcurrencyUtilities
1919
private const int HashLength = 20;
2020
private static readonly TimeSpan SleepDuration = TimeSpan.FromMilliseconds(10);
2121
private static readonly KeyedLock PerFileLock = new KeyedLock();
22-
private static bool? _useDeleteOnClose = null;
23-
24-
// FileOptions.DeleteOnClose causes concurrency issues on Mac OS X and Linux.
25-
// These are fixed in .NET 7 (https://github.com/dotnet/runtime/pull/55327).
26-
// To continue working in parallel with older versions of .NET,
27-
// we cannot use DeleteOnClose by default until .NET 6 goes EOL (Nov 2024).
28-
private static bool UseDeleteOnClose => _useDeleteOnClose ??= RuntimeEnvironmentHelper.IsWindows ||
29-
EnvironmentVariableReader.GetEnvironmentVariable("NUGET_ConcurrencyUtils_DeleteOnClose") == "1"; // opt-in.
3022

3123
internal static IEnvironmentVariableReader EnvironmentVariableReader { get; set; } = EnvironmentVariableWrapper.Instance;
3224

@@ -36,13 +28,12 @@ static ConcurrencyUtilities()
3628
}
3729

3830
/// <summary>
39-
/// Clears the environment-derived caches (the delete-on-close opt-in and the lock-file base path) so they
40-
/// are re-read from the current environment on next use. The base path also derives from the NuGet temp
41-
/// directory; callers should reset <see cref="NuGetEnvironment" /> as well.
31+
/// Clears the cached lock-file base path so it is re-read from the current environment on next use.
32+
/// The base path also derives from the NuGet home or temp directory; callers should reset
33+
/// <see cref="NuGetEnvironment" /> as well.
4234
/// </summary>
4335
internal static void ResetEnvironmentCaches()
4436
{
45-
_useDeleteOnClose = null;
4637
_basePath = null;
4738
}
4839

@@ -235,7 +226,7 @@ private static FileStream AcquireFileStream(string lockPath)
235226
FileAccess.ReadWrite,
236227
FileShare.None,
237228
bufferSize: 32,
238-
options: UseDeleteOnClose ? FileOptions.DeleteOnClose : FileOptions.None);
229+
options: FileOptions.DeleteOnClose);
239230
}
240231

241232
private static string? _basePath;
@@ -249,7 +240,11 @@ private static string BasePath
249240
return basePath;
250241
}
251242

252-
basePath = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "lock");
243+
var folder = RuntimeEnvironmentHelper.IsLinux &&
244+
string.IsNullOrEmpty(EnvironmentVariableReader.GetEnvironmentVariable("NUGET_SCRATCH"))
245+
? NuGetFolderPath.NuGetHome
246+
: NuGetFolderPath.Temp;
247+
basePath = Path.Combine(NuGetEnvironment.GetFolderPath(folder), "lock");
253248

254249
Directory.CreateDirectory(basePath);
255250

‎src/nuget-client/src/NuGet.Core/NuGet.Common/PathUtil/PathUtility.cs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,6 @@ private static bool CheckIfFileSystemIsCaseInsensitive()
453453
var listOfPathsToCheck = new Func<string>[]
454454
{
455455
() => NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome),
456-
() => NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp),
457456
() => Directory.GetCurrentDirectory()
458457
};
459458

‎src/nuget-client/src/NuGet.Core/NuGet.Packaging/PackageArchiveReader.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -308,9 +308,7 @@ public override IEnumerable<string> CopyFiles(
308308
var normalizedPath = Uri.UnescapeDataString(packageFileName.Replace('/', Path.DirectorySeparatorChar));
309309

310310
destination = NormalizeDirectoryPath(destination);
311-
ValidatePackageEntry(destination, normalizedPath, packageIdentity);
312-
313-
var targetFilePath = Path.Combine(destination, normalizedPath);
311+
var targetFilePath = GetValidatedPackageEntryPath(destination, normalizedPath, packageIdentity);
314312

315313
using (var stream = entry.Open())
316314
using (var sizedStream = new SizedArchiveEntryStream(stream, entry.Length))

‎src/nuget-client/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -552,7 +552,17 @@ protected static string GetNuspecFile(IEnumerable<string> files)
552552
/// </summary>
553553
protected static void ValidatePackageEntry(string normalizedDestination, string normalizedFilePath, PackageIdentity packageIdentity)
554554
{
555-
// Destination and filePath must be normalized.
555+
GetValidatedPackageEntryPath(normalizedDestination, normalizedFilePath, packageIdentity);
556+
}
557+
558+
/// <summary>
559+
/// Returns the canonical extraction path after checking that it is inside the destination directory.
560+
/// </summary>
561+
/// <param name="normalizedDestination">The canonical destination path, including its trailing directory separator.</param>
562+
/// <param name="normalizedFilePath">The package entry path, with URI escaping decoded and directory separators normalized.</param>
563+
/// <param name="packageIdentity">The package identity used in the error message for an unsafe entry.</param>
564+
internal static string GetValidatedPackageEntryPath(string normalizedDestination, string normalizedFilePath, PackageIdentity packageIdentity)
565+
{
556566
var fullPath = Path.GetFullPath(Path.Combine(normalizedDestination, normalizedFilePath));
557567

558568
if (!fullPath.StartsWith(normalizedDestination, PathUtility.GetStringComparisonBasedOnOS()) || fullPath.Length == normalizedDestination.Length)
@@ -563,6 +573,9 @@ protected static void ValidatePackageEntry(string normalizedDestination, string
563573
packageIdentity,
564574
normalizedFilePath));
565575
}
576+
577+
// Use the checked path for extraction rather than recombining the untrusted entry path.
578+
return fullPath;
566579
}
567580

568581
protected string NormalizeDirectoryPath(string path)

‎src/nuget-client/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1113,11 +1113,15 @@ private void CreatePackageDownloadMarkerFile(string nupkgFilePath)
11131113

11141114
private static string GetTemporaryDirectoryPath()
11151115
{
1116+
#if NETCOREAPP
1117+
return Directory.CreateTempSubdirectory("NuGet-").FullName;
1118+
#else
11161119
var tempDirectoryPath = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), Path.GetRandomFileName());
11171120

11181121
Directory.CreateDirectory(tempDirectoryPath);
11191122

11201123
return tempDirectoryPath;
1124+
#endif
11211125
}
11221126

11231127
public override Task<PrimarySignature?> GetPrimarySignatureAsync(CancellationToken token)

‎src/nuget-client/src/NuGet.Core/NuGet.Protocol/SourceCacheContext.cs‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
using System;
55
using System.Diagnostics;
66
using System.IO;
7-
using System.Threading;
7+
#if !NET7_0_OR_GREATER
88
using NuGet.Common;
9+
#endif
910

1011
namespace NuGet.Protocol.Core.Types
1112
{
@@ -18,6 +19,7 @@ public class SourceCacheContext : IDisposable
1819
/// Path of temp folder if requested by GeneratedTempFolder
1920
/// </summary>
2021
private string? _generatedTempFolder;
22+
private readonly object _generatedTempFolderLock = new object();
2123

2224
/// <summary>
2325
/// Default amount of time to cache version lists.
@@ -97,19 +99,30 @@ public virtual string GeneratedTempFolder
9799
{
98100
get
99101
{
100-
if (_generatedTempFolder == null)
102+
lock (_generatedTempFolderLock)
101103
{
102-
var newTempFolder = Path.Combine(
103-
NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp),
104-
Guid.NewGuid().ToString());
104+
if (_generatedTempFolder == null)
105+
{
106+
#if NET7_0_OR_GREATER
107+
_generatedTempFolder = Directory.CreateTempSubdirectory("NuGet-").FullName;
108+
#else
109+
_generatedTempFolder = Path.Combine(
110+
NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp),
111+
Guid.NewGuid().ToString());
112+
#endif
113+
}
105114

106-
Interlocked.CompareExchange(ref _generatedTempFolder, newTempFolder, comparand: null);
115+
return _generatedTempFolder;
107116
}
108-
109-
return _generatedTempFolder;
110117
}
111118

112-
set => Interlocked.CompareExchange(ref _generatedTempFolder, value, comparand: null);
119+
set
120+
{
121+
lock (_generatedTempFolderLock)
122+
{
123+
_generatedTempFolder ??= value;
124+
}
125+
}
113126
}
114127

115128
public bool IgnoreFailedSources { get; set; }
@@ -128,7 +141,10 @@ public virtual SourceCacheContext Clone()
128141
RefreshMemoryCache = RefreshMemoryCache,
129142
SessionId = SessionId
130143
};
131-
clone._generatedTempFolder = _generatedTempFolder;
144+
lock (_generatedTempFolderLock)
145+
{
146+
clone._generatedTempFolder = _generatedTempFolder;
147+
}
132148
return clone;
133149
}
134150

@@ -154,7 +170,11 @@ public void Dispose()
154170

155171
protected virtual void Dispose(bool disposing)
156172
{
157-
var currentTempFolder = Interlocked.CompareExchange(ref _generatedTempFolder, value: null, comparand: null);
173+
string? currentTempFolder;
174+
lock (_generatedTempFolderLock)
175+
{
176+
currentTempFolder = _generatedTempFolder;
177+
}
158178

159179
if (currentTempFolder != null)
160180
{

‎src/nuget-client/test/NuGet.Clients.Tests/NuGet.CommandLine.Test/RestoreNETCoreTest.cs‎

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -9706,49 +9706,6 @@ public void RestoreNetCore_WithMultipleFrameworksWithPlatformAndAssetTargetFallb
97069706
}
97079707
}
97089708

9709-
[PlatformFact(Platform.Windows)]
9710-
public async Task RestoreNetCore_WithCustomAliases_WritesConditionWithCorrectAlias()
9711-
{
9712-
// Arrange
9713-
using (var pathContext = new SimpleTestPathContext())
9714-
{
9715-
// Set up solution, project, and packages
9716-
var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
9717-
9718-
var packageX = new SimpleTestPackageContext()
9719-
{
9720-
Id = "x",
9721-
Version = "1.0.0"
9722-
};
9723-
9724-
var projects = new List<SimpleTestProjectContext>();
9725-
9726-
var project = SimpleTestProjectContext.CreateNETCoreWithSDK(
9727-
"proj",
9728-
pathContext.SolutionRoot,
9729-
$"net10.0-windows");
9730-
9731-
project.AddPackageToAllFrameworks(packageX);
9732-
solution.Projects.Add(project);
9733-
solution.Create();
9734-
9735-
await SimpleTestPackageUtility.CreateFolderFeedV3Async(
9736-
pathContext.PackageSource,
9737-
PackageSaveMode.Defaultv3,
9738-
packageX);
9739-
9740-
// Act
9741-
var r = Util.RestoreSolution(pathContext, testOutputHelper: _testOutputHelper);
9742-
Assert.Equal(0, r.ExitCode);
9743-
Assert.True(File.Exists(project.PropsOutput), r.Output);
9744-
var propsXML = XDocument.Parse(File.ReadAllText(project.PropsOutput));
9745-
9746-
var propsItemGroups = propsXML.Root.Elements().Where(e => e.Name.LocalName == "ItemGroup").ToList();
9747-
9748-
Assert.Contains($"'$(TargetFramework)' == 'net10.0-windows' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim());
9749-
}
9750-
}
9751-
97529709
[Fact]
97539710
public async Task RestoreNetCore_CPVMProject_TransitiveDependenciesAreNotPinned()
97549711
{

0 commit comments

Comments
 (0)