Skip to content

(#3675) Extract all used environment variables #3241

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Chocolatey.PowerShell/Chocolatey.PowerShell.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="..\chocolatey\StringResources.cs">
<Link>Shared\StringResources.cs</Link>
</Compile>
<Compile Include="Commands\GetEnvironmentVariableCommand.cs" />
<Compile Include="Commands\GetEnvironmentVariableNamesCommand.cs" />
<Compile Include="Commands\InstallChocolateyPathCommand.cs" />
Expand All @@ -75,6 +78,7 @@
<Link>Properties\SolutionVersion.cs</Link>
</Compile>
<Compile Include="Shared\ChocolateyCmdlet.cs" />
<Compile Include="Shared\EnvironmentNames.cs" />
<Compile Include="Shared\EnvironmentVariables.cs" />
<Compile Include="Win32\NativeMethods.cs" />
</ItemGroup>
Expand Down
30 changes: 15 additions & 15 deletions src/Chocolatey.PowerShell/Helpers/EnvironmentHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Chocolatey.PowerShell.Shared;
using Chocolatey.PowerShell.Win32;
using Microsoft.Win32;
using static chocolatey.StringResources;

namespace Chocolatey.PowerShell.Helpers
{
Expand Down Expand Up @@ -163,7 +163,7 @@ public static void SetVariable(PSCmdlet cmdlet, string name, EnvironmentVariable
// The value doesn't exist yet, suppress the error.
}

if (name.ToUpper() == EnvironmentVariables.Path)
if (name.ToUpper() == EnvironmentVariables.System.Path)
{
registryType = RegistryValueKind.ExpandString;
}
Expand Down Expand Up @@ -199,8 +199,8 @@ public static void SetVariable(PSCmdlet cmdlet, string name, EnvironmentVariable
out UIntPtr result);

// 2. Set a user environment variable making the system refresh
var setxPath = string.Format(@"{0}\System32\setx.exe", GetVariable(cmdlet, EnvironmentVariables.SystemRoot, EnvironmentVariableTarget.Process));
cmdlet.InvokeCommand.InvokeScript($"& \"{setxPath}\" {EnvironmentVariables.ChocolateyLastPathUpdate} \"{DateTime.Now.ToFileTime()}\"");
var setxPath = string.Format(@"{0}\System32\setx.exe", GetVariable(cmdlet, EnvironmentVariables.System.SystemRoot, EnvironmentVariableTarget.Process));
cmdlet.InvokeCommand.InvokeScript($"& \"{setxPath}\" {EnvironmentVariables.Package.ChocolateyLastPathUpdate} \"{DateTime.Now.ToFileTime()}\"");
}
}
catch (Exception error)
Expand All @@ -217,16 +217,16 @@ public static void SetVariable(PSCmdlet cmdlet, string name, EnvironmentVariable
/// <param name="cmdlet">The cmdlet calling the method.</param>
public static void UpdateSession(PSCmdlet cmdlet)
{
var userName = GetVariable(cmdlet, EnvironmentVariables.Username, EnvironmentVariableTarget.Process);
var architecture = GetVariable(cmdlet, EnvironmentVariables.ProcessorArchitecture, EnvironmentVariableTarget.Process);
var psModulePath = GetVariable(cmdlet, EnvironmentVariables.PSModulePath, EnvironmentVariableTarget.Process);
var userName = GetVariable(cmdlet, EnvironmentVariables.System.Username, EnvironmentVariableTarget.Process);
var architecture = GetVariable(cmdlet, EnvironmentVariables.System.ProcessorArchitecture, EnvironmentVariableTarget.Process);
var psModulePath = GetVariable(cmdlet, EnvironmentVariables.System.PSModulePath, EnvironmentVariableTarget.Process);

var scopeList = new List<EnvironmentVariableTarget>() { EnvironmentVariableTarget.Process, EnvironmentVariableTarget.Machine };

var computerName = GetVariable(cmdlet, EnvironmentVariables.ComputerName, EnvironmentVariableTarget.Process);
var computerName = GetVariable(cmdlet, EnvironmentVariables.System.ComputerName, EnvironmentVariableTarget.Process);

// User scope should override (be checked after) machine scope, but only if we're not running as SYSTEM
if (userName != computerName && userName != EnvironmentVariables.System)
if (userName != computerName && userName != Shared.EnvironmentNames.System)
{
scopeList.Add(EnvironmentVariableTarget.User);
}
Expand All @@ -247,23 +247,23 @@ public static void UpdateSession(PSCmdlet cmdlet)

// Update PATH, combining both scopes' values.
var paths = new string[2];
paths[0] = GetVariable(cmdlet, EnvironmentVariables.Path, EnvironmentVariableTarget.Machine);
paths[1] = GetVariable(cmdlet, EnvironmentVariables.Path, EnvironmentVariableTarget.User);
paths[0] = GetVariable(cmdlet, EnvironmentVariables.System.Path, EnvironmentVariableTarget.Machine);
paths[1] = GetVariable(cmdlet, EnvironmentVariables.System.Path, EnvironmentVariableTarget.User);

SetVariable(cmdlet, EnvironmentVariables.Path, EnvironmentVariableTarget.Process, string.Join(";", paths));
SetVariable(cmdlet, EnvironmentVariables.System.Path, EnvironmentVariableTarget.Process, string.Join(";", paths));

// Preserve PSModulePath as it's almost always updated by process, preserve it
SetVariable(cmdlet, EnvironmentVariables.PSModulePath, EnvironmentVariableTarget.Process, psModulePath);
SetVariable(cmdlet, EnvironmentVariables.System.PSModulePath, EnvironmentVariableTarget.Process, psModulePath);

// Preserve user and architecture
if (!string.IsNullOrEmpty(userName))
{
SetVariable(cmdlet, EnvironmentVariables.Username, EnvironmentVariableTarget.Process, userName);
SetVariable(cmdlet, EnvironmentVariables.System.Username, EnvironmentVariableTarget.Process, userName);
}

if (!string.IsNullOrEmpty(architecture))
{
SetVariable(cmdlet, EnvironmentVariables.ProcessorArchitecture, EnvironmentVariableTarget.Process, architecture);
SetVariable(cmdlet, EnvironmentVariables.System.ProcessorArchitecture, EnvironmentVariableTarget.Process, architecture);
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/Chocolatey.PowerShell/Helpers/Paths.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
using System.Management.Automation;
using System.Text;
using System.Text.RegularExpressions;
using Chocolatey.PowerShell.Shared;
using static chocolatey.StringResources;

namespace Chocolatey.PowerShell.Helpers
{
Expand Down Expand Up @@ -106,7 +106,7 @@ internal static string GetPathString(IList<string> paths)
/// <param name="scope">The target scope of the PATH variable to modify.</param>
public static void InstallPathEntry(PSCmdlet cmdlet, string pathEntry, EnvironmentVariableTarget scope)
{
var pathEntries = new List<string>(ParsePathString(EnvironmentHelper.GetVariable(cmdlet, EnvironmentVariables.Path, scope, preserveVariables: true)));
var pathEntries = new List<string>(ParsePathString(EnvironmentHelper.GetVariable(cmdlet, EnvironmentVariables.System.Path, scope, preserveVariables: true)));
if (FindPathIndex(pathEntries, pathEntry) == -1)
{
PSHelper.WriteHost(cmdlet, $"PATH environment variable does not have {pathEntry} in it. Adding...");
Expand All @@ -116,7 +116,7 @@ public static void InstallPathEntry(PSCmdlet cmdlet, string pathEntry, Environme

void updatePath()
{
EnvironmentHelper.SetVariable(cmdlet, EnvironmentVariables.Path, scope, newPath);
EnvironmentHelper.SetVariable(cmdlet, EnvironmentVariables.System.Path, scope, newPath);
}

if (scope == EnvironmentVariableTarget.Machine)
Expand All @@ -138,7 +138,7 @@ void updatePath()
/// <param name="scope">The target scope of the PATH variable to modify.</param>
public static void UninstallPathEntry(PSCmdlet cmdlet, string pathEntry, EnvironmentVariableTarget scope)
{
var pathEntries = new List<string>(ParsePathString(EnvironmentHelper.GetVariable(cmdlet, EnvironmentVariables.Path, scope, preserveVariables: true)));
var pathEntries = new List<string>(ParsePathString(EnvironmentHelper.GetVariable(cmdlet, EnvironmentVariables.System.Path, scope, preserveVariables: true)));
var removeIndex = FindPathIndex(pathEntries, pathEntry);
if (removeIndex >= 0)
{
Expand All @@ -149,7 +149,7 @@ public static void UninstallPathEntry(PSCmdlet cmdlet, string pathEntry, Environ

void updatePath()
{
EnvironmentHelper.SetVariable(cmdlet, EnvironmentVariables.Path, scope, newPath);
EnvironmentHelper.SetVariable(cmdlet, EnvironmentVariables.System.Path, scope, newPath);
}

if (scope == EnvironmentVariableTarget.Machine)
Expand Down
23 changes: 23 additions & 0 deletions src/Chocolatey.PowerShell/Shared/EnvironmentNames.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright © 2017 - 2025 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Chocolatey.PowerShell.Shared
{
public static class EnvironmentNames
{
public const string System = "SYSTEM";
}
}
22 changes: 14 additions & 8 deletions src/Chocolatey.PowerShell/Shared/EnvironmentVariables.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,23 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using chocolatey;

namespace Chocolatey.PowerShell.Shared
{

[Obsolete("This class has been deprecated, make use of chocolatey.StringResources.EnvironmentVariables instead.", error: false)]
public static class EnvironmentVariables
{
public const string ChocolateyLastPathUpdate = "ChocolateyLastPathUpdate";
public const string ComputerName = "COMPUTERNAME";
public const string Path = "PATH";
public const string ProcessorArchitecture = "PROCESSOR_ARCHITECTURE";
public const string PSModulePath = "PSModulePath";
public const string System = "SYSTEM";
public const string SystemRoot = "SystemRoot";
public const string Username = "USERNAME";
public const string ChocolateyLastPathUpdate = StringResources.EnvironmentVariables.Package.ChocolateyLastPathUpdate;
public const string ComputerName = StringResources.EnvironmentVariables.System.ComputerName;
public const string Path = StringResources.EnvironmentVariables.System.Path;
public const string ProcessorArchitecture = StringResources.EnvironmentVariables.System.ProcessorArchitecture;
public const string PSModulePath = StringResources.EnvironmentVariables.System.PSModulePath;
[Obsolete("This constant has been replaced by EnvironmentNames.System.")]
public const string System = EnvironmentNames.System;
public const string SystemRoot = StringResources.EnvironmentVariables.System.SystemRoot;
public const string Username = StringResources.EnvironmentVariables.System.Username;
}
}
10 changes: 10 additions & 0 deletions src/chocolatey.console/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,18 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("2f406051-3fe2-45f4-97bf-40968b86c5a9")]

// We allow the officially built chocolatey.extension to always see the internals.
[assembly: InternalsVisibleTo("chocolatey.licensed, PublicKey=002400000480000094000000060200000024000052534131000400000100010001f55d4a9065e32d5e9854e592ffa5f7b3a707f55a17796937faf70f3ade21346dcf735216015d20304acd25d260d01202a390ac648ace0e93f6c4d6ac7cbede5b3e8f66e536d03ffa2d09594ac8de7bd147419c17e0fa1fa112b81b1b65a9e8b0ca148dc3a77e7b2917f448455ce9dbad266351710d097424692be8854704e8")]
[assembly: InternalsVisibleTo("chocolatey.interfaces, PublicKey=002400000480000094000000060200000024000052534131000400000100010001f55d4a9065e32d5e9854e592ffa5f7b3a707f55a17796937faf70f3ade21346dcf735216015d20304acd25d260d01202a390ac648ace0e93f6c4d6ac7cbede5b3e8f66e536d03ffa2d09594ac8de7bd147419c17e0fa1fa112b81b1b65a9e8b0ca148dc3a77e7b2917f448455ce9dbad266351710d097424692be8854704e8")]

#if !FORCE_CHOCOLATEY_OFFICIAL_KEY
[assembly: InternalsVisibleTo("chocolatey.licensed, PublicKey=00240000048000009400000006020000002400005253413100040000010001003f70732af6adf3f525d983852cc7049878c498e4f8a413bd7685c9edc503ed6c6e4087354c7c1797b7c9f6d9bd3c25cdd5f97b0e810b7dd1aaba2e489f60d17d1f03c0f4db27c63146ee64ce797e4c92d591a750d8c342f5b67775710f6f9b3d9d10b4121522779a1ff72776bcce3962ca66f1755919972fb70ffb289bc082b3")]
[assembly: InternalsVisibleTo("chocolatey.interfaces, PublicKey=00240000048000009400000006020000002400005253413100040000010001003f70732af6adf3f525d983852cc7049878c498e4f8a413bd7685c9edc503ed6c6e4087354c7c1797b7c9f6d9bd3c25cdd5f97b0e810b7dd1aaba2e489f60d17d1f03c0f4db27c63146ee64ce797e4c92d591a750d8c342f5b67775710f6f9b3d9d10b4121522779a1ff72776bcce3962ca66f1755919972fb70ffb289bc082b3")]
#endif
Binary file added src/chocolatey.tests.integration/TestKey.snk
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>TestKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="AnyOf, Version=0.3.0.0, Culture=neutral, PublicKeyToken=b35e6abbb527c6b1, processorArchitecture=MSIL">
<HintPath>..\packages\AnyOf.0.3.0\lib\net45\AnyOf.dll</HintPath>
Expand Down Expand Up @@ -493,6 +499,7 @@
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
<None Include="TestKey.snk" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\chocolatey.tests\chocolatey.tests.csproj">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
using Microsoft.Win32;
using chocolatey.tests.integration.scenarios;
using FluentAssertions;
using static chocolatey.StringResources;

namespace chocolatey.tests.integration.infrastructure.app.builders
{
Expand Down Expand Up @@ -116,11 +117,11 @@ public override void Context()

if (EnvironmentVariableSet)
{
Environment.Setup(e => e.GetEnvironmentVariable(It.IsIn("http_proxy", "https_proxy"))).Returns(EnvironmentVariableProxyValue);
Environment.Setup(e => e.GetEnvironmentVariable(It.IsIn(EnvironmentVariables.System.HttpProxy, EnvironmentVariables.System.HttpsProxy))).Returns(EnvironmentVariableProxyValue);
}
else
{
Environment.Setup(e => e.GetEnvironmentVariable(It.IsIn("http_proxy", "https_proxy"))).Returns(string.Empty);
Environment.Setup(e => e.GetEnvironmentVariable(It.IsIn(EnvironmentVariables.System.HttpProxy, EnvironmentVariables.System.HttpsProxy))).Returns(string.Empty);
}

if (ConfigSet)
Expand Down Expand Up @@ -192,11 +193,11 @@ public override void Context()

if (EnvironmentVariableSet)
{
Environment.Setup(e => e.GetEnvironmentVariable("no_proxy")).Returns(EnvironmentVariableProxyValue);
Environment.Setup(e => e.GetEnvironmentVariable(EnvironmentVariables.System.NoProxy)).Returns(EnvironmentVariableProxyValue);
}
else
{
Environment.Setup(e => e.GetEnvironmentVariable("no_proxy")).Returns(string.Empty);
Environment.Setup(e => e.GetEnvironmentVariable(EnvironmentVariables.System.NoProxy)).Returns(string.Empty);
}

if (ArgumentSet)
Expand Down
Binary file added src/chocolatey.tests/TestKey.snk
Binary file not shown.
7 changes: 4 additions & 3 deletions src/chocolatey.tests/TinySpec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
using chocolatey.infrastructure.logging;
using System.IO;
using chocolatey.infrastructure.app.nuget;
using static chocolatey.StringResources;

namespace chocolatey.tests
{
Expand All @@ -30,12 +31,12 @@ public class NUnitSetup
{
public static MockLogger MockLogger { get; set; }

private static readonly string _installLocationVariable = Environment.GetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName);
private static readonly string _installLocationVariable = Environment.GetEnvironmentVariable(EnvironmentVariables.System.ChocolateyInstall);

[OneTimeSetUp]
public virtual void BeforeEverything()
{
Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, string.Empty);
Environment.SetEnvironmentVariable(EnvironmentVariables.System.ChocolateyInstall, string.Empty);
MockLogger = new MockLogger();
Log.InitializeWith(MockLogger);
// do not log trace messages
Expand All @@ -46,7 +47,7 @@ public virtual void BeforeEverything()
[OneTimeTearDown]
public void AfterEverything()
{
Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, _installLocationVariable);
Environment.SetEnvironmentVariable(EnvironmentVariables.System.ChocolateyInstall, _installLocationVariable);
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/chocolatey.tests/chocolatey.tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>TestKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="Chocolatey.NuGet.Commands">
<HintPath>..\packages\Chocolatey.NuGet.Commands.3.4.3\lib\net472\Chocolatey.NuGet.Commands.dll</HintPath>
Expand Down Expand Up @@ -208,6 +214,7 @@
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
<None Include="TestKey.snk" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\chocolatey\chocolatey.csproj">
Expand Down
Loading
Loading