Skip to content
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

Add -e option to dotnet run #45795

Merged
merged 7 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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
19 changes: 19 additions & 0 deletions src/Cli/dotnet/CommonLocalizableStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,25 @@ setx PATH "%PATH%;{0}"
<data name="CannotSpecifyBothRuntimeAndOsOptions" xml:space="preserve">
<value>Specifying both the `-r|--runtime` and `-os` options is not supported.</value>
</data>
<data name="CmdEnvironmentVariableDescription" xml:space="preserve">
<value>Sets the value of an environment variable.
Creates the variable if it does not exist, overrides if it does.
This will force the tests to be run in an isolated process.
This argument can be specified multiple times to provide multiple variables.

Examples:
-e VARIABLE=abc
-e VARIABLE="value with spaces"
-e VARIABLE="value;seperated with;semicolons"
-e VAR1=abc -e VAR2=def -e VAR3=ghi
</value>
</data>
<data name="CmdEnvironmentVariableExpression" xml:space="preserve">
<value>NAME="VALUE"</value>
</data>
<data name="IncorrectlyFormattedEnvironmentVariables" xml:space="preserve">
<value>Incorrectly formatted environment variables: {0}</value>
</data>
<data name="SelfContainedOptionDescription" xml:space="preserve">
<value>Publish the .NET runtime with your application so the runtime doesn't need to be installed on the target machine.
The default is 'false.' However, when targeting .NET 7 or lower, the default is 'true' if a runtime identifier is specified.</value>
Expand Down
46 changes: 39 additions & 7 deletions src/Cli/dotnet/CommonOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.CommandLine;
using System.CommandLine.Completions;
using System.CommandLine.Parsing;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.Tools.Common;
Expand Down Expand Up @@ -174,6 +175,44 @@ internal static string ArchOptionValue(ParseResult parseResult) =>
// Flip the argument so that if this option is specified we get selfcontained=false
.SetForwardingFunction((arg, p) => ForwardSelfContainedOptions(!arg, p));

public static readonly CliOption<IReadOnlyDictionary<string, string>> EnvOption = new("--environment", "-e")
{
Description = CommonLocalizableStrings.CmdEnvironmentVariableDescription,
HelpName = CommonLocalizableStrings.CmdEnvironmentVariableExpression,
CustomParser = ParseEnvironmentVariables,
// Can't allow multiple arguments because the separator needs to be parsed as part of the environment variable value.
AllowMultipleArgumentsPerToken = false
};

private static IReadOnlyDictionary<string, string> ParseEnvironmentVariables(ArgumentResult argumentResult)
{
Dictionary<string, string> result = [];
List<CliToken>? invalid = null;

foreach (var token in argumentResult.Tokens)
{
if (token.Value.IndexOf('=') is var index and > 0 &&
token.Value[0..index].Trim() is var name and not "")
{
result[name] = token.Value[(index + 1)..];
tmat marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
invalid ??= [];
invalid.Add(token);
}
}

if (invalid != null)
{
argumentResult.AddError(string.Format(
CommonLocalizableStrings.IncorrectlyFormattedEnvironmentVariables,
string.Join(", ", invalid.Select(x => $"'{x.Value}'"))));
}

return result;
}

public static readonly CliOption<string> TestPlatformOption = new("--Platform");

public static readonly CliOption<string> TestFrameworkOption = new("--Framework");
Expand Down Expand Up @@ -259,13 +298,6 @@ private static IEnumerable<string> ForwardSelfContainedOptions(bool isSelfContai
return selfContainedProperties;
}

private static bool UserSpecifiedRidOption(ParseResult parseResult) =>
(parseResult.GetResult(RuntimeOption) ??
parseResult.GetResult(LongFormRuntimeOption) ??
parseResult.GetResult(ArchitectureOption) ??
parseResult.GetResult(LongFormArchitectureOption) ??
parseResult.GetResult(OperatingSystemOption)) is not null;

internal static CliOption<T> AddCompletions<T>(this CliOption<T> option, Func<CompletionContext, IEnumerable<CompletionItem>> completionSource)
{
option.CompletionSources.Add(completionSource);
Expand Down
6 changes: 4 additions & 2 deletions src/Cli/dotnet/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"profiles": {
"dotnet": {
"commandName": "Project"
"commandName": "Project",
"commandLineArgs": "run -e MyCoolEnvironmentVariableKey=OverriddenEnvironmentVariableValue",
"workingDirectory": "C:\\sdk5\\artifacts\\tmp\\Debug\\EnvOptionLaun---86C8BD0D"
Comment on lines +5 to +6
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the changes to this file probably shouldn't be included in this PR.

}
}
}
}
6 changes: 4 additions & 2 deletions src/Cli/dotnet/commands/dotnet-run/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;
using System.CommandLine;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.Utils;
Expand Down Expand Up @@ -61,8 +62,9 @@ public static RunCommand FromParseResult(ParseResult parseResult)
noRestore: parseResult.HasOption(RunCommandParser.NoRestoreOption) || parseResult.HasOption(RunCommandParser.NoBuildOption),
interactive: parseResult.HasOption(RunCommandParser.InteractiveOption),
verbosity: parseResult.HasOption(CommonOptions.VerbosityOption) ? parseResult.GetValue(CommonOptions.VerbosityOption) : null,
restoreArgs: restoreArgs.ToArray(),
args: nonBinLogArgs.ToArray()
restoreArgs: [.. restoreArgs],
args: [.. nonBinLogArgs],
environmentVariables: parseResult.GetValue(CommonOptions.EnvOption) ?? ImmutableDictionary<string, string>.Empty
);

return command;
Expand Down
59 changes: 38 additions & 21 deletions src/Cli/dotnet/commands/dotnet-run/RunCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ private record RunProperties(string? RunCommand, string? RunArguments, string? R
public bool Interactive { get; private set; }
public string[] RestoreArgs { get; private set; }

/// <summary>
/// Environment variables specified on command line via -e option.
/// </summary>
public IReadOnlyDictionary<string, string> EnvironmentVariables { get; private set; }

private bool ShouldBuild => !NoBuild;

public string LaunchProfile { get; private set; }
Expand All @@ -43,7 +48,8 @@ public RunCommand(
bool interactive,
VerbosityOptions? verbosity,
string[] restoreArgs,
string[] args)
string[] args,
IReadOnlyDictionary<string, string> environmentVariables)
{
NoBuild = noBuild;
ProjectFileFullPath = DiscoverProjectFilePath(projectFileOrDirectory);
Expand All @@ -54,6 +60,7 @@ public RunCommand(
NoRestore = noRestore;
Verbosity = verbosity;
RestoreArgs = GetRestoreArguments(restoreArgs);
EnvironmentVariables = environmentVariables;
}

public int Execute()
Expand All @@ -76,10 +83,18 @@ public int Execute()
try
{
ICommand targetCommand = GetTargetCommand();
var launchSettingsCommand = ApplyLaunchSettingsProfileToCommand(targetCommand, launchSettings);
ApplyLaunchSettingsProfileToCommand(targetCommand, launchSettings);

// Env variables specified on command line override those specified in launch profile:
foreach (var (name, value) in EnvironmentVariables)
{
targetCommand.EnvironmentVariable(name, value);
}

// Ignore Ctrl-C for the remainder of the command's execution
Console.CancelKeyPress += (sender, e) => { e.Cancel = true; };
return launchSettingsCommand.Execute().ExitCode;

return targetCommand.Execute().ExitCode;
}
catch (InvalidProjectFileException e)
{
Expand All @@ -89,29 +104,31 @@ public int Execute()
}
}

private ICommand ApplyLaunchSettingsProfileToCommand(ICommand targetCommand, ProjectLaunchSettingsModel? launchSettings)
private void ApplyLaunchSettingsProfileToCommand(ICommand targetCommand, ProjectLaunchSettingsModel? launchSettings)
{
if (launchSettings != null)
if (launchSettings == null)
{
if (!string.IsNullOrEmpty(launchSettings.ApplicationUrl))
{
targetCommand.EnvironmentVariable("ASPNETCORE_URLS", launchSettings.ApplicationUrl);
}
return;
}

targetCommand.EnvironmentVariable("DOTNET_LAUNCH_PROFILE", launchSettings.LaunchProfileName);
if (!string.IsNullOrEmpty(launchSettings.ApplicationUrl))
{
targetCommand.EnvironmentVariable("ASPNETCORE_URLS", launchSettings.ApplicationUrl);
}

foreach (var entry in launchSettings.EnvironmentVariables)
{
string value = Environment.ExpandEnvironmentVariables(entry.Value);
//NOTE: MSBuild variables are not expanded like they are in VS
targetCommand.EnvironmentVariable(entry.Key, value);
}
if (string.IsNullOrEmpty(targetCommand.CommandArgs) && launchSettings.CommandLineArgs != null)
{
targetCommand.SetCommandArgs(launchSettings.CommandLineArgs);
}
targetCommand.EnvironmentVariable("DOTNET_LAUNCH_PROFILE", launchSettings.LaunchProfileName);

foreach (var entry in launchSettings.EnvironmentVariables)
{
string value = Environment.ExpandEnvironmentVariables(entry.Value);
//NOTE: MSBuild variables are not expanded like they are in VS
targetCommand.EnvironmentVariable(entry.Key, value);
}

if (string.IsNullOrEmpty(targetCommand.CommandArgs) && launchSettings.CommandLineArgs != null)
{
targetCommand.SetCommandArgs(launchSettings.CommandLineArgs);
}
return targetCommand;
}

private bool TryGetLaunchProfileSettingsIfNeeded(out ProjectLaunchSettingsModel? launchSettingsModel)
Expand Down
1 change: 1 addition & 0 deletions src/Cli/dotnet/commands/dotnet-run/RunCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ private static CliCommand ConstructCommand()
command.Options.Add(CommonOptions.OperatingSystemOption);
command.Options.Add(CommonOptions.DisableBuildServersOption);
command.Options.Add(CommonOptions.ArtifactsPathOption);
command.Options.Add(CommonOptions.EnvOption);

command.Arguments.Add(ApplicationArguments);

Expand Down
16 changes: 0 additions & 16 deletions src/Cli/dotnet/commands/dotnet-test/LocalizableStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -269,22 +269,6 @@ For MSTest before 2.2.4, the timeout is used for all testcases.</value>
<data name="HangTimeoutArgumentName" xml:space="preserve">
<value>TIMESPAN</value>
</data>
<data name="CmdEnvironmentVariableDescription" xml:space="preserve">
<value>Sets the value of an environment variable.
Creates the variable if it does not exist, overrides if it does.
This will force the tests to be run in an isolated process.
This argument can be specified multiple times to provide multiple variables.

Examples:
-e VARIABLE=abc
-e VARIABLE="value with spaces"
-e VARIABLE="value;seperated with;semicolons"
-e VAR1=abc -e VAR2=def -e VAR3=ghi
</value>
</data>
<data name="CmdEnvironmentVariableExpression" xml:space="preserve">
<value>NAME="VALUE"</value>
</data>
<data name="NoSerializerRegisteredWithIdErrorMessage" xml:space="preserve">
<value>No serializer registered with ID '{0}'</value>
</data>
Expand Down
36 changes: 9 additions & 27 deletions src/Cli/dotnet/commands/dotnet-test/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;
using System.CommandLine;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -228,8 +229,14 @@ private static TestCommand FromParseResult(ParseResult result, string[] settings
noRestore,
msbuildPath);

// Apply environment variables provided by the user via --environment (-e) parameter, if present
SetEnvironmentVariablesFromParameters(testCommand, result);
// Apply environment variables provided by the user via --environment (-e) option, if present
if (result.GetValue(CommonOptions.EnvOption) is { } environmentVariables)
{
foreach (var (name, value) in environmentVariables)
{
testCommand.EnvironmentVariable(name, value);
}
}

// Set DOTNET_PATH if it isn't already set in the environment as it is required
// by the testhost which uses the apphost feature (Windows only).
Expand Down Expand Up @@ -303,31 +310,6 @@ private static bool ContainsBuiltTestSources(string[] args)
return false;
}

private static void SetEnvironmentVariablesFromParameters(TestCommand testCommand, ParseResult parseResult)
{
CliOption<IEnumerable<string>> option = TestCommandParser.EnvOption;

if (parseResult.GetResult(option) is null)
{
return;
}

foreach (string env in parseResult.GetValue(option))
{
string name = env;
string value = string.Empty;

int equalsIndex = env.IndexOf('=');
if (equalsIndex > 0)
{
name = env.Substring(0, equalsIndex);
value = env.Substring(equalsIndex + 1);
}

testCommand.EnvironmentVariable(name, value);
}
}

/// <returns>A case-insensitive dictionary of any properties passed from the user and their values.</returns>
private static Dictionary<string, string> GetUserSpecifiedExplicitMSBuildProperties(ParseResult parseResult)
{
Expand Down
8 changes: 1 addition & 7 deletions src/Cli/dotnet/commands/dotnet-test/TestCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,6 @@ internal static class TestCommandParser
Description = LocalizableStrings.CmdListTestsDescription
}.ForwardAs("-property:VSTestListTests=true");

public static readonly CliOption<IEnumerable<string>> EnvOption = new CliOption<IEnumerable<string>>("--environment", "-e")
{
Description = LocalizableStrings.CmdEnvironmentVariableDescription,
HelpName = LocalizableStrings.CmdEnvironmentVariableExpression
}.AllowSingleArgPerToken();

public static readonly CliOption<string> FilterOption = new ForwardedOption<string>("--filter")
{
Description = LocalizableStrings.CmdTestCaseFilterDescription,
Expand Down Expand Up @@ -219,7 +213,7 @@ private static CliCommand GetVSTestCliCommand()

command.Options.Add(SettingsOption);
command.Options.Add(ListTestsOption);
command.Options.Add(EnvOption);
command.Options.Add(CommonOptions.EnvOption);
command.Options.Add(FilterOption);
command.Options.Add(AdapterOption);
command.Options.Add(LoggerOption);
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading