Skip to content

Override default properties with custom file-level directives #49767

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 4 commits into from
Jul 22, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
68 changes: 39 additions & 29 deletions src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ internal sealed class VirtualProjectBuildingCommand : CommandBase
"MSBuild.rsp",
];

/// <remarks>
/// Kept in sync with the default <c>dotnet new console</c> project file (enforced by <c>DotnetProjectAddTests.SameAsTemplate</c>).
/// </remarks>
private static readonly FrozenDictionary<string, string> s_defaultProperties = FrozenDictionary.Create<string, string>(StringComparer.OrdinalIgnoreCase,
[
new("OutputType", "Exe"),
new("TargetFramework", "net10.0"),
Copy link
Member

Choose a reason for hiding this comment

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

Any reason we can't use ToolsetInfo.CurrentTargetFramework here? I think that's the right value.

Copy link
Member Author

Choose a reason for hiding this comment

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

ToolsetInfo is only available in tests. I'm introducing a product equivalent in #49528 and once that's merged I expect it to be used here (there will be conflicts that will remind me to do that).

new("ImplicitUsings", "enable"),
new("Nullable", "enable"),
new("PublishAot", "true"),
]);

internal static readonly string TargetOverrides = """
<!--
Override targets which don't work with project files that are not present on disk.
Expand Down Expand Up @@ -645,33 +657,37 @@ public static void WriteProjectFile(
writer.WriteLine();
}

// Kept in sync with the default `dotnet new console` project file (enforced by `DotnetProjectAddTests.SameAsTemplate`).
writer.WriteLine($"""
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
</PropertyGroup>
""");
// Write default properties unless they are overridden by custom directives.
var propertyDirectiveNames = propertyDirectives.Select(d => d.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
if (!s_defaultProperties.Keys.All(propertyDirectiveNames.Contains))
{
writer.WriteLine(" <PropertyGroup>");
foreach (var (name, value) in s_defaultProperties)
{
if (!propertyDirectiveNames.Contains(name))
{
writer.WriteLine($"""
<{name}>{EscapeValue(value)}</{name}>
""");
}
}
writer.WriteLine(" </PropertyGroup>");
writer.WriteLine();
}

if (isVirtualProject)
{
writer.WriteLine("""
Copy link
Preview

Copilot AI Jul 14, 2025

Choose a reason for hiding this comment

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

[nitpick] The code currently mixes raw string literals and direct WriteLine calls for XML fragments. For consistency, you could unify on one style (either always use raw string literals or always use WriteLine with interpolated strings).

Suggested change
writer.WriteLine("""
writer.WriteLine($"""

Copilot uses AI. Check for mistakes.

Copy link
Member

Choose a reason for hiding this comment

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

Personally, I would also agree with copilot here.

Copy link
Member Author

@jjonescz jjonescz Jul 22, 2025

Choose a reason for hiding this comment

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

either always use raw string literals or always use WriteLine with interpolated strings

I'm not sure what is being suggested here. Why would I use WriteLine with interpolated strings when I don't need anything interpolated? And when I'm using interpolated strings, they are raw string literals.

Copy link
Member

Choose a reason for hiding this comment

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

Oh, the suggested fix is bogus. I'm talking about the mix of raw vs non-raw


<PropertyGroup>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>

""");
}

if (propertyDirectives.Any())
{
writer.WriteLine("""

<PropertyGroup>
""");
writer.WriteLine(" <PropertyGroup>");

foreach (var property in propertyDirectives)
{
Expand All @@ -683,25 +699,23 @@ public static void WriteProjectFile(
}

writer.WriteLine(" </PropertyGroup>");
writer.WriteLine();
}

if (isVirtualProject)
{
// After `#:property` directives so they don't override this.
writer.WriteLine("""

<PropertyGroup>
<Features>$(Features);FileBasedProgram</Features>
</PropertyGroup>

""");
}

if (packageDirectives.Any())
{
writer.WriteLine("""

<ItemGroup>
""");
writer.WriteLine(" <ItemGroup>");

foreach (var package in packageDirectives)
{
Expand All @@ -722,14 +736,12 @@ public static void WriteProjectFile(
}

writer.WriteLine(" </ItemGroup>");
writer.WriteLine();
}

if (projectDirectives.Any())
{
writer.WriteLine("""

<ItemGroup>
""");
writer.WriteLine(" <ItemGroup>");

foreach (var projectReference in projectDirectives)
{
Expand All @@ -741,6 +753,7 @@ public static void WriteProjectFile(
}

writer.WriteLine(" </ItemGroup>");
writer.WriteLine();
}

Debug.Assert(processedDirectives + directives.OfType<CSharpDirective.Shebang>().Count() == directives.Length);
Expand All @@ -750,7 +763,6 @@ public static void WriteProjectFile(
Debug.Assert(targetFilePath is not null);

writer.WriteLine($"""

<ItemGroup>
<Compile Include="{EscapeValue(targetFilePath)}" />
</ItemGroup>
Expand Down Expand Up @@ -784,12 +796,10 @@ public static void WriteProjectFile(

writer.WriteLine();
writer.WriteLine(TargetOverrides);
writer.WriteLine();
}

writer.WriteLine("""

</Project>
""");
writer.WriteLine("</Project>");

static string EscapeValue(string value) => SecurityElement.Escape(value);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -640,14 +640,13 @@ public void Directives()
#:property LangVersion=preview
Console.WriteLine();
""",
expectedProject: $"""
expectedProject: """
<Project Sdk="Microsoft.NET.Sdk">

<Sdk Name="Aspire.Hosting.Sdk" Version="9.1.0" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>{ToolsetInfo.CurrentTargetFramework}</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
Expand All @@ -670,6 +669,44 @@ public void Directives()
""");
}

/// <summary>
/// There should be only one <c>PropertyGroup</c> element when the default properties are overridden.
/// </summary>
[Fact]
public void Directives_AllDefaultOverridden()
{
VerifyConversion(
inputCSharp: """
#!/program
#:sdk Microsoft.NET.Web.Sdk
#:property OutputType=Exe
#:property TargetFramework=net11.0
Copy link
Member

Choose a reason for hiding this comment

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

main for the SDK is not net11 yet.

Copy link
Member Author

Choose a reason for hiding this comment

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

I know, this is supposed to be a different version for testing, I can probably use something like net472 to make that clearer.

#:property Nullable=disable
#:property PublishAot=false
#:property Custom=1
#:property ImplicitUsings=disable
Console.WriteLine();
""",
expectedProject: """
<Project Sdk="Microsoft.NET.Web.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
Copy link
Member

Choose a reason for hiding this comment

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

Same here.

<Nullable>disable</Nullable>
<PublishAot>false</PublishAot>
<Custom>1</Custom>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>

</Project>

""",
expectedCSharp: """
Console.WriteLine();
""");
}

[Fact]
public void Directives_Variable()
{
Expand Down
1 change: 0 additions & 1 deletion test/dotnet.Tests/CommandTests/Run/RunFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1858,7 +1858,6 @@ public void Api()

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>{ToolsetInfo.CurrentTargetFramework}</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
Expand Down