Skip to content
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
10 changes: 10 additions & 0 deletions src/Cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ to `dotnet` and `Microsoft.DotNet.Cli.Utils`. Internal parser APIs are accessibl
signed `dotnet` assembly through MSBuild's `InternalsVisibleTo`; keep those calls
managed-only rather than introducing MSBuild dependencies into `Definitions`.

CLI-owned path options (such as `--output`, `--artifacts-path`, `--packages`, and VSTest
`--settings`) keep their default, unescaped forwarding in the definitions for consumers such as
`dotnet-watch`. The managed command parsers replace it through
[`MSBuildOptionExtensions`](dotnet/Extensions/MSBuildOptionExtensions.cs), which uses
[`MSBuildPropertyEscaping`](../Microsoft.DotNet.ProjectTools/MSBuildPropertyEscaping.cs)
to escape literal paths with MSBuild's API before adding command-line quotes. When adding a path
option, forward it with `ForwardAsPathProperty`/`ForwardAsOutputPath` in the definition and wire
the `ForwardAsLiteral*` override in the managed parser. Keep explicit `-p:` values on their
existing MSBuild-syntax path; they are not literals.

When changing AOT-linked commands, resources, dependencies, or first-run behavior,
follow the [size and trimming contracts](dotnet-aot/DESIGN.md#size-and-trimming-contracts).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ internal sealed class PackCommandDefinition : Command
{
Description = CommandDefinitionStrings.PackCmdOutputDirDescription,
HelpName = CommandDefinitionStrings.PackCmdOutputDir
}.ForwardAsSingle(o => $"-property:PackageOutputPath={CommandDirectoryContext.GetFullPath(o)}");
}.ForwardAsPathProperty("PackageOutputPath");

public readonly Option<bool> NoBuildOption = new Option<bool>("--no-build")
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public sealed class VSTest : TestCommandDefinition
{
Description = CommandDefinitionStrings.CmdSettingsDescription,
HelpName = CommandDefinitionStrings.CmdSettingsFile
}.ForwardAsSingle(o => $"-property:VSTestSetting={MSBuildPropertyParser.SurroundWithDoubleQuotes(CommandDirectoryContext.GetFullPath(o))}");
}.ForwardAsPathProperty("VSTestSetting", surroundWithDoubleQuotes: true);

public readonly Option<bool> ListTestsOption = new Option<bool>("--list-tests", "-t")
{
Expand Down Expand Up @@ -54,7 +54,7 @@ public sealed class VSTest : TestCommandDefinition
Description = CommandDefinitionStrings.CmdOutputDescription,
HelpName = CommandDefinitionStrings.TestCmdOutputDir
}
.ForwardAsOutputPath("OutputPath", true);
.ForwardAsOutputPath("OutputPath", surroundWithDoubleQuotes: true);

public readonly Option<string> ArtifactsPathOption = CommonOptions.CreateArtifactsPathOption();

Expand All @@ -63,7 +63,7 @@ public sealed class VSTest : TestCommandDefinition
Description = CommandDefinitionStrings.CmdPathTologFileDescription,
HelpName = CommandDefinitionStrings.CmdPathToLogFile
}
.ForwardAsSingle(o => $"-property:VSTestDiag={MSBuildPropertyParser.SurroundWithDoubleQuotes(CommandDirectoryContext.GetFullPath(o))}");
.ForwardAsPathProperty("VSTestDiag", surroundWithDoubleQuotes: true);

public readonly Option<bool> NoBuildOption = new Option<bool>("--no-build")
{
Expand All @@ -81,7 +81,7 @@ public sealed class VSTest : TestCommandDefinition
{
Description = CommandDefinitionStrings.CmdResultsDirectoryDescription,
HelpName = CommandDefinitionStrings.CmdPathToResultsDirectory
}.ForwardAsSingle(o => $"-property:VSTestResultsDirectory={MSBuildPropertyParser.SurroundWithDoubleQuotes(CommandDirectoryContext.GetFullPath(o))}");
}.ForwardAsPathProperty("VSTestResultsDirectory", surroundWithDoubleQuotes: true);

public readonly Option<IEnumerable<string>> CollectOption = new Option<IEnumerable<string>>("--collect")
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ internal sealed class StoreCommandDefinition : Command
{
Description = CommandDefinitionStrings.IntermediateWorkingDirOptionDescription,
HelpName = CommandDefinitionStrings.IntermediateWorkingDirOption
}.ForwardAsSingle(o => $"-property:ComposeWorkingDir={CommandDirectoryContext.GetFullPath(o)}");
}.ForwardAsPathProperty("ComposeWorkingDir");

public readonly Option<bool> SkipOptimizationOption = new Option<bool>("--skip-optimization")
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ public static Option<string> CreateArtifactsPathOption() =>
{
Description = CommandDefinitionStrings.ArtifactsPathOptionDescription,
HelpName = CommandDefinitionStrings.ArtifactsPathArgumentName
}.ForwardAsSingle(o => $"--property:ArtifactsPath={CommandDirectoryContext.GetFullPath(o)}");
}.ForwardAsPathProperty("ArtifactsPath");

public static Option<bool> CreateUseCurrentRuntimeOption(string description) =>
new Option<bool>("--use-current-runtime", "--ucr")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public ImplicitRestoreOptions(bool showHelp, bool useShortOptions)
Description = showHelp ? CommandDefinitionStrings.CmdPackagesOptionDescription : string.Empty,
HelpName = CommandDefinitionStrings.CmdPackagesOption,
Hidden = !showHelp
}.ForwardAsSingle(o => $"-property:RestorePackagesPath={CommandDirectoryContext.GetFullPath(o)}");
}.ForwardAsPathProperty("RestorePackagesPath");

CurrentRuntimeOption = CommonOptions.CreateUseCurrentRuntimeOption(CommandDefinitionStrings.CmdCurrentRuntimeOptionDescription);

Expand All @@ -46,7 +46,7 @@ public ImplicitRestoreOptions(bool showHelp, bool useShortOptions)
Description = showHelp ? CommandDefinitionStrings.CmdConfigFileOptionDescription : string.Empty,
HelpName = CommandDefinitionStrings.CmdConfigFileOption,
Hidden = !showHelp
}.ForwardAsSingle(o => $"-property:RestoreConfigFile={CommandDirectoryContext.GetFullPath(o)}");
}.ForwardAsPathProperty("RestoreConfigFile");

NoCacheOption = new Option<bool>("--no-cache")
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,18 @@ public static Option<T> DisableAllowMultipleArgumentsPerToken<T>(this Option<T>
return o;
}


/// <summary>
/// Set up an option to be forwarded as an output path to MSBuild
/// </summary>
/// <param name="option">The command line option</param>
/// <param name="outputPropertyName">The property name for the output path (such as OutputPath or PublishDir)</param>
/// <param name="surroundWithDoubleQuotes">Whether the path should be surrounded with double quotes. This may not be necessary but preserves the previous behavior of "dotnet test"</param>
/// <param name="escapePropertyValue">
/// Escapes the literal full path for MSBuild before any quoting. The managed CLI supplies MSBuild's escaping;
/// other consumers of these definitions (such as dotnet-watch) keep forwarding the unescaped path.
/// </param>
/// <returns>The option</returns>
public static Option<string> ForwardAsOutputPath(this Option<string> option, string outputPropertyName, bool surroundWithDoubleQuotes = false)
public static Option<string> ForwardAsOutputPath(this Option<string> option, string outputPropertyName, bool surroundWithDoubleQuotes = false, Func<string, string>? escapePropertyValue = null)
{
return option.SetForwardingFunction((string? o) =>
{
Expand All @@ -48,19 +51,39 @@ public static Option<string> ForwardAsOutputPath(this Option<string> option, str
{
argVal += Path.DirectorySeparatorChar;
}
if (surroundWithDoubleQuotes)
{
// Not sure if this is necessary, but this is what "dotnet test" previously did and so we are
// preserving the behavior here after refactoring
argVal = MSBuildPropertyParser.SurroundWithDoubleQuotes(argVal);
}
return [
$"--property:{outputPropertyName}={argVal}",
$"--property:{outputPropertyName}={FormatPathPropertyValue(argVal, surroundWithDoubleQuotes, escapePropertyValue)}",
"--property:_CommandLineDefinedOutputPath=true"
];
});
}

/// <summary>
/// Set up an option whose value is a file system path to be forwarded to MSBuild as the full path in <paramref name="propertyName"/>.
/// </summary>
/// <param name="option">The command line option</param>
/// <param name="propertyName">The MSBuild property that receives the full path</param>
/// <param name="surroundWithDoubleQuotes">Whether the path should be surrounded with double quotes</param>
/// <param name="escapePropertyValue">
/// Escapes the literal full path for MSBuild before any quoting. The managed CLI supplies MSBuild's escaping;
/// other consumers of these definitions (such as dotnet-watch) keep forwarding the unescaped path.
/// </param>
/// <returns>The option</returns>
public static Option<string> ForwardAsPathProperty(this Option<string> option, string propertyName, bool surroundWithDoubleQuotes = false, Func<string, string>? escapePropertyValue = null)
{
return option.SetForwardingFunction((string? o) =>
o is null
? []
: [$"--property:{propertyName}={FormatPathPropertyValue(CommandDirectoryContext.GetFullPath(o), surroundWithDoubleQuotes, escapePropertyValue)}"]);
}

private static string FormatPathPropertyValue(string fullPath, bool surroundWithDoubleQuotes, Func<string, string>? escapePropertyValue)
{
string propertyValue = escapePropertyValue is null ? fullPath : escapePropertyValue(fullPath);
// Quote after escaping so the quotes remain MSBuild command-line syntax rather than part of the literal path.
return surroundWithDoubleQuotes ? MSBuildPropertyParser.SurroundWithDoubleQuotes(propertyValue) : propertyValue;
}

/// <summary>
/// Set up an option to be forwarded as an MSBuild property
/// This will parse the values as MSBuild properties and forward them in the format <c>optionName:key=value</c>.
Expand Down
3 changes: 3 additions & 0 deletions src/Cli/dotnet/Commands/Build/BuildCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ internal static class BuildCommandParser
{
public static void ConfigureCommand(BuildCommandDefinition command)
{
command.OutputOption.ForwardAsLiteralOutputPath("OutputPath");
command.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
command.ImplicitRestoreOptions.ForwardPathsAsLiterals();
command.SetAction(BuildCommand.Run);
command.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile);
command.ConfigurationOption.AddCompletions(CliCompletion.ConfigurationsFromProjectFileOrDefaults);
Expand Down
2 changes: 2 additions & 0 deletions src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ internal static class CleanCommandParser
{
public static void ConfigureCommand(CleanCommandDefinition command)
{
command.OutputOption.ForwardAsLiteralOutputPath("OutputPath");
command.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
command.SetAction(CleanCommand.Run);
command.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile);
command.ConfigurationOption.AddCompletions(CliCompletion.ConfigurationsFromProjectFileOrDefaults);
Expand Down
3 changes: 3 additions & 0 deletions src/Cli/dotnet/Commands/Pack/PackCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ internal static class PackCommandParser
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
public static void ConfigureCommand(PackCommandDefinition command)
{
command.OutputOption.ForwardAsLiteralPathProperty("PackageOutputPath");
command.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
command.ImplicitRestoreOptions.ForwardPathsAsLiterals();
command.ConfigurationOption.AddCompletions(CliCompletion.ConfigurationsFromProjectFileOrDefaults);
command.SetAction(PackCommand.Run);
}
Expand Down
3 changes: 3 additions & 0 deletions src/Cli/dotnet/Commands/Publish/PublishCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ internal static class PublishCommandParser
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
public static void ConfigureCommand(PublishCommandDefinition command)
{
command.OutputOption.ForwardAsLiteralOutputPath("PublishDir");
command.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
command.ImplicitRestoreOptions.ForwardPathsAsLiterals();
command.SetAction(PublishCommand.Run);
command.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile);
command.ConfigurationOption.AddCompletions(CliCompletion.ConfigurationsFromProjectFileOrDefaults);
Expand Down
2 changes: 2 additions & 0 deletions src/Cli/dotnet/Commands/Restore/RestoreCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ internal static class RestoreCommandParser
{
public static void ConfigureCommand(RestoreCommandDefinition command)
{
command.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
command.ImplicitRestoreOptions.ForwardPathsAsLiterals();
command.TargetPlatformOptions.RuntimeOption.AddCompletions(CliCompletion.RuntimesFromProjectFile);
command.SetAction(RestoreCommand.Run);
}
Expand Down
1 change: 1 addition & 0 deletions src/Cli/dotnet/Commands/Run/RunCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ internal static class RunCommandParser
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
public static void ConfigureCommand(RunCommandDefinition command)
{
command.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
command.SetAction(RunCommand.Run);
command.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile);
command.ConfigurationOption.AddCompletions(CliCompletion.ConfigurationsFromProjectFileOrDefaults);
Expand Down
6 changes: 6 additions & 0 deletions src/Cli/dotnet/Commands/Test/TestCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@ public static void ConfigureCommand(TestCommandDefinition command)
switch (command)
{
case TestCommandDefinition.VSTest vs:
vs.OutputOption.ForwardAsLiteralOutputPath("OutputPath", surroundWithDoubleQuotes: true);
vs.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
vs.SettingsOption.ForwardAsLiteralPathProperty("VSTestSetting", surroundWithDoubleQuotes: true);
vs.DiagOption.ForwardAsLiteralPathProperty("VSTestDiag", surroundWithDoubleQuotes: true);
vs.ResultsOption.ForwardAsLiteralPathProperty("VSTestResultsDirectory", surroundWithDoubleQuotes: true);
vs.SetAction(TestCommand.Run);
break;

case TestCommandDefinition.MicrosoftTestingPlatform mtp:
mtp.ArtifactsPathOption.ForwardAsLiteralPathProperty("ArtifactsPath");
var impl = new MicrosoftTestingPlatformTestCommand();
mtp.SetAction(parseResult => impl.Run(parseResult, isHelp: false));
mtp.CustomHelpLayoutProvider = impl;
Expand Down
2 changes: 2 additions & 0 deletions src/Cli/dotnet/Commands/Tool/Store/StoreCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ internal static class StoreCommandParser
{
public static void ConfigureCommand(StoreCommandDefinition command)
{
command.OutputOption.ForwardAsLiteralOutputPath("ComposeDir");
command.WorkingDirOption.ForwardAsLiteralPathProperty("ComposeWorkingDir");
command.SetAction(StoreCommand.Run);
command.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile);
}
Expand Down
27 changes: 27 additions & 0 deletions src/Cli/dotnet/Extensions/MSBuildOptionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.CommandLine;
using Microsoft.DotNet.Cli.Commands.Restore;
using Microsoft.DotNet.ProjectTools;

namespace Microsoft.DotNet.Cli;

/// <summary>
/// Replaces the definitions' default path forwarding with forwarding that escapes CLI-owned literal paths
/// using MSBuild's API, so characters such as <c>;</c>, <c>%</c>, and <c>$</c> are not reinterpreted by MSBuild.
/// </summary>
internal static class MSBuildOptionExtensions
{
public static Option<string> ForwardAsLiteralOutputPath(this Option<string> option, string outputPropertyName, bool surroundWithDoubleQuotes = false)
=> option.ForwardAsOutputPath(outputPropertyName, surroundWithDoubleQuotes, MSBuildPropertyEscaping.Escape);

public static Option<string> ForwardAsLiteralPathProperty(this Option<string> option, string propertyName, bool surroundWithDoubleQuotes = false)
=> option.ForwardAsPathProperty(propertyName, surroundWithDoubleQuotes, MSBuildPropertyEscaping.Escape);

public static void ForwardPathsAsLiterals(this ImplicitRestoreOptions options)
{
options.PackagesOption.ForwardAsLiteralPathProperty("RestorePackagesPath");
options.ConfigFileOption.ForwardAsLiteralPathProperty("RestoreConfigFile");
}
}
12 changes: 12 additions & 0 deletions test/dotnet-watch.Tests/CommandLine/CommandLineOptionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -685,4 +685,16 @@ public void ForwardedBuildOptions_ArtifactsPath()
var options = VerifyOptions(["run", .. args]);
AssertEx.SequenceEqual(buildArgs, options.BuildArguments);
}

[TestMethod]
public void ForwardedBuildOptions_OutputPath()
{
var path = Path.Combine(SdkTestContext.Current.TestAssetsDirectory, "out;put") + Path.DirectorySeparatorChar;

var args = new[] { "--output", path };
var buildArgs = new[] { NugetInteractiveProperty, "--property:OutputPath=" + path, "--property:_CommandLineDefinedOutputPath=true", "--nologo" };

var options = VerifyOptions(["build", .. args]);
AssertEx.SequenceEqual(buildArgs, options.BuildArguments);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ public class GivenDotnetPackInvocation : SdkTest
[DataRow(new string[] { }, new string[] { })]
[DataRow(new string[] { "-o", "<packageoutputpath>" }, new string[] { "--property:PackageOutputPath=<cwd><packageoutputpath>" })]
[DataRow(new string[] { "--output", "<packageoutputpath>" }, new string[] { "--property:PackageOutputPath=<cwd><packageoutputpath>" })]
[DataRow(new string[] { "--output", "out;put" }, new string[] { "--property:PackageOutputPath=<cwd>out%3bput" })]
[DataRow(new string[] { "--artifacts-path", "foo" }, new string[] { "--property:ArtifactsPath=<cwd>foo" })]
[DataRow(new string[] { "--artifacts-path", "fo%3Bo" }, new string[] { "--property:ArtifactsPath=<cwd>fo%253Bo" })]
[DataRow(new string[] { "--no-build" }, new string[] { "--property:NoBuild=true" })]
[DataRow(new string[] { "--include-symbols" }, new string[] { "--property:IncludeSymbols=true" })]
[DataRow(new string[] { "--include-source" }, new string[] { "--property:IncludeSource=true" })]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ public class GivenDotnetRestoreInvocation : SdkTest
[DataRow(new string[] { "--runtime", "<runtime>" }, new string[] { "--property:RuntimeIdentifiers=<runtime>" })]
[DataRow(new string[] { "-r", "<runtime0>", "-r", "<runtime1>" }, new string[] { "--property:RuntimeIdentifiers=<runtime0>%3B<runtime1>" })]
[DataRow(new string[] { "--packages", "<packages>" }, new string[] { "--property:RestorePackagesPath=<cwd><packages>" })]
[DataRow(new string[] { "--packages", "pack;ages" }, new string[] { "--property:RestorePackagesPath=<cwd>pack%3bages" })]
[DataRow(new string[] { "--disable-parallel" }, new string[] { "--property:RestoreDisableParallel=true" })]
[DataRow(new string[] { "--configfile", "<config>" }, new string[] { "--property:RestoreConfigFile=<cwd><config>" })]
[DataRow(new string[] { "--configfile", "nuget$(x).config" }, new string[] { "--property:RestoreConfigFile=<cwd>nuget%24%28x%29.config" })]
[DataRow(new string[] { "--no-cache" }, new string[] { "--property:RestoreNoCache=true" })]
[DataRow(new string[] { "--no-http-cache" }, new string[] { "--property:RestoreNoHttpCache=true" })]
[DataRow(new string[] { "--ignore-failed-sources" }, new string[] { "--property:RestoreIgnoreFailedSources=true" })]
Expand Down
Loading
Loading