Skip to content
Open
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
8 changes: 6 additions & 2 deletions src/RazorSdk/Tasks/FindAssembliesWithReferencesTo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@

namespace Microsoft.AspNetCore.Razor.Tasks
{
public class FindAssembliesWithReferencesTo : Task
[MSBuildMultiThreadableTask]
public class FindAssembliesWithReferencesTo : Task, IMultiThreadableTask
{
/// <inheritdoc/>
public TaskEnvironment TaskEnvironment { get; set; } = TaskEnvironment.Fallback;
Comment thread
OvesN marked this conversation as resolved.

[Required]
public ITaskItem[] TargetAssemblyNames { get; set; }

Expand Down Expand Up @@ -44,7 +48,7 @@ public override bool Execute()

var targetAssemblyNames = TargetAssemblyNames.Select(s => s.ItemSpec).ToList();

var provider = new ReferenceResolver((IReadOnlyList<string>)targetAssemblyNames, referenceItems);
var provider = new ReferenceResolver((IReadOnlyList<string>)targetAssemblyNames, referenceItems, TaskEnvironment);
try
{
var assemblyNames = provider.ResolveAssemblies();
Expand Down
25 changes: 22 additions & 3 deletions src/RazorSdk/Tasks/ReferenceResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Microsoft.Build.Framework;

namespace Microsoft.AspNetCore.Razor.Tasks
{
Expand All @@ -15,9 +16,25 @@ public class ReferenceResolver
private readonly HashSet<string> _mvcAssemblies;
private readonly IReadOnlyList<AssemblyItem> _assemblyItems;
private readonly Dictionary<AssemblyItem, Classification> _classifications;
private readonly TaskEnvironment _taskEnvironment = TaskEnvironment.Fallback;

public ReferenceResolver(IReadOnlyList<string> targetAssemblies, IReadOnlyList<AssemblyItem> assemblyItems)
public ReferenceResolver(
IReadOnlyList<string> targetAssemblies,
IReadOnlyList<AssemblyItem> assemblyItems)
: this(targetAssemblies, assemblyItems, null)
{
}

public ReferenceResolver(
IReadOnlyList<string> targetAssemblies,
IReadOnlyList<AssemblyItem> assemblyItems,
TaskEnvironment? taskEnvironment)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hm, it worries me here that we have the pattern of passing around environment, which makes things quite implicit - we discussed previously that we want to use tasks as a boundary and do the transforms there without passing the environment deeper into the call chain. Looking here, it seems like here it would mean that we change the AssemblyItem.Path to an AbsolutePath - I briefly checked and the AssemblyItem seems not that widely used, so it might be viable. What do you think @OvesN?

{
if (taskEnvironment != null)
{
_taskEnvironment = taskEnvironment;
}

_mvcAssemblies = new HashSet<string>(targetAssemblies, StringComparer.Ordinal);
_assemblyItems = assemblyItems;
_classifications = new Dictionary<AssemblyItem, Classification>();
Expand Down Expand Up @@ -103,12 +120,14 @@ protected virtual IReadOnlyList<AssemblyItem> GetReferences(string file)
{
try
{
if (!File.Exists(file))
var absoluteFilePath = !String.IsNullOrEmpty(file) ? _taskEnvironment.GetAbsolutePath(file) : file;

if (!File.Exists(absoluteFilePath))
{
throw new ReferenceAssemblyNotFoundException(file);
}

using var peReader = new PEReader(File.OpenRead(file));
using var peReader = new PEReader(File.OpenRead(absoluteFilePath));
if (!peReader.HasMetadata)
{
return Array.Empty<AssemblyItem>(); // not a managed assembly
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#nullable disable

using System.Reflection;
using Microsoft.AspNetCore.Razor.Tasks;
using Microsoft.Build.Framework;
using Moq;
using TaskItem = Microsoft.Build.Utilities.TaskItem;

namespace Microsoft.NET.Sdk.Razor.Test
{
public class FindAssembliesWithReferencesToMultiThreadingTest
{
[Fact]
public void GetReferences_RelativePath_ResolvesAgainstTaskEnvironmentProjectDirectory()
{
// The point of the migration: relative paths must be absolutized against

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please let's not reference "the migration" as it's unclear what that means outside of the context of the PR

// TaskEnvironment.ProjectDirectory instead of the process CWD. The file is placed
// in a temp directory distinct from CWD so pre-migration code would not find it.
using var temp = new TempDirectory();
const string fileName = "stub.dll";
File.WriteAllBytes(Path.Combine(temp.Path, fileName), new byte[] { 0 });
Directory.GetCurrentDirectory().Should().NotBe(temp.Path,
"test must run with CWD distinct from the temp dir so the migration is actually exercised");

var resolver = CreateExposingResolver(TaskEnvironment.CreateWithProjectDirectoryAndEnvironment(temp.Path));

resolver.CallGetReferences(fileName).Should().BeEmpty(
"the file exists at TaskEnvironment.ProjectDirectory; PEReader's BadImageFormatException is swallowed and an empty list returned");
}


[Fact]
public void Execute_PassesTaskEnvironmentToResolver_AndResolvesRelativeAssemblyItemSpecs()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should we also add a negative test?

{
// End-to-end wiring test: FindAssembliesWithReferencesTo must forward its
// TaskEnvironment to the ReferenceResolver so relative ItemSpecs on Assemblies
// are resolved against the project directory, not the process CWD.
using var temp = new TempDirectory();
const string fileName = "candidate.dll";
File.WriteAllBytes(Path.Combine(temp.Path, fileName), new byte[] { 0 });

var warnings = new List<BuildWarningEventArgs>();
var errors = new List<BuildErrorEventArgs>();
var buildEngine = new Mock<IBuildEngine>();
buildEngine.Setup(e => e.LogWarningEvent(It.IsAny<BuildWarningEventArgs>()))
.Callback<BuildWarningEventArgs>(warnings.Add);
buildEngine.Setup(e => e.LogErrorEvent(It.IsAny<BuildErrorEventArgs>()))
.Callback<BuildErrorEventArgs>(errors.Add);

var task = new FindAssembliesWithReferencesTo
{
BuildEngine = buildEngine.Object,
TaskEnvironment = TaskEnvironment.CreateWithProjectDirectoryAndEnvironment(temp.Path),
TargetAssemblyNames = new ITaskItem[] { new TaskItem("Microsoft.AspNetCore.Mvc") },
Assemblies = new ITaskItem[]
{
new TaskItem(fileName, new Dictionary<string, string>
{
["FusionName"] = "Candidate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
}),
},
};

task.Execute().Should().BeTrue();
errors.Should().BeEmpty();
warnings.Should().NotContain(w => w.Code == "RAZORSDK1007",
"the file is present under TaskEnvironment.ProjectDirectory; no not-found warning should be raised");
}

private static ExposingReferenceResolver CreateExposingResolver(TaskEnvironment env) =>
new(Array.Empty<string>(), Array.Empty<AssemblyItem>(), env);

private sealed class ExposingReferenceResolver : ReferenceResolver
{
public ExposingReferenceResolver(
IReadOnlyList<string> targetAssemblies,
IReadOnlyList<AssemblyItem> assemblyItems,
TaskEnvironment taskEnvironment)
: base(targetAssemblies, assemblyItems, taskEnvironment)
{
}

public IReadOnlyList<AssemblyItem> CallGetReferences(string file) => GetReferences(file);
}

private sealed class TempDirectory : IDisposable
{
public TempDirectory()
{
Path = System.IO.Path.Combine(
System.IO.Path.GetTempPath(),
nameof(FindAssembliesWithReferencesToMultiThreadingTest),
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path);
}

public string Path { get; }

public void Dispose()
{
try { Directory.Delete(Path, recursive: true); } catch { /* best effort */ }
}
}
}
}
Loading