Skip to content
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
32 changes: 32 additions & 0 deletions src/Tasks/Microsoft.NET.Build.Tasks/CheckForTargetInAssetsFile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Build.Framework;
using NuGet.ProjectModel;
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.NET.Build.Tasks
{
public class CheckForTargetInAssetsFile : TaskBase
{
[Required]
public string AssetsFilePath { get; set; }

[Required]
public string TargetFrameworkMoniker { get; set; }

public string RuntimeIdentifier { get; set; }


protected override void ExecuteCore()
{
LockFile lockFile = new LockFileCache(BuildEngine4).GetLockFile(AssetsFilePath);

var nugetFramework = NuGetUtils.ParseFrameworkName(TargetFrameworkMoniker);

lockFile.GetTargetAndThrowIfNotFound(nugetFramework, RuntimeIdentifier);
}
}
}
39 changes: 28 additions & 11 deletions src/Tasks/Microsoft.NET.Build.Tasks/LockFileExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,33 @@ namespace Microsoft.NET.Build.Tasks
{
internal static class LockFileExtensions
{
public static LockFileTarget GetTargetAndThrowIfNotFound(this LockFile lockFile, NuGetFramework framework, string runtime)
{
LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);

if (lockFileTarget == null)
{
string frameworkString = framework.DotNetFrameworkName;
string targetMoniker = string.IsNullOrEmpty(runtime) ?
frameworkString :
$"{frameworkString}/{runtime}";

string message;
if (string.IsNullOrEmpty(runtime))
{
message = string.Format(Strings.AssetsFileMissingTarget, lockFile.Path, targetMoniker, framework.GetShortFolderName());
}
else
{
message = string.Format(Strings.AssetsFileMissingRuntimeIdentifier, lockFile.Path, targetMoniker, framework.GetShortFolderName(), runtime);
}

throw new BuildErrorException(message);
}

return lockFileTarget;
}

public static ProjectContext CreateProjectContext(
this LockFile lockFile,
NuGetFramework framework,
Expand All @@ -28,17 +55,7 @@ public static ProjectContext CreateProjectContext(
throw new ArgumentNullException(nameof(framework));
}

LockFileTarget lockFileTarget = lockFile.GetTarget(framework, runtime);

if (lockFileTarget == null)
{
string frameworkString = framework.DotNetFrameworkName;
string targetMoniker = string.IsNullOrEmpty(runtime) ?
frameworkString :
$"{frameworkString}/{runtime}";

throw new BuildErrorException(Strings.AssetsFileMissingTarget, lockFile.Path, targetMoniker, framework.GetShortFolderName(), runtime);
}
var lockFileTarget = lockFile.GetTargetAndThrowIfNotFound(framework, runtime);

LockFileTargetLibrary platformLibrary = lockFileTarget.GetLibrary(platformLibraryName);
bool isFrameworkDependent = platformLibrary != null && (!isSelfContained || string.IsNullOrEmpty(lockFileTarget.RuntimeIdentifier));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@
<DependentUpon>Strings.resx</DependentUpon>
</EmbeddedResource>
<Compile Update="Resources\Strings.Designer.cs">
<DesignTime>true</DesignTime>
<AutoGen>true</AutoGen>
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Strings.resx</DependentUpon>
</Compile>
</ItemGroup>
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/Tasks/Microsoft.NET.Build.Tasks/Resources/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
<value>Assets file '{0}' not found. Run a NuGet package restore to generate this file.</value>
</data>
<data name="AssetsFileMissingTarget" xml:space="preserve">
<value>Assets file '{0}' doesn't have a target for '{1}'. Ensure you have restored this project for TargetFramework='{2}' and RuntimeIdentifier='{3}'.</value>
<value>Assets file '{0}' doesn't have a target for '{1}'. Ensure you have included '{2}' in the TargetFrameworks for your project.</value>
</data>
<data name="AssetsFilePathNotRooted" xml:space="preserve">
<value>Assets file path '{0}' is not rooted. Only full paths are supported.</value>
Expand Down Expand Up @@ -297,4 +297,7 @@
<data name="UnsupportedTargetFrameworkVersion" xml:space="preserve">
<value>The current .NET SDK does not support targeting {0} {1}. Either target {0} {2} or lower, or use a version of the .NET SDK that supports {0} {1}.</value>
</data>
<data name="AssetsFileMissingRuntimeIdentifier" xml:space="preserve">
<value>Assets file '{0}' doesn't have a target for '{1}'. Ensure you have included '{2}' in the TargetFrameworks for your project. You may also need to include '{3}' in your project's RuntimeIdentifiers.</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,24 @@ Copyright (c) .NET Foundation. All rights reserved.

<UsingTask TaskName="Microsoft.NET.Build.Tasks.ResolvePackageDependencies"
AssemblyFile="$(MicrosoftNETBuildTasksAssembly)" />
<UsingTask TaskName="Microsoft.NET.Build.Tasks.CheckForTargetInAssetsFile"
AssemblyFile="$(MicrosoftNETBuildTasksAssembly)" />

<!-- The condition on this target causes it to be skipped during design-time builds if
the restore operation hasn't run yet. This is to avoid displaying an error in
the Visual Studio error list when a project is created before NuGet restore has
run and created the assets file. -->
<Target Name="RunResolvePackageDependencies"
Condition=" '$(DesignTimeBuild)' != 'true' Or Exists('$(ProjectAssetsFile)')">

<!-- Verify that the assets file has a target for the right framework. Otherwise, if we restored for the
wrong framework, we'd end up finding no references to pass to the compiler, and we'd get a ton of
compile errors. -->
<CheckForTargetInAssetsFile
AssetsFilePath="$(ProjectAssetsFile)"
TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
RuntimeIdentifier="$(RuntimeIdentifier)" />

<ResolvePackageDependencies
ProjectPath="$(MSBuildProjectFullPath)"
ProjectAssetsFile="$(ProjectAssetsFile)"
Expand Down
50 changes: 40 additions & 10 deletions test/Microsoft.NET.Build.Tests/GivenThatWeWantToBuildALibrary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
using System.Runtime.CompilerServices;
using Xunit.Abstractions;
using Microsoft.NET.TestFramework.ProjectConstruction;
using NuGet.ProjectModel;
using NuGet.Common;
using Newtonsoft.Json.Linq;

namespace Microsoft.NET.Build.Tests
{
Expand Down Expand Up @@ -591,19 +594,46 @@ public void It_fails_to_build_if_targeting_a_higher_framework_than_is_supported(
[Fact]
public void It_passes_ridless_target_to_compiler()
{
var testAsset = _testAssetsManager
.CopyTestAsset("AppWithLibrary", "RidlessLib")
.WithSource()
.Restore(Log, relativePath: "TestLibrary");
var runtimeIdentifier = EnvironmentInfo.GetCompatibleRid("netcoreapp2.0");

var libraryProjectDirectory = Path.Combine(testAsset.TestRoot, "TestLibrary");
var fullPathProjectFile = new BuildCommand(Log, libraryProjectDirectory).FullPathProjectFile;
var testProject = new TestProject()
{
Name = "CompileDoesntUseRid",
TargetFrameworks = "netcoreapp2.0",
RuntimeIdentifier = runtimeIdentifier,
IsSdkProject = true
};

var testAsset = _testAssetsManager.CreateTestProject(testProject, testProject.Name)
.WithProjectChanges(project =>
{
// Set property to disable logic in Microsoft.NETCore.App package that will otherwise cause a failure
// when we remove everything under the rid-specific targets in the assets file
var ns = project.Root.Name.Namespace;
project.Root.Element(ns + "PropertyGroup")
.Add(new XElement(ns + "EnsureNETCoreAppRuntime", false));
})
.Restore(Log, testProject.Name);

var buildCommand = new BuildCommand(Log, testAsset.TestRoot, testProject.Name);

// Test that compilation doesn't depend on any rid-specific assets by removing them from the assets file after it's been restored
var assetsFilePath = Path.Combine(buildCommand.GetBaseIntermediateDirectory().FullName, "project.assets.json");

JObject assetsContents = JObject.Parse(File.ReadAllText(assetsFilePath));
foreach (JProperty target in assetsContents["targets"])
{
if (target.Name.Contains("/"))
{
// This is a target element with a RID specified, so remove all its contents
target.Value = new JObject();
}
}
string newContents = assetsContents.ToString();
File.WriteAllText(assetsFilePath, newContents);

// compile should still pass with unknown RID because references are always pulled
// from RIDLess target
var buildCommand = new MSBuildCommand(Log, "Compile", fullPathProjectFile);
buildCommand
.Execute("/p:RuntimeIdentifier=unkownrid")
.Execute()
.Should()
.Pass();
}
Expand Down