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
1 change: 1 addition & 0 deletions .github/memory/API_MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Repo-wide entry points and the formal public-API tracking rules. Layer-specific
| `dotnet test <test.csproj>` | Run a specific test project. |
| `dotnet run --file eng/generate-compiler-code.cs` | Regenerate Syntax/BoundNodes code. |
| `pwsh eng/validate-benchmarks.ps1 -configuration Release -ci` | Validate benchmark projects with BenchmarkDotNet Dry jobs; custom multi-job Razor harnesses use their explicit validation mode. Used by the correctness artifacts CI job. |
| `artifacts/bin/BuildBoss/<config>/net472/BuildBoss.exe -r <repo>/ -c <config> -p Roslyn.slnx` | Validate solutions, project files and build artifacts. Used by the correctness artifacts CI job and the bootstrap build. See `src/Tools/BuildBoss/README.md` for available checks and options. |
| `dotnet msbuild <proj> /t:UpdateXlf` | Refresh `.xlf` after `.resx` changes. |

Solution filters: `Roslyn.slnx` (full), `Compilers.slnf`, `Ide.slnf`, `Razor.slnf`.
Expand Down
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ stages:
/p:Configuration=Release
/p:PublishToMSDL=false

- script: $(Build.SourcesDirectory)\artifacts\bin\BuildBoss\Release\net472\BuildBoss.exe -r "$(Build.SourcesDirectory)/" -c Release -p Roslyn.slnx
- script: $(Build.SourcesDirectory)\artifacts\bin\BuildBoss\Release\net472\BuildBoss.exe -r "$(Build.SourcesDirectory)/" -c Release -p Roslyn.slnx --check-package-install
displayName: Validate Build Artifacts

- powershell: eng/validate-rules-missing-documentation.ps1 -ci
Expand Down
24 changes: 5 additions & 19 deletions src/Tools/BuildBoss/CompilerNuGetCheckerUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ private bool CheckPackages(TextWriter textWriter)
// https://github.com/dotnet/roslyn/issues/17864
allGood &= VerifyPackageCore(
textWriter,
FindNuGetPackage(Path.Combine(ArtifactsDirectory, "VSSetup", Configuration, "DevDivPackages"), "VS.Tools.Roslyn"),
SharedUtil.FindNuGetPackage(Path.Combine(ArtifactsDirectory, "VSSetup", Configuration, "DevDivPackages"), "VS.Tools.Roslyn"),
excludeFunc: relativeFileName =>
PathComparer.Equals(relativeFileName, "csc.exe") ||
PathComparer.Equals(relativeFileName, "Icon.png") ||
Expand All @@ -158,7 +158,7 @@ private bool CheckPackages(TextWriter textWriter)

allGood &= VerifyPackageCore(
textWriter,
FindNuGetPackage(Path.Combine(ArtifactsDirectory, "packages", Configuration, "Shipping"), "Microsoft.Net.Compilers.Toolset.Arm64"),
SharedUtil.FindNuGetPackage(Path.Combine(ArtifactsDirectory, "packages", Configuration, "Shipping"), "Microsoft.Net.Compilers.Toolset.Arm64"),
(@"tasks\net472", GetProjectOutputDirectory("csc-arm64", "net472")),
(@"tasks\net472", GetProjectOutputDirectory("vbc-arm64", "net472")),
(@"tasks\net472", GetProjectOutputDirectory("csi", "net472")),
Expand All @@ -167,7 +167,7 @@ private bool CheckPackages(TextWriter textWriter)

allGood &= VerifyPackageCore(
textWriter,
FindNuGetPackage(Path.Combine(ArtifactsDirectory, "packages", Configuration, "Shipping"), "Microsoft.Net.Compilers.Toolset.Framework"),
SharedUtil.FindNuGetPackage(Path.Combine(ArtifactsDirectory, "packages", Configuration, "Shipping"), "Microsoft.Net.Compilers.Toolset.Framework"),
(@"tasks\net472", GetProjectOutputDirectory("csc", "net472")),
(@"tasks\net472", GetProjectOutputDirectory("vbc", "net472")),
(@"tasks\net472", GetProjectOutputDirectory("csi", "net472")),
Expand All @@ -176,7 +176,7 @@ private bool CheckPackages(TextWriter textWriter)

allGood &= VerifyPackageCore(
textWriter,
FindNuGetPackage(Path.Combine(ArtifactsDirectory, "packages", Configuration, "Shipping"), "Microsoft.Net.Compilers.Toolset"),
SharedUtil.FindNuGetPackage(Path.Combine(ArtifactsDirectory, "packages", Configuration, "Shipping"), "Microsoft.Net.Compilers.Toolset"),
excludeFunc: relativeFileName =>
relativeFileName.StartsWith(@"tasks\netcore\bincore\Microsoft.DiaSymReader.Native", PathComparison) ||
relativeFileName.StartsWith(@"tasks\netcore\bincore\Microsoft.CodeAnalysis.ExternalAccess.RazorCompiler.dll", PathComparison) ||
Expand Down Expand Up @@ -358,7 +358,7 @@ private static IEnumerable<PackagePart> GetPartsInFolder(Package package, string
/// <param name="textWriter"></param>
private bool CheckExternalApis(TextWriter textWriter)
{
var packageFilePath = FindNuGetPackage(Path.Combine(ArtifactsDirectory, "VSSetup", Configuration, "DevDivPackages"), "VS.ExternalAPIs.Roslyn");
var packageFilePath = SharedUtil.FindNuGetPackage(Path.Combine(ArtifactsDirectory, "VSSetup", Configuration, "DevDivPackages"), "VS.ExternalAPIs.Roslyn");
var allGood = true;

// This tracks the packages which are included in separate packages. Hence they don't need to
Expand Down Expand Up @@ -421,20 +421,6 @@ void verifyFolder(string folderRelativeName)
}
}

private string FindNuGetPackage(string directory, string partialName)
{
var regex = $@"{partialName}.\d.*\.nupkg";
var file = Directory
.EnumerateFiles(directory, "*.nupkg")
.Where(filePath =>
{
var fileName = Path.GetFileName(filePath);
return Regex.IsMatch(fileName, regex);
})
.SingleOrDefault();
return file ?? throw new Exception($"Unable to find unique '{partialName}' in '{directory}'");
}

private string FindVsix(string fileName)
{
fileName = fileName + ".vsix";
Expand Down
241 changes: 241 additions & 0 deletions src/Tools/BuildBoss/PackageInstallCheckerUtil.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
// 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.IO;
using System.Xml.Linq;

namespace BuildBoss
{
/// <summary>
/// Verifies our NuGet packages can actually be consumed: that a customer can add one to a project
/// and compile against its API.
///
/// The generated project calls into the package it installs, so the build proves the package
/// really surfaces a usable reference rather than just restoring successfully.
///
/// Everything here uses SDK style projects and PackageReference. That covers .NET Framework as well
/// because an SDK style project can target net472. Legacy packages.config is deliberately not
/// tested: install would require us to hand author the Reference / HintPath / Import edits that
/// Visual Studio normally makes, which would test our emulation of NuGet rather than NuGet itself.
///
/// This is the one checker that spawns processes and needs network access, so it is opt in via the
/// --check-package-install switch rather than running on every BuildBoss invocation.
/// </summary>
internal sealed class PackageInstallChecker : ICheckerUtil
{
/// <summary>
/// The packages validated by this checker, each paired with source that consumes it. The source
/// is compiled but never run, and uses fully qualified names so it works on any target framework.
/// </summary>
private static readonly (string PackageId, string SourceCode)[] s_packages = new[]
{
("Microsoft.CodeAnalysis",
@"internal static class PackageUsage
{
internal static void Use()
{
Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(""class C { }"").GetRoot();
Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText("""").GetRoot();
}
}"),

("Microsoft.CodeAnalysis.Workspaces.MSBuild",
@"internal static class PackageUsage
{
internal static void Use()
{
using (var workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create())
{
var solution = workspace.OpenSolutionAsync(""Test.sln"");
}
}
}"),
};

internal string RepositoryDirectory { get; }
internal string ArtifactsDirectory { get; }
internal string Configuration { get; }

internal PackageInstallChecker(string repositoryDirectory, string artifactsDirectory, string configuration)
{
RepositoryDirectory = repositoryDirectory;
ArtifactsDirectory = artifactsDirectory;
Configuration = configuration;
}

public bool Check(TextWriter textWriter)
{
try
{
var packagesDirectory = Path.Combine(ArtifactsDirectory, "packages", Configuration, "Shipping");
if (!Directory.Exists(packagesDirectory))
{
textWriter.WriteLine($"Package directory '{packagesDirectory}' does not exist; was the build run with -pack?");
return false;
}

// Build outside the repository so the generated projects behave like a customer's: no
// Directory.Build.props, central package management, or NuGet.config walked up into.
var scratchDirectory = Path.Combine(Path.GetTempPath(), "RoslynPackageInstallValidation");
var globalPackagesDirectory = Path.Combine(scratchDirectory, ".nuget");
PrepareScratchDirectory(scratchDirectory, packagesDirectory, globalPackagesDirectory);

var allGood = true;
foreach (var (packageId, sourceCode) in s_packages)
{
var packageFilePath = SharedUtil.FindNuGetPackage(packagesDirectory, packageId);
var packageVersion = SharedUtil.GetNuGetPackageVersion(packageFilePath, packageId);

foreach (var (name, targetFramework) in s_targetFrameworks)
{
allGood &= CheckPackage(textWriter, scratchDirectory, packageId, sourceCode, packageVersion, name, targetFramework);
}
}

return allGood;
}
catch (Exception ex)
{
textWriter.WriteLine($"Error verifying: {ex.Message}");
return false;
}
}

/// <summary>
/// Installs the package into a freshly generated project that compiles against it. Returns false,
/// having written the details, if any step misbehaves.
/// </summary>
private static bool CheckPackage(
TextWriter textWriter,
string scratchDirectory,
string packageId,
string sourceCode,
string packageVersion,
string targetFrameworkName,
string targetFramework)
{
var projectDirectory = Path.Combine(scratchDirectory, $"{packageId}.{targetFrameworkName}");
var projectFilePath = Path.Combine(projectDirectory, "PackageValidation.csproj");

Directory.CreateDirectory(projectDirectory);
File.WriteAllText(projectFilePath, GenerateProjectFile(targetFramework), SharedUtil.Encoding);
File.WriteAllText(Path.Combine(projectDirectory, "PackageUsage.cs"), sourceCode, SharedUtil.Encoding);

var context = $"{packageId} ({targetFrameworkName})";

if (!RunDotnetAndReport(textWriter, $"{context}: install", $"add package {packageId} --version {packageVersion}", projectDirectory))
{
return false;
}

// The source calls into the package, so this only succeeds if the package really surfaced a
// usable reference for this target framework. --disable-build-servers keeps the compiler
// server from holding the scratch directory's assemblies open, which would block the delete
// at the start of the next run.
return RunDotnetAndReport(textWriter, $"{context}: build", "build --disable-build-servers", projectDirectory);
}

private static bool RunDotnetAndReport(TextWriter textWriter, string description, string arguments, string workingDirectory)
{
var result = ProcessUtil.Run("dotnet", arguments, workingDirectory);
if (result.Succeeded)
{
return true;
}

textWriter.WriteLine($"{description}: 'dotnet {arguments}' failed with exit code {result.ExitCode}");
textWriter.WriteLine(result.Output);

return false;
}

/// <summary>
/// Creates the scratch directory the generated projects build in.
/// </summary>
private void PrepareScratchDirectory(string scratchDirectory, string packagesDirectory, string globalPackagesDirectory)
{
if (Directory.Exists(scratchDirectory))
{
Directory.Delete(scratchDirectory, recursive: true);
}

Directory.CreateDirectory(scratchDirectory);

// RestorePackagesPath outranks both the NUGET_PACKAGES environment variable the CI job sets
// and the globalPackagesFolder in the generated NuGet.config, so it is what actually pins
// restore to the throwaway folder.
File.WriteAllText(
Path.Combine(scratchDirectory, "Directory.Build.props"),
$"""
<Project>
<PropertyGroup>
<RestorePackagesPath>{globalPackagesDirectory}</RestorePackagesPath>
</PropertyGroup>
</Project>
""",
SharedUtil.Encoding);

File.WriteAllText(Path.Combine(scratchDirectory, "NuGet.config"), GenerateNuGetConfig(packagesDirectory, globalPackagesDirectory), SharedUtil.Encoding);
}

/// <summary>
/// Builds a NuGet.config exposing the just built packages alongside the repository's own feeds.
/// The local feed supplies our packages and their Roslyn dependencies; the repository feeds
/// supply third party dependencies such as Microsoft.Build.Framework.
/// </summary>
private string GenerateNuGetConfig(string packagesDirectory, string globalPackagesDirectory)
{
var sources = new List<XElement>
{
new XElement("add", new XAttribute("key", "package-install-validation-local"), new XAttribute("value", packagesDirectory))
};

var repositoryConfigPath = Path.Combine(RepositoryDirectory, "NuGet.config");
var repositoryConfig = XDocument.Load(repositoryConfigPath);
foreach (var element in repositoryConfig.Root.Element("packageSources").Elements("add"))
{
sources.Add(new XElement(element));
}

var document = new XDocument(
new XElement("configuration",
// A dedicated packages folder, wiped with the scratch directory, keeps this honest.
// Sharing the machine's global folder would let an already extracted package of the
// same version silently stand in for the one we just built.
new XElement("config",
new XElement("add", new XAttribute("key", "globalPackagesFolder"), new XAttribute("value", globalPackagesDirectory))),
new XElement("packageSources",
new XElement("clear"),
sources),
new XElement("disabledPackageSources",
new XElement("clear"))));

return document.ToString();
}

private static string GenerateProjectFile(string targetFramework) =>
$"""
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>{targetFramework}</TargetFramework>
<OutputType>Library</OutputType>
</PropertyGroup>
</Project>
""";

/// <summary>
/// The target frameworks a customer could consume these packages from, paired with a name safe
/// to use in a directory. The .NET Core case is spelled as a property the SDK defines so it
/// always matches whichever SDK is running rather than needing to be updated here.
/// </summary>
private static readonly (string Name, string TargetFramework)[] s_targetFrameworks = new[]
{
("net472", "net472"),
("netcore", "net$(BundledNETCoreAppTargetFrameworkVersion)"),
};

}
}
20 changes: 18 additions & 2 deletions src/Tools/BuildBoss/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,18 @@ private static bool MainCore(string[] args)
string repositoryDirectory = null;
string configuration = "Debug";
string primarySolution = null;
bool checkPackageInstall = false;
List<string> solutionFiles;

var options = new OptionSet
{
{ "r|root=", "The repository root", value => repositoryDirectory = value },
{ "c|configuration=", "Build configuration", value => configuration = value },
{ "p|primary=", "Primary solution file name (which contains all projects)", value => primarySolution = value },
// The trailing ':' makes the value optional, so a bare --check-package-install turns the
// check on. Without it Mono.Options silently discards an explicit value and
// --check-package-install=false would still run the check.
{ "check-package-install:", "Verify our NuGet packages can be installed", value => checkPackageInstall = value is null || bool.Parse(value) },
Comment on lines +47 to +50

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Copilot chose to make this optional given it touches network and such; we could also remove the switch if that seems easier.

};

if (configuration is not "Debug" and not "Release")
Expand Down Expand Up @@ -79,7 +84,7 @@ private static bool MainCore(string[] args)
solutionFiles = Directory.EnumerateFiles(repositoryDirectory, "*.sln").ToList();
}

return Go(repositoryDirectory, configuration, primarySolution, solutionFiles);
return Go(repositoryDirectory, configuration, primarySolution, solutionFiles, checkPackageInstall);
}

private static string FindRepositoryRoot(string startDirectory)
Expand All @@ -93,7 +98,7 @@ private static string FindRepositoryRoot(string startDirectory)
return dir;
}

private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames)
private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames, bool checkPackageInstall)
{
var allGood = true;
foreach (var solutionFileName in solutionFileNames)
Expand All @@ -109,6 +114,11 @@ private static bool Go(string repositoryDirectory, string configuration, string
allGood &= ProcessStructuredLog(artifactsDirectory, configuration);
allGood &= ProcessOptProf(repositoryDirectory, artifactsDirectory, configuration);

if (checkPackageInstall)
{
allGood &= ProcessPackageInstall(repositoryDirectory, artifactsDirectory, configuration);
}

if (!allGood)
{
Console.WriteLine("Failed");
Expand Down Expand Up @@ -171,5 +181,11 @@ private static bool ProcessOptProf(string repositoryDirectory, string artifactsD
var util = new OptProfCheckerUtil(repositoryDirectory, artifactsDirectory, configuration);
return CheckCore(util, $"OptProf inputs");
}

private static bool ProcessPackageInstall(string repositoryDirectory, string artifactsDirectory, string configuration)
{
var util = new PackageInstallChecker(repositoryDirectory, artifactsDirectory, configuration);
return CheckCore(util, "NuGet package install");
}
}
}
Loading