Skip to content

Commit

Permalink
Remove manual home variable lookup (#46349)
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperk81 authored Jan 29, 2025
1 parent bb9c0fd commit 7d3013e
Show file tree
Hide file tree
Showing 13 changed files with 25 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ public static string WindowsNonExpandedToolsShimPath

public static string ToolsResolverCachePath => Path.Combine(DotnetUserProfileFolderPath, ToolsResolverCacheFolderName);

public static string PlatformHomeVariableName => CliFolderPathCalculatorCore.PlatformHomeVariableName;

public static string DotnetHomePath
{
get
Expand Down
9 changes: 1 addition & 8 deletions src/Cli/Microsoft.TemplateEngine.Cli/Commands/CliPathInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public CliPathInfo(
throw new ArgumentException($"{nameof(host.Version)} of {nameof(host)} cannot be null or whitespace.", nameof(host));
}

UserProfileDir = GetUserProfileDir(environment);
UserProfileDir = CliFolderPathCalculator.DotnetHomePath;
GlobalSettingsDir = GetGlobalSettingsDir(settingsLocation);
HostSettingsDir = Path.Combine(GlobalSettingsDir, host.HostIdentifier);
HostVersionSettingsDir = Path.Combine(GlobalSettingsDir, host.HostIdentifier, host.Version);
Expand All @@ -38,13 +38,6 @@ public CliPathInfo(

public string HostVersionSettingsDir { get; }

private static string GetUserProfileDir(IEnvironment environment) => environment.GetEnvironmentVariable(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "USERPROFILE"
: "HOME")
?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
?? throw new NotSupportedException("HOME or USERPROFILE environment variable is not defined, the environment is not supported");

private static string GetGlobalSettingsDir(string? settingsLocation)
{
var definedSettingsLocation = string.IsNullOrWhiteSpace(settingsLocation)
Expand Down
5 changes: 3 additions & 2 deletions src/Cli/dotnet/SudoEnvironmentDirectoryOverride.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Configurer;
using NuGet.Common;
using NuGet.Configuration;

Expand Down Expand Up @@ -32,8 +33,8 @@ public static void OverrideEnvironmentVariableToTmp(ParseResult parseResult)
if (!OperatingSystem.IsWindows() && IsRunningUnderSudo() && IsRunningWorkloadCommand(parseResult))
{
string sudoHome = PathUtilities.CreateTempSubdirectory();
var homeBeforeOverride = Path.Combine(Environment.GetEnvironmentVariable("HOME"));
Environment.SetEnvironmentVariable("HOME", sudoHome);
var homeBeforeOverride = Path.Combine(Environment.GetEnvironmentVariable(CliFolderPathCalculator.DotnetHomeVariableName));
Environment.SetEnvironmentVariable(CliFolderPathCalculator.DotnetHomeVariableName, sudoHome);

CopyUserNuGetConfigToOverriddenHome(homeBeforeOverride);
}
Expand Down
10 changes: 2 additions & 8 deletions src/Common/CliFolderPathCalculatorCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ static class CliFolderPathCalculatorCore
{
public const string DotnetHomeVariableName = "DOTNET_CLI_HOME";
public const string DotnetProfileDirectoryName = ".dotnet";
public static readonly string PlatformHomeVariableName =
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "USERPROFILE" : "HOME";

public static string? GetDotnetUserProfileFolderPath()
{
Expand All @@ -26,14 +24,10 @@ static class CliFolderPathCalculatorCore
var home = Environment.GetEnvironmentVariable(DotnetHomeVariableName);
if (string.IsNullOrEmpty(home))
{
home = Environment.GetEnvironmentVariable(PlatformHomeVariableName);
home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if (string.IsNullOrEmpty(home))
{
home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if (string.IsNullOrEmpty(home))
{
return null;
}
return null;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#nullable disable

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Extensions.DependencyModel;
using Microsoft.NET.Build.Tasks;
using Newtonsoft.Json.Linq;
Expand Down Expand Up @@ -167,7 +168,8 @@ private void It_targets_the_right_framework(

var additionalProbingPaths = ((JArray)devruntimeConfig["runtimeOptions"]["additionalProbingPaths"]).Values<string>();
// can't use Path.Combine on segments with an illegal `|` character
var expectedPath = $"{Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "store")}{Path.DirectorySeparatorChar}|arch|{Path.DirectorySeparatorChar}|tfm|";
var homePath = Environment.GetEnvironmentVariable(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "USERPROFILE" : "HOME");
var expectedPath = $"{Path.Combine(homePath, ".dotnet", "store")}{Path.DirectorySeparatorChar}|arch|{Path.DirectorySeparatorChar}|tfm|";
additionalProbingPaths.Should().Contain(expectedPath);
}

Expand Down Expand Up @@ -269,7 +271,7 @@ public void It_runs_the_app_from_the_output_folder(string targetFramework)
[InlineData("net7.0")]
[InlineData(ToolsetInfo.CurrentTargetFramework)]
public void It_runs_a_rid_specific_app_from_the_output_folder(string targetFramework)
{
{
RunAppFromOutputFolder("RunFromOutputFolderWithRID_" + targetFramework, true, false, targetFramework);
}

Expand Down Expand Up @@ -1001,7 +1003,7 @@ public void It_warns_on_nonportable_rids(string targetFramework, string[] rids,
IsExe = true
};

// Reference the package, add it to restore sources, and use a test-specific packages folder
// Reference the package, add it to restore sources, and use a test-specific packages folder
testProject.PackageReferences.Add(package);
testProject.AdditionalProperties["RestoreAdditionalProjectSources"] = Path.GetDirectoryName(package.NupkgPath);
testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\packages";
Expand Down Expand Up @@ -1054,7 +1056,7 @@ public void It_does_not_warn_on_rids_if_no_framework_references()
IsExe = true
};

// Reference the package, add it to restore sources, and use a test-specific packages folder
// Reference the package, add it to restore sources, and use a test-specific packages folder
testProject.PackageReferences.Add(package);
testProject.AdditionalProperties["RestoreAdditionalProjectSources"] = Path.GetDirectoryName(package.NupkgPath);
testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\packages";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

#nullable disable
using Microsoft.DotNet.Configurer;

namespace Microsoft.NET.Build.Tests
{
Expand Down Expand Up @@ -258,7 +259,7 @@ public void It_resolves_multitargeted_analyzers()
static readonly List<string> nugetRoots = new()
{
TestContext.Current.NuGetCachePath,
Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "NuGetFallbackFolder"),
Path.Combine(CliFolderPathCalculator.DotnetHomePath, ".dotnet", "NuGetFallbackFolder"),
Path.Combine(TestContext.Current.ToolsetUnderTest.DotNetRoot, "packs")
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@
<ItemGroup>
<!-- Make sure tasks project is built, but don't directly reference it as an assembly. -->
<ProjectReference Include="..\..\src\Tasks\Microsoft.NET.Build.Tasks\Microsoft.NET.Build.Tasks.csproj" PrivateAssets="all" ReferenceOutputAssembly="false" />

<ProjectReference Include="..\Microsoft.NET.TestFramework\Microsoft.NET.TestFramework.csproj" />
<ProjectReference Include="..\TelemetryStdOutLogger\TelemetryStdOutLogger.csproj" />
<ProjectReference Include="..\..\src\Cli\Microsoft.DotNet.Configurer\Microsoft.DotNet.Configurer.csproj" />
</ItemGroup>

<ItemGroup>
Expand All @@ -53,5 +54,5 @@
</ItemGroup>

<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />

</Project>
3 changes: 0 additions & 3 deletions test/Microsoft.NET.TestFramework/FileConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,5 @@ public static class FileConstants

public static readonly string DynamicLibSuffix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".dll" :
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? ".dylib" : ".so";
public static readonly string? UserProfileFolder = Environment.GetEnvironmentVariable(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
"USERPROFILE" : "HOME");
}
}
3 changes: 2 additions & 1 deletion test/dotnet-build.Tests/GivenDotnetBuildBuildsCsproj.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#nullable disable

using System.CommandLine;
using Microsoft.DotNet.Configurer;

namespace Microsoft.DotNet.Cli.Build.Tests
{
Expand Down Expand Up @@ -379,7 +380,7 @@ public void It_resolves_analyzers_targeting_mulitple_roslyn_versions(string comp
static readonly List<string> nugetRoots = new()
{
TestContext.Current.NuGetCachePath,
Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "NuGetFallbackFolder")
Path.Combine(CliFolderPathCalculator.DotnetHomePath, ".dotnet", "NuGetFallbackFolder")
};

static string RelativeNuGetPath(string absoluteNuGetPath)
Expand Down
3 changes: 2 additions & 1 deletion test/dotnet-new.Tests/DotnetNewDebugOptionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Configurer;

namespace Microsoft.DotNet.Cli.New.IntegrationTests
{
Expand Down Expand Up @@ -93,7 +94,7 @@ public Task CanShowConfigWithDebugShowConfig()
public void DoesNotCreateCacheWhenVirtualHiveIsUsed()
{
string home = CreateTemporaryFolder(folderName: "Home");
string envVariable = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "USERPROFILE" : "HOME";
string envVariable = CliFolderPathCalculator.DotnetHomePath;

new DotnetNewCommand(_log, "--debug:ephemeral-hive")
.WithoutCustomHive()
Expand Down
3 changes: 2 additions & 1 deletion test/dotnet.Tests/GivenThatDotNetRunsCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#nullable disable

using System.Runtime.InteropServices;
using Microsoft.DotNet.Configurer;
using LocalizableStrings = Microsoft.DotNet.Cli.Utils.LocalizableStrings;

Expand Down Expand Up @@ -39,7 +40,7 @@ public void UnresolvedPlatformReferencesFailAsExpected()
public void GivenAMissingHomeVariableItExecutesHelpCommandSuccessfully(string value)
{
new DotnetCommand(Log)
.WithEnvironmentVariable(CliFolderPathCalculator.PlatformHomeVariableName, value)
.WithEnvironmentVariable(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "USERPROFILE" : "HOME", value)
.WithEnvironmentVariable(CliFolderPathCalculator.DotnetHomeVariableName, "")
.Execute("--help")
.Should()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,12 @@ public TestCommand Setup(ITestOutputHelper log, TestAssetsManager testAssets, [C

var command = new DotnetCommand(log)
.WithWorkingDirectory(TestDirectory)
.WithEnvironmentVariable("HOME", testNuGetHome)
.WithEnvironmentVariable("USERPROFILE", testNuGetHome)
.WithEnvironmentVariable("APPDATA", testNuGetHome)
.WithEnvironmentVariable("DOTNET_CLI_TEST_FALLBACKFOLDER", cliTestFallbackFolder)
.WithEnvironmentVariable("DOTNET_CLI_TEST_LINUX_PROFILED_PATH", profiled)
.WithEnvironmentVariable("DOTNET_CLI_TEST_OSX_PATHSD_PATH", pathsd)
.WithEnvironmentVariable("SkipInvalidConfigurations", "true")
.WithEnvironmentVariable(CliFolderPathCalculator.DotnetHomeVariableName, "");
.WithEnvironmentVariable(CliFolderPathCalculator.DotnetHomeVariableName, testNuGetHome);

NugetFallbackFolder = new DirectoryInfo(cliTestFallbackFolder);
DotDotnetFolder = new DirectoryInfo(Path.Combine(testNuGetHome, ".dotnet"));
Expand Down
10 changes: 1 addition & 9 deletions test/dotnet.Tests/TestCommandExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,7 @@ public static class TestCommandExtensions
{
public static TestCommand WithUserProfileRoot(this TestCommand testCommand, string path)
{
var userProfileEnvironmentVariableName = GetUserProfileEnvironmentVariableName();
return testCommand.WithEnvironmentVariable(userProfileEnvironmentVariableName, path);
}

private static string GetUserProfileEnvironmentVariableName()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "LocalAppData"
: "HOME";
return testCommand.WithEnvironmentVariable("DOTNET_CLI_HOME", path);
}
}
}

0 comments on commit 7d3013e

Please sign in to comment.