-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add basic support for 'dotnet run file.cs' #46915
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
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
aea7240
Add basic support for 'dotnet run file.cs'
jjonescz 8094d49
Fix tests on case sensitive OSes
jjonescz 9f51756
Share binlog arg detection code
jjonescz 5a5206f
Nullable-enable RunCommand.cs
jjonescz 254eccb
Test embedded resource
jjonescz aa913b0
Merge branch 'main' into sprint
jjonescz fe91ade
Allow `--no-build`
jjonescz 5c873d1
Allow `--launch-profile`
jjonescz da30f3e
Improve binlog option parsing
jjonescz fcd9a92
Improve code
jjonescz eb2a1e8
Fix test to work on Linux
jjonescz d08a1be
Link related issues
jjonescz d646bfc
Fix more binary logger inconsistencies
jjonescz 9b80546
Reuse terminal logger creation function
jjonescz 4968d9a
Fix TFM
jjonescz 5c04bcc
Merge branch 'main' into sprint
jjonescz 768eaab
Include only the entry-point file
jjonescz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
200 changes: 200 additions & 0 deletions
200
src/Cli/dotnet/commands/VirtualProjectBuildingCommand.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,200 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
#nullable enable | ||
|
||
using System.Xml; | ||
using Microsoft.Build.Construction; | ||
using Microsoft.Build.Definition; | ||
using Microsoft.Build.Evaluation; | ||
using Microsoft.Build.Execution; | ||
using Microsoft.Build.Framework; | ||
using Microsoft.Build.Logging; | ||
using Microsoft.DotNet.Cli.Utils; | ||
using Microsoft.DotNet.Tools.Run; | ||
|
||
namespace Microsoft.DotNet.Tools; | ||
|
||
/// <summary> | ||
/// Used to build a virtual project file in memory to support <c>dotnet run file.cs</c>. | ||
/// </summary> | ||
internal sealed class VirtualProjectBuildingCommand | ||
{ | ||
public Dictionary<string, string> GlobalProperties { get; } = new(StringComparer.OrdinalIgnoreCase); | ||
public required string EntryPointFileFullPath { get; init; } | ||
|
||
public int Execute(string[] binaryLoggerArgs, ILogger consoleLogger) | ||
{ | ||
var binaryLogger = GetBinaryLogger(binaryLoggerArgs); | ||
Dictionary<string, string?> savedEnvironmentVariables = new(); | ||
try | ||
{ | ||
// Set environment variables. | ||
foreach (var (key, value) in MSBuildForwardingAppWithoutLogging.GetMSBuildRequiredEnvironmentVariables()) | ||
{ | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
savedEnvironmentVariables[key] = Environment.GetEnvironmentVariable(key); | ||
Environment.SetEnvironmentVariable(key, value); | ||
} | ||
|
||
// Set up MSBuild. | ||
ReadOnlySpan<ILogger> binaryLoggers = binaryLogger is null ? [] : [binaryLogger]; | ||
var projectCollection = new ProjectCollection( | ||
GlobalProperties, | ||
[.. binaryLoggers, consoleLogger], | ||
ToolsetDefinitionLocations.Default); | ||
var parameters = new BuildParameters(projectCollection) | ||
{ | ||
Loggers = projectCollection.Loggers, | ||
LogTaskInputs = binaryLoggers.Length != 0, | ||
}; | ||
BuildManager.DefaultBuildManager.BeginBuild(parameters); | ||
|
||
// Do a restore first (equivalent to MSBuild's "implicit restore", i.e., `/restore`). | ||
// See https://github.com/dotnet/msbuild/blob/a1c2e7402ef0abe36bf493e395b04dd2cb1b3540/src/MSBuild/XMake.cs#L1838 | ||
// and https://github.com/dotnet/msbuild/issues/11519. | ||
var restoreRequest = new BuildRequestData( | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
CreateProjectInstance(projectCollection, addGlobalProperties: static (globalProperties) => | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
globalProperties["MSBuildRestoreSessionId"] = Guid.NewGuid().ToString("D"); | ||
globalProperties["MSBuildIsRestoring"] = bool.TrueString; | ||
}), | ||
targetsToBuild: ["Restore"], | ||
hostServices: null, | ||
BuildRequestDataFlags.ClearCachesAfterBuild | BuildRequestDataFlags.SkipNonexistentTargets | BuildRequestDataFlags.IgnoreMissingEmptyAndInvalidImports | BuildRequestDataFlags.FailOnUnresolvedSdk); | ||
var restoreResult = BuildManager.DefaultBuildManager.BuildRequest(restoreRequest); | ||
if (restoreResult.OverallResult != BuildResultCode.Success) | ||
{ | ||
return 1; | ||
} | ||
|
||
// Then do a build. | ||
var buildRequest = new BuildRequestData( | ||
CreateProjectInstance(projectCollection), | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
targetsToBuild: ["Build"]); | ||
var buildResult = BuildManager.DefaultBuildManager.BuildRequest(buildRequest); | ||
if (buildResult.OverallResult != BuildResultCode.Success) | ||
{ | ||
return 1; | ||
} | ||
|
||
BuildManager.DefaultBuildManager.EndBuild(); | ||
return 0; | ||
} | ||
catch (Exception e) | ||
{ | ||
Console.Error.WriteLine(e.Message); | ||
return 1; | ||
} | ||
finally | ||
{ | ||
foreach (var (key, value) in savedEnvironmentVariables) | ||
{ | ||
Environment.SetEnvironmentVariable(key, value); | ||
} | ||
|
||
binaryLogger?.Shutdown(); | ||
consoleLogger.Shutdown(); | ||
} | ||
|
||
static ILogger? GetBinaryLogger(string[] args) | ||
{ | ||
// Like in MSBuild, only the last binary logger is used. | ||
for (int i = args.Length - 1; i >= 0; i--) | ||
{ | ||
var arg = args[i]; | ||
if (RunCommand.IsBinLogArgument(arg)) | ||
{ | ||
return new BinaryLogger | ||
{ | ||
Parameters = arg.IndexOf(':') is >= 0 and var index | ||
? arg[(index + 1)..] | ||
: "msbuild.binlog", | ||
}; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
} | ||
|
||
public ProjectInstance CreateProjectInstance(ProjectCollection projectCollection) | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
return CreateProjectInstance(projectCollection, addGlobalProperties: null); | ||
} | ||
|
||
private ProjectInstance CreateProjectInstance( | ||
ProjectCollection projectCollection, | ||
Action<IDictionary<string, string>>? addGlobalProperties) | ||
{ | ||
var projectRoot = CreateProjectRootElement(projectCollection); | ||
|
||
var globalProperties = projectCollection.GlobalProperties; | ||
if (addGlobalProperties is not null) | ||
{ | ||
globalProperties = new Dictionary<string, string>(projectCollection.GlobalProperties, StringComparer.OrdinalIgnoreCase); | ||
addGlobalProperties(globalProperties); | ||
} | ||
|
||
return ProjectInstance.FromProjectRootElement(projectRoot, new ProjectOptions | ||
{ | ||
GlobalProperties = globalProperties, | ||
}); | ||
} | ||
|
||
private ProjectRootElement CreateProjectRootElement(ProjectCollection projectCollection) | ||
{ | ||
var projectFileFullPath = Path.ChangeExtension(EntryPointFileFullPath, ".csproj"); | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
var projectFileText = """ | ||
<Project> | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<!-- We need to explicitly import Sdk props/targets so we can override the targets below. --> | ||
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" /> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net10.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
<EnableDefaultItems>false</EnableDefaultItems> | ||
</PropertyGroup> | ||
|
||
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" /> | ||
|
||
<!-- | ||
Override targets which don't work with project files that are not present on disk. | ||
See https://github.com/NuGet/Home/issues/14148. | ||
jjonescz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
--> | ||
|
||
<Target Name="_FilterRestoreGraphProjectInputItems" | ||
DependsOnTargets="_LoadRestoreGraphEntryPoints" | ||
Returns="@(FilteredRestoreGraphProjectInputItems)"> | ||
<ItemGroup> | ||
<FilteredRestoreGraphProjectInputItems Include="@(RestoreGraphProjectInputItems)" /> | ||
</ItemGroup> | ||
</Target> | ||
|
||
<Target Name="_GetAllRestoreProjectPathItems" | ||
DependsOnTargets="_FilterRestoreGraphProjectInputItems" | ||
Returns="@(_RestoreProjectPathItems)"> | ||
<ItemGroup> | ||
<_RestoreProjectPathItems Include="@(FilteredRestoreGraphProjectInputItems)" /> | ||
</ItemGroup> | ||
</Target> | ||
|
||
<Target Name="_GenerateRestoreGraph" | ||
DependsOnTargets="_FilterRestoreGraphProjectInputItems;_GetAllRestoreProjectPathItems;_GenerateRestoreGraphProjectEntry;_GenerateProjectRestoreGraph" | ||
Returns="@(_RestoreGraphEntry)"> | ||
<!-- Output from dependency _GenerateRestoreGraphProjectEntry and _GenerateProjectRestoreGraph --> | ||
</Target> | ||
</Project> | ||
"""; | ||
ProjectRootElement projectRoot; | ||
using (var xmlReader = XmlReader.Create(new StringReader(projectFileText))) | ||
{ | ||
projectRoot = ProjectRootElement.Create(xmlReader, projectCollection); | ||
} | ||
projectRoot.AddItem(itemType: "Compile", include: EntryPointFileFullPath); | ||
projectRoot.FullPath = projectFileFullPath; | ||
return projectRoot; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.