Skip to content

Directly create virtual project when dotnet run-api is missing for now #78788

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 1 commit into from
Jun 2, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,10 @@ public async ValueTask TryRemoveMiscellaneousDocumentAsync(DocumentUri uri, bool
var content = await _projectXmlProvider.GetVirtualProjectContentAsync(documentPath, cancellationToken);
if (content is not var (virtualProjectContent, diagnostics))
{
// 'GetVirtualProjectContentAsync' will log errors when it fails
return null;
// https://github.com/dotnet/roslyn/issues/78618: falling back to this until dotnet run-api is more widely available
_logger.LogInformation($"Failed to obtain virtual project for '{documentPath}' using dotnet run-api. Falling back to directly creating the virtual project.");
virtualProjectContent = VirtualProjectXmlProvider.MakeVirtualProjectContent_DirectFallback(documentPath);
diagnostics = [];
}

foreach (var diagnostic in diagnostics)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,106 @@ internal static bool IsFileBasedProgram(string documentFilePath, SourceText text
var isFileBasedProgram = root.GetLeadingTrivia().Any(SyntaxKind.IgnoredDirectiveTrivia) || root.ChildNodes().Any(node => node.IsKind(SyntaxKind.GlobalStatement));
return isFileBasedProgram;
}

#region Temporary copy of subset of dotnet run-api behavior for fallback: https://github.com/dotnet/roslyn/issues/78618
// See https://github.com/dotnet/sdk/blob/b5dbc69cc28676ac6ea615654c8016a11b75e747/src/Cli/Microsoft.DotNet.Cli.Utils/Sha256Hasher.cs#L10
private static class Sha256Hasher
{
public static string Hash(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] hash = SHA256.HashData(bytes);
#if NET9_0_OR_GREATER
return Convert.ToHexStringLower(hash);
#else
return Convert.ToHexString(hash).ToLowerInvariant();
#endif
}

public static string HashWithNormalizedCasing(string text)
{
return Hash(text.ToUpperInvariant());
}
}

// See https://github.com/dotnet/sdk/blob/5a4292947487a9d34f4256c1d17fb3dc26859174/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs#L449
internal static string GetArtifactsPath(string entryPointFileFullPath)
{
// We want a location where permissions are expected to be restricted to the current user.
string directory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Path.GetTempPath()
: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

// Include entry point file name so the directory name is not completely opaque.
string fileName = Path.GetFileNameWithoutExtension(entryPointFileFullPath);
string hash = Sha256Hasher.HashWithNormalizedCasing(entryPointFileFullPath);
string directoryName = $"{fileName}-{hash}";

return Path.Join(directory, "dotnet", "runfile", directoryName);
}
#endregion

// https://github.com/dotnet/roslyn/issues/78618: falling back to this until dotnet run-api is more widely available
internal static string MakeVirtualProjectContent_DirectFallback(string documentFilePath)
{
Contract.ThrowIfFalse(PathUtilities.IsAbsolute(documentFilePath));
var artifactsPath = GetArtifactsPath(documentFilePath);

var targetFramework = Environment.GetEnvironmentVariable("DOTNET_RUN_FILE_TFM") ?? "net10.0";

var virtualProjectXml = $"""
<Project>
<PropertyGroup>
<IncludeProjectNameInArtifactsPaths>false</IncludeProjectNameInArtifactsPaths>
<ArtifactsPath>{SecurityElement.Escape(artifactsPath)}</ArtifactsPath>
</PropertyGroup>
<!-- 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>{SecurityElement.Escape(targetFramework)}</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<EnableDefaultItems>false</EnableDefaultItems>
</PropertyGroup>
<PropertyGroup>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<PropertyGroup>
<Features>$(Features);FileBasedProgram</Features>
</PropertyGroup>
<ItemGroup>
<Compile Include="{SecurityElement.Escape(documentFilePath)}" />
</ItemGroup>
<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.
-->
<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>
""";

return virtualProjectXml;
}
}
Loading