Skip to content

Commit b5efdd1

Browse files
authored
cache NuGetEnvironment.GetFolderPath values (#6874)
1 parent da03b38 commit b5efdd1

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/NuGet.Core/NuGet.Common/PathUtil/NuGetEnvironment.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#nullable disable
66

77
using System;
8+
using System.Collections.Concurrent;
89
using System.Globalization;
910
using System.IO;
1011
using System.Runtime.InteropServices;
@@ -26,6 +27,9 @@ public static class NuGetEnvironment
2627
private static readonly Lazy<string> _getHome = new Lazy<string>(() => GetHome());
2728

2829
private static string _nuGetTempDirectory = null;
30+
31+
private static readonly ConcurrentDictionary<NuGetFolderPath, string> Cache = new ConcurrentDictionary<NuGetFolderPath, string>();
32+
2933
internal static string NuGetTempDirectory
3034
{
3135
get { return _nuGetTempDirectory ??= GetNuGetTempDirectory(); }
@@ -65,6 +69,12 @@ private static string GetNuGetTempDirectory()
6569
}
6670

6771
public static string GetFolderPath(NuGetFolderPath folder)
72+
{
73+
string path = Cache.GetOrAdd(folder, CalculateFolderPath);
74+
return path;
75+
}
76+
77+
private static string CalculateFolderPath(NuGetFolderPath folder)
6878
{
6979
switch (folder)
7080
{

test/NuGet.Core.Tests/NuGet.Common.Test/NuGetEnvironmentTests.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) .NET Foundation. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

4+
using System.Collections.Generic;
45
using NuGet.Common.Migrations;
56
using NuGet.Test.Utility;
67
using Xunit;
@@ -15,5 +16,27 @@ public void GetFolderPath_Temp_Success()
1516
var nuGetTempDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp);
1617
Assert.Equal("700", Migration1.GetPermissions(nuGetTempDirectory).ToString());
1718
}
19+
20+
public static IEnumerable<object[]> AllNuGetFolderPaths()
21+
{
22+
foreach (NuGetFolderPath folderPath in (NuGetFolderPath[])System.Enum.GetValues(typeof(NuGetFolderPath)))
23+
{
24+
if (folderPath == NuGetFolderPath.DefaultMsBuildPath)
25+
{
26+
// Skip DefaultMsBuildPath as it throws on Mac and Linux
27+
continue;
28+
}
29+
yield return new object[] { folderPath };
30+
}
31+
}
32+
33+
[Theory]
34+
[MemberData(nameof(AllNuGetFolderPaths))]
35+
public void GetFolderPath_MultipleCalls_ReturnsCachedInstance(NuGetFolderPath folder)
36+
{
37+
var firstCall = NuGetEnvironment.GetFolderPath(folder);
38+
var secondCall = NuGetEnvironment.GetFolderPath(folder);
39+
Assert.Same(firstCall, secondCall);
40+
}
1841
}
1942
}

0 commit comments

Comments
 (0)