Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
@@ -0,0 +1,124 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Roslyn.Test.Utilities;
using Xunit;

namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim;

public sealed class SdkAnalyzerAssemblyRedirectorTests : TestBase
{
[Theory]
[InlineData("9.0.0-preview.5.24306.11", "9.0.0-preview.7.24406.2")]
[InlineData("9.0.0-preview.5.24306.11", "9.0.1-preview.7.24406.2")]
[InlineData("9.0.100", "9.0.0-preview.7.24406.2")]
[InlineData("9.0.100", "9.0.200")]
[InlineData("9.0.100", "9.0.101")]
public void SameMajorMinorVersion(string a, string b)
{
var testDir = Temp.CreateDirectory();

var vsDir = Path.Combine(testDir.Path, "vs");
Metadata(vsDir, new() { { "AspNetCoreAnalyzers", a } });
var vsAnalyzerPath = FakeDll(vsDir, @$"AspNetCoreAnalyzers\analyzers\dotnet\cs", "Microsoft.AspNetCore.App.Analyzers");
var sdkAnalyzerPath = @$"Z:\Program Files\dotnet\sdk\packs\Microsoft.AspNetCore.App.Ref\{b}\analyzers\dotnet\cs\Microsoft.AspNetCore.App.Analyzers.dll";

var resolver = new SdkAnalyzerAssemblyRedirectorCore(vsDir);
var redirected = resolver.RedirectPath(sdkAnalyzerPath);
AssertEx.Equal(vsAnalyzerPath, redirected);
}

[Fact]
public void DifferentPathSuffix()
{
var testDir = Temp.CreateDirectory();

var vsDir = Path.Combine(testDir.Path, "vs");
Metadata(vsDir, new() { { "AspNetCoreAnalyzers", "9.0.0-preview.5.24306.11" } });
FakeDll(vsDir, @"AspNetCoreAnalyzers\analyzers\dotnet\cs", "Microsoft.AspNetCore.App.Analyzers");
var sdkAnalyzerPath = @"Z:\Program Files\dotnet\sdk\packs\Microsoft.AspNetCore.App.Ref\9.0.0-preview.7.24406.2\analyzers\dotnet\vb\Microsoft.AspNetCore.App.Analyzers.dll";

var resolver = new SdkAnalyzerAssemblyRedirectorCore(vsDir);
var redirected = resolver.RedirectPath(sdkAnalyzerPath);
Assert.Null(redirected);
}

[Fact]
public void DifferentPathSuffix_NoParentDirectory()
{
var testDir = Temp.CreateDirectory();

var vsDir = Path.Combine(testDir.Path, "vs");
Metadata(vsDir, new() { { "AspNetCoreAnalyzers", "9.0.0-preview.5.24306.11" } });
var vsAnalyzerPath = FakeDll(vsDir, @"AspNetCoreAnalyzers\analyzers\dotnet\cs", "Microsoft.AspNetCore.App.Analyzers");

// The suffix matches but there is no parent directory.
var sdkAnalyzerPath = @"\sdk\packs\Microsoft.AspNetCore.App.Ref\9.0.0-preview.7.24406.2\analyzers\dotnet\cs\Microsoft.AspNetCore.App.Analyzers.dll";

var resolver = new SdkAnalyzerAssemblyRedirectorCore(vsDir);
var redirected = resolver.RedirectPath(sdkAnalyzerPath);
AssertEx.Equal(vsAnalyzerPath, redirected);
}

[Fact]
public void TwoMajorVersions()
{
var testDir = Temp.CreateDirectory();

var vsDir = Path.Combine(testDir.Path, "vs");
Metadata(vsDir, new()
{
{ "AspNetCoreAnalyzers9", "9.0.0-preview.5.24306.11" },
{ "AspNetCoreAnalyzers10", "10.0.0-preview.5.24306.11" },
});
var vsAnalyzerPath9 = FakeDll(vsDir, @"AspNetCoreAnalyzers9\analyzers\dotnet\cs", "Microsoft.AspNetCore.App.Analyzers");
var vsAnalyzerPath10 = FakeDll(vsDir, @"AspNetCoreAnalyzers10\analyzers\dotnet\cs", "Microsoft.AspNetCore.App.Analyzers");

var resolver = new SdkAnalyzerAssemblyRedirectorCore(vsDir);
AssertEx.Equal(vsAnalyzerPath9, resolver.RedirectPath(@"Z:\sdk\packs\Microsoft.AspNetCore.App.Ref\9.0.0-preview.7.24406.2\analyzers\dotnet\cs\Microsoft.AspNetCore.App.Analyzers.dll"));
AssertEx.Equal(vsAnalyzerPath10, resolver.RedirectPath(@"Z:\sdk\packs\Microsoft.AspNetCore.App.Ref\10.0.0-preview.7.24406.2\analyzers\dotnet\cs\Microsoft.AspNetCore.App.Analyzers.dll"));
}

[Theory]
[InlineData("8.0.100", "9.0.0-preview.7.24406.2")]
[InlineData("9.1.100", "9.0.0-preview.7.24406.2")]
[InlineData("9.1.0-preview.5.24306.11", "9.0.0-preview.7.24406.2")]
[InlineData("9.0.100", "9.1.100")]
[InlineData("9.0.100", "10.0.100")]
[InlineData("9.9.100", "9.10.100")]
[InlineData("111.111.0", "1.1.0")]
[InlineData("1.1.0", "111.111.0")]
public void DifferentMajorMinorVersion(string a, string b)
{
var testDir = Temp.CreateDirectory();

var vsDir = Path.Combine(testDir.Path, "vs");
Metadata(vsDir, new() { { "AspNetCoreAnalyzers", a } });
FakeDll(vsDir, @$"AspNetCoreAnalyzers\analyzers\dotnet\cs", "Microsoft.AspNetCore.App.Analyzers");
var sdkAnalyzerPath = @$"Z:\Program Files\dotnet\sdk\packs\Microsoft.AspNetCore.App.Ref\{b}\analyzers\dotnet\cs\Microsoft.AspNetCore.App.Analyzers.dll";

var resolver = new SdkAnalyzerAssemblyRedirectorCore(vsDir);
var redirected = resolver.RedirectPath(sdkAnalyzerPath);
Assert.Null(redirected);
}

private static string FakeDll(string root, string subdir, string name)
{
var dllPath = Path.Combine(root, subdir, $"{name}.dll");
Directory.CreateDirectory(Path.GetDirectoryName(dllPath));
File.WriteAllText(dllPath, "");
return dllPath;
}

private static void Metadata(string root, Dictionary<string, string> versions)
{
var metadataFilePath = Path.Combine(root, "metadata.json");
Directory.CreateDirectory(Path.GetDirectoryName(metadataFilePath));
File.WriteAllText(metadataFilePath, JsonSerializer.Serialize(versions));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Workspaces.AnalyzerRedirecting;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

// Example:
// FullPath: "C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\8.0.8\analyzers\dotnet\System.Windows.Forms.Analyzers.dll"
// ProductVersion: "8.0.8"
// PathSuffix: "analyzers\dotnet"
using AnalyzerInfo = (string FullPath, string ProductVersion, string PathSuffix);

namespace Microsoft.VisualStudio.LanguageServices.ProjectSystem;

/// <summary>
/// See <see href="https://github.com/dotnet/sdk/blob/main/documentation/general/analyzer-redirecting.md"/>.
/// </summary>
[Export(typeof(IAnalyzerAssemblyRedirector))]
[method: ImportingConstructor]
[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
internal sealed class SdkAnalyzerAssemblyRedirector(SVsServiceProvider serviceProvider) : SdkAnalyzerAssemblyRedirectorCore(
GetInsertedAnalyzersDirectory(),
(IVsActivityLog)serviceProvider.GetService(typeof(SVsActivityLog)))
{
private static string? GetInsertedAnalyzersDirectory()
{
var enable = Environment.GetEnvironmentVariable("DOTNET_ANALYZER_REDIRECTING");
if (!"0".Equals(enable, StringComparison.OrdinalIgnoreCase) && !"false".Equals(enable, StringComparison.OrdinalIgnoreCase))
{
return Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"CommonExtensions\Microsoft\DotNet"));
Copy link
Member

Choose a reason for hiding this comment

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

Should this check if the folder is present first? Or we're trusting that nothing will try to use it before the File.Exists check doesn't find the metadata.json?

Copy link
Member Author

@jjonescz jjonescz Dec 22, 2025

Choose a reason for hiding this comment

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

we're trusting that nothing will try to use it before the File.Exists check doesn't find the metadata.json

Yes, in the current implementation, the directory path is not even stored anywhere else, so that File.Exists check should be enough I think.

}

return null;
}
}

/// <summary>
/// Core functionality of <see cref="SdkAnalyzerAssemblyRedirector"/> extracted for testing.
/// </summary>
internal class SdkAnalyzerAssemblyRedirectorCore : IAnalyzerAssemblyRedirector
{
private readonly IVsActivityLog? _log;

/// <summary>
/// Map from analyzer assembly name (file name without extension) to a list of matching analyzers.
/// </summary>
private readonly Lazy<ImmutableDictionary<string, List<AnalyzerInfo>>> _analyzerMap;

public SdkAnalyzerAssemblyRedirectorCore(string? insertedAnalyzersDirectory, IVsActivityLog? log = null)
{
_log = log;
_analyzerMap = new(() => CreateAnalyzerMap(insertedAnalyzersDirectory));
}

private ImmutableDictionary<string, List<AnalyzerInfo>> CreateAnalyzerMap(string? insertedAnalyzersDirectory)
{
if (insertedAnalyzersDirectory == null)
{
Log("Analyzer redirecting is disabled.");
return ImmutableDictionary<string, List<AnalyzerInfo>>.Empty;
}

var metadataFilePath = Path.Combine(insertedAnalyzersDirectory, "metadata.json");
if (!File.Exists(metadataFilePath))
{
Log($"File does not exist: {metadataFilePath}");
return ImmutableDictionary<string, List<AnalyzerInfo>>.Empty;
}

Dictionary<string, string>? versions;

try
{
versions = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(metadataFilePath));
}
catch (Exception ex)
{
Log($"Failed to read or parse metadata file '{metadataFilePath}'. {ex}", __ACTIVITYLOG_ENTRYTYPE.ALE_WARNING);
return ImmutableDictionary<string, List<AnalyzerInfo>>.Empty;
}

if (versions is null || versions.Count == 0)
{
Log($"Versions are empty: {metadataFilePath}", __ACTIVITYLOG_ENTRYTYPE.ALE_WARNING);
return ImmutableDictionary<string, List<AnalyzerInfo>>.Empty;
}

var builder = ImmutableDictionary.CreateBuilder<string, List<AnalyzerInfo>>(StringComparer.OrdinalIgnoreCase);

// Expects layout like:
// VsInstallDir\DotNetRuntimeAnalyzers\WindowsDesktopAnalyzers\analyzers\dotnet\System.Windows.Forms.Analyzers.dll
// ~~~~~~~~~~~~~~~~~~~~~~~ = topLevelDirectory
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ = analyzerPath

foreach (var topLevelDirectory in Directory.EnumerateDirectories(insertedAnalyzersDirectory))
Copy link
Member

Choose a reason for hiding this comment

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

Is there a way we can produce a file that produces all this up front so we don't need to search for binaries that ship in the product? This is having the user pay a cost for things we can absolutely determine because we insert these binaries.

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, sounds doable, I will look into that, thanks.

Copy link
Member Author

Choose a reason for hiding this comment

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

Done in 64ed67b with SDK counterpart in dotnet/sdk#52326.

{
var subsetName = Path.GetFileName(topLevelDirectory);

foreach (var analyzerPath in Directory.EnumerateFiles(topLevelDirectory, "*.dll", SearchOption.AllDirectories))
{
if (!analyzerPath.StartsWith(topLevelDirectory, StringComparison.OrdinalIgnoreCase))
{
// We can't continue, because computations in code below assume this.
Debug.Fail($"Analyzer path '{analyzerPath}' must start with '{topLevelDirectory}'.");
continue;
}

if (!versions.TryGetValue(subsetName, out var version))
Copy link
Member

Choose a reason for hiding this comment

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

It'd be nice if there was a comment what the versions JSON is or looks like. There's not a file I can look at right now so I'm guessing, but I would have assumed versioning was related to the individual DLL which is odd since this path isn't depending on that 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.

There is an example in the doc (which is linked in the doc comment of SdkAnalyzerAssemblyRedirector): https://github.com/dotnet/sdk/blob/main/documentation/general/analyzer-redirecting.md

Copy link
Member

Choose a reason for hiding this comment

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

Ah that's really helpful. How does versioning work in this design them? If we needed to have redirected versions for a 9.0 and 10.0, then there'd be two top level folders in the JSON with different names?

Copy link
Member Author

@jjonescz jjonescz Dec 22, 2025

Choose a reason for hiding this comment

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

If we needed to have redirected versions for a 9.0 and 10.0

That's intentionally unsupported. There is always only one SDK version inserted into VS anyway.

then there'd be two top level folders in the JSON with different names?

I guess that would technically work. I will add a test. But that won't happen in the way we currently generate the payload in the sdk repo.

{
continue;
}

var analyzerName = Path.GetFileNameWithoutExtension(analyzerPath);
var pathSuffix = analyzerPath.Substring(topLevelDirectory.Length + 1 /* slash */);
pathSuffix = Path.GetDirectoryName(pathSuffix);

AnalyzerInfo analyzer = new() { FullPath = analyzerPath, ProductVersion = version, PathSuffix = pathSuffix };

if (builder.TryGetValue(analyzerName, out var existing))
{
existing.Add(analyzer);
}
else
{
builder.Add(analyzerName, [analyzer]);
}
}
}

Log($"Loaded analyzer map ({builder.Count}): {insertedAnalyzersDirectory}");

return builder.ToImmutable();
}

public string? RedirectPath(string fullPath)
{
if (_analyzerMap.Value.TryGetValue(Path.GetFileNameWithoutExtension(fullPath), out var analyzers))
{
foreach (var analyzer in analyzers)
{
var directoryPath = Path.GetDirectoryName(fullPath);

// Note that both paths we compare here are normalized via netfx's Path.GetDirectoryName.
if (directoryPath.EndsWith(analyzer.PathSuffix, StringComparison.OrdinalIgnoreCase) &&
MajorAndMinorVersionsMatch(directoryPath, analyzer.PathSuffix, analyzer.ProductVersion))
{
return analyzer.FullPath;
}
}
}

return null;

static bool MajorAndMinorVersionsMatch(string directoryPath, string pathSuffix, string version)
{
// Find the version number in the directory path - it is in the directory name before the path suffix.
// Example:
// "C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\8.0.8\analyzers\dotnet\" = directoryPath
// ~~~~~~~~~~~~~~~~ = pathSuffix
// ~~~~~ = directoryPathVersion
// This can match also a NuGet package because the version number is at the same position:
// "C:\.nuget\packages\Microsoft.WindowsDesktop.App.Ref\8.0.8\analyzers\dotnet\"

var index = directoryPath.LastIndexOf(pathSuffix, StringComparison.OrdinalIgnoreCase);
if (index < 0)
{
return false;
}

var directoryPathVersion = Path.GetFileName(Path.GetDirectoryName(directoryPath.Substring(0, index)));
Copy link
Member

Choose a reason for hiding this comment

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

Make sure there's a test if somebody were to add a reference to Z:\analyzers\dotnet\Foo.dll or wherever, where the suffix does match but there is no parent directory.

Copy link
Member Author

@jjonescz jjonescz Dec 22, 2025

Choose a reason for hiding this comment

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

If the suffix matches, that's enough and it will be redirected, there is no need for it to have a parent directory. But I can add a test for it, thanks.


return AreVersionMajorMinorPartEqual(directoryPathVersion, version);
}

static bool AreVersionMajorMinorPartEqual(string version1, string version2)
{
var firstDotIndex = version1.IndexOf('.');
if (firstDotIndex < 0)
{
return false;
}

var secondDotIndex = version1.IndexOf('.', firstDotIndex + 1);
if (secondDotIndex < 0)
{
return false;
}

return 0 == string.Compare(version1, 0, version2, 0, secondDotIndex, StringComparison.OrdinalIgnoreCase);
}
}

private void Log(string message, __ACTIVITYLOG_ENTRYTYPE level = __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION)
{
_log?.LogEntry(
(uint)level,
"Roslyn" + nameof(SdkAnalyzerAssemblyRedirector),
message);
}
}
Loading