Skip to content
71 changes: 30 additions & 41 deletions src/System.Management.Automation/engine/CommandDiscovery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1199,63 +1199,57 @@ internal void UnregisterLookupCommandInfoAction(string currentAction, string com
/// </remarks>
internal LookupPathCollection GetLookupDirectoryPaths()
{
LookupPathCollection result = new LookupPathCollection();

string path = Environment.GetEnvironmentVariable("PATH");
discoveryTracer.WriteLine("PATH: {0}", path);

discoveryTracer.WriteLine(
"PATH: {0}",
path);

bool isPathCacheValid =
path != null &&
string.Equals(_pathCacheKey, path, StringComparison.OrdinalIgnoreCase) &&
_cachedPath != null;
bool isPathCacheValid = _cachedLookupPaths is not null
&& string.Equals(_pathCacheKey, path, StringComparison.OrdinalIgnoreCase);

if (!isPathCacheValid)
{
// Reset the cached lookup paths
_pathCacheKey = null;
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
_cachedLookupPaths = null;

// Tokenize the path and cache it

_pathCacheKey = path;

if (_pathCacheKey != null)
if (path is null)
{
// Cache an empty collection when PATH is null (unset).
_cachedLookupPaths = new LookupPathCollection();
}
else
{
// Tokenize the path and cache it
_pathCacheKey = path;
string[] tokenizedPath = _pathCacheKey.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
_cachedPath = new Collection<string>();
List<string> pathList = new(capacity: tokenizedPath.Length);

foreach (string directory in tokenizedPath)
{
string tempDir = directory.TrimStart();
if (tempDir.EqualsOrdinalIgnoreCase("~"))
string tempDir = directory.Trim();
if (tempDir.StartsWith('~'))
{
tempDir = Environment.GetFolderPath(
string homeDir = Environment.GetFolderPath(
Environment.SpecialFolder.UserProfile,
Environment.SpecialFolderOption.DoNotVerify);
}
else if (tempDir.StartsWith("~" + Path.DirectorySeparatorChar))
{
tempDir = Environment.GetFolderPath(
Environment.SpecialFolder.UserProfile,
Environment.SpecialFolderOption.DoNotVerify)
+ Path.DirectorySeparatorChar
+ tempDir.Substring(2);

if (tempDir.Length is 1)
{
tempDir = homeDir;
}
else if (tempDir[1] == Path.DirectorySeparatorChar)
{
tempDir = $"{homeDir}{Path.DirectorySeparatorChar}{tempDir.AsSpan(2)}";
}
}

_cachedPath.Add(tempDir);
result.Add(tempDir);
pathList.Add(tempDir);
}

// Cache the new lookup paths.
_cachedLookupPaths = new LookupPathCollection(pathList);
}
}
else
{
result.AddRange(_cachedPath);
}

// Cache the new lookup paths
return _cachedLookupPaths ??= result;
return _cachedLookupPaths;
}

/// <summary>
Expand All @@ -1269,11 +1263,6 @@ internal LookupPathCollection GetLookupDirectoryPaths()
/// </summary>
private string _pathCacheKey;

/// <summary>
/// The cache of the tokenized PATH directories.
/// </summary>
private Collection<string> _cachedPath;

#endregion internal members

#region environment variable helpers
Expand Down
Loading