Skip to content
Draft
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 @@ -574,14 +574,14 @@ protected virtual ModelFactoryProvider CreateModelFactoryCore(IEnumerable<InputM
// unsatisfied dependency, ...) so the message points at the actual problem.
var details = ExternalTypeReferenceResolver.GetFailureReason(externalProperties)
?? (string.IsNullOrEmpty(externalProperties.Package)
? "no package metadata was provided"
: string.IsNullOrEmpty(externalProperties.MinVersion)
? $"package '{externalProperties.Package}' was not found in the NuGet cache or any configured feed"
: $"package '{externalProperties.Package}' (>= {externalProperties.MinVersion}) was not found in the NuGet cache or any configured feed");
? "runtime type lookup failed and no NuGet package ID was provided. " +
"To resolve the type from NuGet, specify its package ID in @alternateType. " +
ExternalTypeReferenceResolver.PackageReferenceGuidance
: $"no resolution details are available for NuGet package '{externalProperties.Package}'");

CodeModelGenerator.Instance.Emitter.ReportDiagnostic(
"unsupported-external-type",
$"External type '{externalProperties.Identity}' could not be resolved: {details}.");
$"External type '{externalProperties.Identity}' could not be resolved: {details.TrimEnd('.')}.");

return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ namespace Microsoft.TypeSpec.Generator.Utilities
/// </remarks>
internal static class ExternalTypeReferenceResolver
{
public const string PackageReferenceGuidance =
"A ProjectReference alone cannot resolve @alternateType. Use a versioned NuGet PackageReference " +
"and, if versions are managed centrally, set the version there (for example, in a package override)";

// Per-generator cache state. Using ConditionalWeakTable means a new CodeModelGenerator instance
// (e.g. a fresh mock installed by the next test) starts with an empty cache automatically, and
// the entries are released when the generator is collected.
Expand Down Expand Up @@ -268,7 +272,8 @@ private static async Task<ResolutionResult> ResolveResultAsync(InputExternalType
: $" (>= {external.MinVersion})";
return CacheResult(state, key, new ResolutionResult(
null,
$"package '{external.Package}'{versionQualifier} is not present in package dependencies."));
$"no assembly was found in the project's resolved dependencies for NuGet package '{external.Package}'{versionQualifier}. " +
PackageReferenceGuidance));
}

// Pin every package in this package's dependency closure before loading it, so the resolving
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.TypeSpec.Generator.EmitterRpc;
using Microsoft.TypeSpec.Generator.Input;
using Microsoft.TypeSpec.Generator.Tests.Common;
using Microsoft.TypeSpec.Generator.Utilities;
Expand Down Expand Up @@ -69,6 +71,71 @@ public void TryResolve_ReturnsNullWhenPackageMissing()
Assert.IsNull(ExternalTypeReferenceResolver.TryResolve(external));
}

[TestCase(null, null)]
[TestCase("Test.Referenced.Project", "2.0.0")]
public async Task CreateCSharpType_ReportsHowToResolveProjectReference(string? package, string? minVersion)
{
const string projectName = "TestProject";
const string typeName = "Test.Referenced.Project.AlternateType";
var sourceDir = Path.Combine(_projectDir!, "src");
var dependencyDir = Directory.CreateDirectory(Path.Combine(_projectDir!, "Dependency"));
const string dependencyProject = """
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
</Project>
""";
File.WriteAllText(Path.Combine(dependencyDir.FullName, "Test.Referenced.Project.csproj"), dependencyProject);
File.WriteAllText(Path.Combine(sourceDir, $"{projectName}.csproj"), """
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Dependency/Test.Referenced.Project.csproj" />
</ItemGroup>
</Project>
""");

var generator = MockHelpers.LoadMockGenerator(
outputPath: _projectDir,
configuration: $"{{\"package-name\": \"{projectName}\"}}");
await GeneratedCodeWorkspace.AddPackageReferencesFromProject();
Assert.That(File.Exists(Path.Combine(sourceDir, "obj", "project.assets.json")), Is.True);

using var diagnosticStream = new MemoryStream();
using var emitter = new Emitter(diagnosticStream);
generator.SetupGet(g => g.Emitter).Returns(emitter);
var external = new InputExternalTypeMetadata(typeName, package, minVersion);
var inputType = InputFactory.Union([InputPrimitiveType.String], "ExternalUnion", external);

Assert.That(generator.Object.TypeFactory.CreateCSharpType(inputType), Is.Null);

diagnosticStream.Position = 0;
using var diagnostic = await JsonDocument.ParseAsync(diagnosticStream);
var parameters = diagnostic.RootElement.GetProperty("params");
var message = parameters.GetProperty("message").GetString();
Assert.Multiple(() =>
{
Assert.That(parameters.GetProperty("code").GetString(), Is.EqualTo("unsupported-external-type"));
Assert.That(parameters.GetProperty("severity").GetString(), Is.EqualTo("warning"));
Assert.That(message, Does.Contain(typeName));
Assert.That(message, Does.Contain("ProjectReference alone"));
Assert.That(message, Does.Contain("versioned NuGet PackageReference"));
Assert.That(message, Does.Contain("package override"));
if (package == null)
{
Assert.That(message, Does.Contain("specify its package ID in @alternateType"));
}
else
{
Assert.That(message, Does.Contain("no assembly was found in the project's resolved dependencies"));
Assert.That(message, Does.Contain($"NuGet package '{package}' (>= {minVersion})"));
}
});
}

[TestCase(false)]
[TestCase(true)]
public async Task TryResolve_LoadsTypeFromNuGetCache(bool isHosted)
Expand Down Expand Up @@ -98,7 +165,7 @@ public void TryResolve_HostedModeReportsUncachedPackage(string? minVersion)

Assert.IsNull(ExternalTypeReferenceResolver.TryResolve(external));
StringAssert.Contains(
"is not present in package dependencies.",
"no assembly was found in the project's resolved dependencies",
ExternalTypeReferenceResolver.GetFailureReason(external));
Assert.AreEqual(refsBefore, CodeModelGenerator.Instance.AdditionalMetadataReferences.Count);
Assert.That(Directory.EnumerateFileSystemEntries(_nugetCacheDir!), Is.Empty);
Expand All @@ -116,7 +183,7 @@ public async Task ResolveAllAsync_HostedModeReportsUncachedPackage()
await ExternalTypeReferenceResolver.ResolveAllAsync();

StringAssert.Contains(
"is not present in package dependencies.",
"no assembly was found in the project's resolved dependencies",
ExternalTypeReferenceResolver.GetFailureReason(external));
Assert.IsNull(ExternalTypeReferenceResolver.TryResolve(external));
Assert.That(Directory.EnumerateFileSystemEntries(_nugetCacheDir!), Is.Empty);
Expand All @@ -133,7 +200,7 @@ public void TryResolve_ReturnsNullForUndeclaredCachedPackage(bool isHosted)
var refsBefore = CodeModelGenerator.Instance.AdditionalMetadataReferences.Count;

Assert.IsNull(ExternalTypeReferenceResolver.TryResolve(external));
StringAssert.Contains("is not present in package dependencies.", ExternalTypeReferenceResolver.GetFailureReason(external));
StringAssert.Contains("no assembly was found in the project's resolved dependencies", ExternalTypeReferenceResolver.GetFailureReason(external));
Assert.AreEqual(refsBefore, CodeModelGenerator.Instance.AdditionalMetadataReferences.Count);
}

Expand Down Expand Up @@ -200,7 +267,7 @@ public async Task TryResolve_ReturnsNullForUnknownPackage()

Assert.IsNull(resolved);
StringAssert.Contains(
"is not present in package dependencies.",
"no assembly was found in the project's resolved dependencies",
ExternalTypeReferenceResolver.GetFailureReason(external),
"A missing package should be reported as a missing package.");
}
Expand Down
Loading