Fix application crashes if there are two environment variables with same name, differing only in case (#67)

This commit is contained in:
Ron Myers
2020-07-28 08:20:02 -03:00
committed by GitHub
parent b491818779
commit 9a20101f30
4 changed files with 28 additions and 5 deletions

View File

@@ -206,7 +206,7 @@ namespace CliFx.Analyzers
// Duplicate environment variable name
var duplicateEnvironmentVariableNameOptions = options
.Where(p => !string.IsNullOrWhiteSpace(p.EnvironmentVariableName))
.GroupBy(p => p.EnvironmentVariableName, StringComparer.OrdinalIgnoreCase)
.GroupBy(p => p.EnvironmentVariableName, StringComparer.Ordinal)
.Where(g => g.Count() > 1)
.SelectMany(g => g.AsEnumerable())
.ToArray();

View File

@@ -89,5 +89,27 @@ namespace CliFx.Tests
Option = $"foo{Path.PathSeparator}bar"
});
}
[Fact]
public void Option_can_use_a_specific_environment_variable_as_fallback_while_respecting_case()
{
// Arrange
const string expected = "foobar";
var input = CommandInput.Empty;
var envVars = new Dictionary<string, string>
{
["ENV_OPT"] = expected,
["env_opt"] = "2"
};
// Act
var instance = CommandHelper.ResolveCommand<EnvironmentVariableCommand>(input, envVars);
// Assert
instance.Should().BeEquivalentTo(new EnvironmentVariableCommand
{
Option = expected
});
}
}
}

View File

@@ -218,9 +218,10 @@ namespace CliFx
/// </remarks>
public async ValueTask<int> RunAsync(IReadOnlyList<string> commandLineArguments)
{
// Environment variable names are case-insensitive on Windows but are case-sensitive on Linux and macOS
var environmentVariables = Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.ToDictionary(e => (string) e.Key, e => (string) e.Value, StringComparer.OrdinalIgnoreCase);
.ToDictionary(e => (string) e.Key, e => (string) e.Value, StringComparer.Ordinal);
return await RunAsync(commandLineArguments, environmentVariables);
}

View File

@@ -45,7 +45,7 @@ namespace CliFx.Domain
public bool MatchesEnvironmentVariableName(string environmentVariableName) =>
!string.IsNullOrWhiteSpace(EnvironmentVariableName) &&
string.Equals(EnvironmentVariableName, environmentVariableName, StringComparison.OrdinalIgnoreCase);
string.Equals(EnvironmentVariableName, environmentVariableName, StringComparison.Ordinal);
public string GetUserFacingDisplayString()
{