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

Improve MSBuildProjectLoader #33

Merged
merged 1 commit into from
Jul 30, 2018
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
151 changes: 151 additions & 0 deletions src/SlnGen.Build.Tasks.UnitTests/MSBuildProjectLoaderTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// Copyright (c) Jeff Kluge. All rights reserved.
//
// Licensed under the MIT license.

using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities.ProjectCreation;
using Shouldly;
using SlnGen.Build.Tasks.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace SlnGen.Build.Tasks.UnitTests
{
public class MSBuildProjectLoaderTests : TestBase
{
private const string MSBuildToolsVersion = "15.0";

[Fact]
public void ArgumentNullException_BuildEngine()
{
ArgumentNullException exception = Should.Throw<ArgumentNullException>(() =>
{
MSBuildProjectLoader unused = new MSBuildProjectLoader(globalProperties: null, toolsVersion: null, buildEngine: null);
});

exception.ParamName.ShouldBe("buildEngine");
}

[Fact]
public void BuildFailsIfError()
{
ProjectCreator dirsProj = ProjectCreator
.Create(GetTempFileName())
.Property("IsTraversal", "true")
.ItemInclude("ProjectFile", "does not exist")
.Save();

BuildEngine buildEngine = BuildEngine.Create();

MSBuildProjectLoader loader = new MSBuildProjectLoader(null, MSBuildToolsVersion, buildEngine);

loader.LoadProjectsAndReferences(new[] { dirsProj.FullPath });

buildEngine.Errors.ShouldHaveSingleItem().ShouldStartWith("The project file could not be loaded. Could not find file ");
}

[Fact]
public void GlobalPropertiesSetCorrectly()
{
Dictionary<string, string> expectedGlobalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["Property1"] = "1A836FEB3ABA43B183034DFDD5C4E375",
["Property2"] = "CEEC5C9FF0F344DAA32A0F545460EB2C"
};

ProjectCreator projectA = ProjectCreator
.Create(GetTempFileName())
.Save();

BuildEngine buildEngine = BuildEngine.Create();

MSBuildProjectLoader loader = new MSBuildProjectLoader(expectedGlobalProperties, MSBuildToolsVersion, buildEngine);

ProjectCollection projectCollection = loader.LoadProjectsAndReferences(new[] { projectA.FullPath });

projectCollection.GlobalProperties.ShouldBe(expectedGlobalProperties);
}

[Fact]
public void InvalidProjectsLogGoodInfo()
{
ProjectCreator projectA = ProjectCreator
.Create(GetTempFileName())
.Import(@"$(Foo)\foo.props")
.Save();

ProjectCreator dirsProj = ProjectCreator
.Create(GetTempFileName())
.Property("IsTraversal", "true")
.ItemInclude("ProjectFile", projectA.FullPath)
.Save();

BuildEngine buildEngine = BuildEngine.Create();

MSBuildProjectLoader loader = new MSBuildProjectLoader(null, MSBuildToolsVersion, buildEngine);

loader.LoadProjectsAndReferences(new[] { dirsProj.FullPath });

BuildErrorEventArgs errorEventArgs = buildEngine.ErrorEvents.ShouldHaveSingleItem();

errorEventArgs.Code.ShouldBe("MSB4019");
errorEventArgs.ColumnNumber.ShouldBe(3);
errorEventArgs.HelpKeyword.ShouldBe("MSBuild.ImportedProjectNotFound");
errorEventArgs.LineNumber.ShouldBe(3);
errorEventArgs.File.ShouldBe(projectA.FullPath);
}

[Fact]
public void ProjectReferencesWork()
{
ProjectCreator projectB = ProjectCreator
.Create(GetTempFileName())
.Save();

ProjectCreator projectA = ProjectCreator
.Create(GetTempFileName())
.ItemProjectReference(projectB)
.Save();

BuildEngine buildEngine = BuildEngine.Create();

MSBuildProjectLoader loader = new MSBuildProjectLoader(null, MSBuildToolsVersion, buildEngine);

ProjectCollection projectCollection = loader.LoadProjectsAndReferences(new[] { projectA.FullPath });

projectCollection.LoadedProjects.Select(i => i.FullPath).ShouldBe(new[] { projectA.FullPath, projectB.FullPath });
}

[Fact]
public void TraversalReferencesWork()
{
ProjectCreator projectB = ProjectCreator
.Create(GetTempFileName())
.Save();

ProjectCreator projectA = ProjectCreator
.Create(GetTempFileName())
.ItemProjectReference(projectB)
.Save();

ProjectCreator dirsProj = ProjectCreator
.Create(GetTempFileName())
.Property("IsTraversal", "true")
.ItemInclude("ProjectFile", projectA.FullPath)
.Save();

BuildEngine buildEngine = BuildEngine.Create();

MSBuildProjectLoader loader = new MSBuildProjectLoader(null, MSBuildToolsVersion, buildEngine);

ProjectCollection projectCollection = loader.LoadProjectsAndReferences(new[] { dirsProj.FullPath });

projectCollection.LoadedProjects.Select(i => i.FullPath).ShouldBe(
new[] { dirsProj.FullPath, projectA.FullPath, projectB.FullPath },
ignoreOrder: true);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MSBuild.ProjectCreation" Version="1.1.1" />
<PackageReference Include="MSBuild.ProjectCreation" Version="1.2.5" />
<PackageReference Include="Microsoft.Build" Version="15.7.179" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.Build.Framework" Version="15.7.179" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.Build.Locator" Version="1.0.13" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.7.2" />
<PackageReference Include="Shouldly" Version="3.0.0" />
<PackageReference Include="xunit" Version="2.3.1" />
Expand Down
11 changes: 2 additions & 9 deletions src/SlnGen.Build.Tasks.UnitTests/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,16 @@
//
// Licensed under the MIT license.

using Microsoft.Build.Locator;
using Microsoft.Build.Utilities.ProjectCreation;
using System;
using System.IO;

namespace SlnGen.Build.Tasks.UnitTests
{
public abstract class TestBase
public abstract class TestBase : MSBuildTestBase
{
public static readonly VisualStudioInstance CurrentVisualStudioInstance = MSBuildLocator.RegisterDefaults();

private readonly string _testRootPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

protected TestBase()
{
MSBuildPath = CurrentVisualStudioInstance.MSBuildPath;
}

public string TestRootPath
{
get
Expand Down
2 changes: 1 addition & 1 deletion src/SlnGen.Build.Tasks/ExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public static string ToFullPathInCorrectCase(this string str)

if (!File.Exists(fullPath))
{
throw new FileNotFoundException($"Could not find part of the path \"{fullPath}\"");
return str;
}

string filename = Path.GetFileName(fullPath);
Expand Down
37 changes: 28 additions & 9 deletions src/SlnGen.Build.Tasks/Internal/MSBuildProjectLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ internal sealed class MSBuildProjectLoader
/// </summary>
private const string ProjectReferenceItemName = "ProjectReference";

/// <summary>
/// The name of the environment variable that configures MSBuild to ignore eager wildcard evaluations (like \**)
/// </summary>
private const string MSBuildSkipEagerWildcardEvaluationsEnvironmentVariableName = "MSBUILDSKIPEAGERWILDCARDEVALUATIONREGEXES";

private readonly IBuildEngine _buildEngine;

/// <summary>
Expand Down Expand Up @@ -84,16 +89,30 @@ public MSBuildProjectLoader(IDictionary<string, string> globalProperties, string
/// <returns>A <see cref="ProjectCollection"/> object containing the loaded projects.</returns>
public ProjectCollection LoadProjectsAndReferences(IEnumerable<string> projectPaths)
{
// Create a ProjectCollection for this thread
ProjectCollection projectCollection = new ProjectCollection(_globalProperties)
// Store the current value of the environment variable that disables eager wildcard evaluations
string currentSkipEagerWildcardEvaluationsValue = Environment.GetEnvironmentVariable(MSBuildSkipEagerWildcardEvaluationsEnvironmentVariableName);

try
{
DefaultToolsVersion = _toolsVersion,
DisableMarkDirty = true, // Not sure but hoping this improves load performance
};
// Indicate to MSBuild that any item that has two wildcards should be evaluated lazily
Environment.SetEnvironmentVariable(MSBuildSkipEagerWildcardEvaluationsEnvironmentVariableName, @"\*{2}");

Parallel.ForEach(projectPaths, projectPath => { LoadProject(projectPath, projectCollection, _projectLoadSettings); });
// Create a ProjectCollection for this thread
ProjectCollection projectCollection = new ProjectCollection(_globalProperties)
{
DefaultToolsVersion = _toolsVersion,
DisableMarkDirty = true, // Not sure but hoping this improves load performance
};

return projectCollection;
Parallel.ForEach(projectPaths, projectPath => { LoadProject(projectPath, projectCollection, _projectLoadSettings); });

return projectCollection;
}
finally
{
// Restore the environment variable value
Environment.SetEnvironmentVariable(MSBuildSkipEagerWildcardEvaluationsEnvironmentVariableName, currentSkipEagerWildcardEvaluationsValue);
}
}

/// <summary>
Expand Down Expand Up @@ -186,12 +205,12 @@ private bool TryLoadProject(string path, string toolsVersion, ProjectCollection
_buildEngine.LogErrorEvent(new BuildErrorEventArgs(
subcategory: null,
code: null,
file: null,
file: path,
lineNumber: 0,
columnNumber: 0,
endLineNumber: 0,
endColumnNumber: 0,
message: $"Error loading project '{path}'. {e.Message}",
message: e.ToString(),
helpKeyword: null,
senderName: null));

Expand Down