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

Implement caching in .NET info resolver #267

Merged
merged 2 commits into from
Apr 30, 2024
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
65 changes: 65 additions & 0 deletions src/Buildalyzer/Environment/DotNetInfoResolver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Collections.Concurrent;
using Buildalyzer.IO;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Buildalyzer.Environment;

internal sealed class DotNetInfoResolver(ILoggerFactory? factory)
{
private static readonly TimeSpan FallbackWaitTime = TimeSpan.FromSeconds(10);
private readonly ILoggerFactory Factory = factory ?? NullLoggerFactory.Instance;
private readonly ILogger Logger = (factory ?? NullLoggerFactory.Instance).CreateLogger<DotNetInfoResolver>();

[Pure]
public DotNetInfo Resolve(IOPath projectPath, IOPath dotNetExePath)
=> Cache.TryGetValue(projectPath, out var info)
? info
: Execute(projectPath, dotNetExePath);

[Pure]
private DotNetInfo Execute(IOPath projectPath, IOPath dotNetExePath)
{
// Ensure that we set the DOTNET_CLI_UI_LANGUAGE environment variable to "en-US" before
// running 'dotnet --info'. Otherwise, we may get localized results
// Also unset some MSBuild variables, see https://github.com/OmniSharp/omnisharp-roslyn/blob/df160f86ce906bc566fe3e04e38a4077bd6023b4/src/OmniSharp.Abstractions/Services/DotNetCliService.cs#L36
var environmentVariables = new Dictionary<string, string?>
{
[EnvironmentVariables.DOTNET_CLI_UI_LANGUAGE] /*.*/ = "en-US",
[EnvironmentVariables.MSBUILD_EXE_PATH] /*.......*/ = null,
[EnvironmentVariables.COREHOST_TRACE] /*.........*/ = "0",
[MsBuildProperties.MSBuildExtensionsPath] /*.....*/ = null,
};

// global.json may change the version, so need to set working directory
using var processRunner = new ProcessRunner(
dotNetExePath.ToString(),
"--info",
projectPath.File().Directory!.FullName,
environmentVariables,
Factory);

processRunner.Start();
processRunner.WaitForExit(GetWaitTime());

var info = DotNetInfo.Parse(processRunner.Output);
Cache[projectPath] = info;
return info;
}

[Pure]
private int GetWaitTime()
{
if (int.TryParse(System.Environment.GetEnvironmentVariable(EnvironmentVariables.DOTNET_INFO_WAIT_TIME), out int waitTime))
{
Logger?.LogInformation("dotnet --info wait time is {WaitTime}ms", waitTime);
return waitTime;
}
else
{
return (int)FallbackWaitTime.TotalMilliseconds;
}
}

private readonly ConcurrentDictionary<IOPath, DotNetInfo> Cache = new();
}
62 changes: 0 additions & 62 deletions src/Buildalyzer/Environment/DotnetPathResolver.cs

This file was deleted.

33 changes: 16 additions & 17 deletions src/Buildalyzer/Environment/EnvironmentFactory.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.IO;
using System.Runtime.InteropServices;
using Buildalyzer.Construction;
using Microsoft.Build.Utilities;
Expand All @@ -23,19 +20,19 @@ internal EnvironmentFactory(IAnalyzerManager manager, IProjectFile projectFile)
_logger = _manager.LoggerFactory?.CreateLogger<EnvironmentFactory>();
}

public BuildEnvironment GetBuildEnvironment() =>
public BuildEnvironment? GetBuildEnvironment() =>
GetBuildEnvironment(null, null);

public BuildEnvironment GetBuildEnvironment(string targetFramework) =>
public BuildEnvironment? GetBuildEnvironment(string? targetFramework) =>
GetBuildEnvironment(targetFramework, null);

public BuildEnvironment GetBuildEnvironment(EnvironmentOptions options) =>
public BuildEnvironment? GetBuildEnvironment(EnvironmentOptions? options) =>
GetBuildEnvironment(null, options);

public BuildEnvironment GetBuildEnvironment(string targetFramework, EnvironmentOptions options)
public BuildEnvironment? GetBuildEnvironment(string? targetFramework, EnvironmentOptions? options)
{
options ??= new EnvironmentOptions();
BuildEnvironment buildEnvironment;
BuildEnvironment? buildEnvironment;

// Use the .NET Framework if that's the preference
// ...or if this project file uses a target known to require .NET Framework
Expand All @@ -57,18 +54,20 @@ public BuildEnvironment GetBuildEnvironment(string targetFramework, EnvironmentO

// Based on code from OmniSharp
// https://github.com/OmniSharp/omnisharp-roslyn/blob/78ccc8b4376c73da282a600ac6fb10fce8620b52/src/OmniSharp.Abstractions/Services/DotNetCliService.cs
private BuildEnvironment CreateCoreEnvironment(EnvironmentOptions options)
private BuildEnvironment? CreateCoreEnvironment(EnvironmentOptions options)
{
// Get paths
DotnetPathResolver pathResolver = new DotnetPathResolver(_manager.LoggerFactory);
string dotnetPath = pathResolver.ResolvePath(_projectFile.Path, options.DotnetExePath);
if (dotnetPath == null)
var resolver = new DotNetInfoResolver(_manager.LoggerFactory);
var info = resolver.Resolve(IO.IOPath.Parse(_projectFile.Path), IO.IOPath.Parse(options.DotnetExePath));

if ((info.BasePath ?? info.Runtimes.Values.FirstOrDefault()) is not { } dotnetPath)
{
_logger?.LogWarning("Could not locate SDK path in `{DotnetPath} --info` results", options.DotnetExePath);
return null;
}

string msBuildExePath = Path.Combine(dotnetPath, "MSBuild.dll");
if (options != null && options.EnvironmentVariables.ContainsKey(EnvironmentVariables.MSBUILD_EXE_PATH))
if (options.EnvironmentVariables.ContainsKey(EnvironmentVariables.MSBUILD_EXE_PATH))
{
msBuildExePath = options.EnvironmentVariables[EnvironmentVariables.MSBUILD_EXE_PATH];
}
Expand Down Expand Up @@ -121,7 +120,7 @@ private BuildEnvironment CreateCoreEnvironment(EnvironmentOptions options)
options.WorkingDirectory);
}

private BuildEnvironment CreateFrameworkEnvironment(EnvironmentOptions options)
private BuildEnvironment? CreateFrameworkEnvironment(EnvironmentOptions options)
{
// Clone the options global properties dictionary so we can add to it
Dictionary<string, string> additionalGlobalProperties = new Dictionary<string, string>(options.GlobalProperties);
Expand All @@ -135,7 +134,7 @@ private BuildEnvironment CreateFrameworkEnvironment(EnvironmentOptions options)
}

string msBuildExePath;
if (options != null && options.EnvironmentVariables.ContainsKey(EnvironmentVariables.MSBUILD_EXE_PATH))
if (options.EnvironmentVariables.ContainsKey(EnvironmentVariables.MSBUILD_EXE_PATH))
{
msBuildExePath = options.EnvironmentVariables[EnvironmentVariables.MSBUILD_EXE_PATH];
}
Expand Down Expand Up @@ -194,7 +193,7 @@ private bool GetFrameworkMsBuildExePath(out string msBuildExePath)
return !string.IsNullOrEmpty(msBuildExePath);
}

private bool OnlyTargetsFramework(string targetFramework)
private bool OnlyTargetsFramework(string? targetFramework)
=> targetFramework == null
? _projectFile.TargetFrameworks.TrueForAll(IsFrameworkTargetFramework)
: IsFrameworkTargetFramework(targetFramework);
Expand Down
7 changes: 2 additions & 5 deletions src/Buildalyzer/Environment/ProcessRunner.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Extensions.Logging;

namespace Buildalyzer.Environment;
Expand All @@ -21,8 +18,8 @@ public ProcessRunner(
string fileName,
string arguments,
string workingDirectory,
Dictionary<string, string> environmentVariables,
ILoggerFactory loggerFactory)
Dictionary<string, string?> environmentVariables,
ILoggerFactory? loggerFactory)
{
_logger = loggerFactory?.CreateLogger<ProcessRunner>();
Process = new Process
Expand Down
Loading